Cómo hacer que la aplicación vaya a otra página si no se ejecuta por primera vez

Tengo RegisterPage y LoginPage . Cuando se ejecute la aplicación, comprobará si la aplicación se ejecuta por primera vez o no en RegisterPage . Si se ejecuta por primera vez y no se hace clic en el button guardar, se RegisterPage en RegisterPage . Si se ejecuta en segundo lugar pero el botón de guardar nunca se hace clic, permanecerá en RegisterPage también. De lo contrario, irá a LoginPage .

Aquí mi código actualizado

Registro

 appGetFirstTimeRun(); boolean clicked=false; buttonSave.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { clicked=true; int appCurrentBuildVersion = BuildConfig.VERSION_CODE; SharedPreferences appPreferences = getSharedPreferences("MyAPP", 0); appPreferences.edit().putInt("app_second_time", appCurrentBuildVersion).apply(); String name = editTextName.getText().toString(); String pass = editTextPassword.getText().toString(); String confirm = editTextConfirm.getText().toString(); if ((editTextName.getText().toString().trim().length() == 0) || (editTextPassword.getText().toString().trim().length() == 0) || (editTextConfirm.getText().toString().trim().length() == 0)) { Toast.makeText(getApplicationContext(), "Field cannot be null", Toast.LENGTH_LONG).show(); } else { insertData(name, pass, imageUri); // insert to SQLite Intent intent = new Intent(MainActivity.this, AddMonthlyExpenses.class); intent.putExtra("name", name); startActivity(intent); } } }); private int appGetFirstTimeRun() { //Check if App Start First Time SharedPreferences appPreferences = getSharedPreferences("MyAPP", 0); int appCurrentBuildVersion = BuildConfig.VERSION_CODE; int appLastBuildVersion = appPreferences.getInt("app_first_time", 0); if (appLastBuildVersion == appCurrentBuildVersion && clicked) { Intent intent = new Intent(MainActivity.this,LoginPage.class); startActivity(intent); return 1; } else { appPreferences.edit().putInt("app_first_time", appCurrentBuildVersion).apply(); if (appLastBuildVersion == 0) { Toast.makeText(getApplicationContext(), "First time", Toast.LENGTH_SHORT).show(); return 0; //es la primera vez } else { return 2; //es una versión nueva } } } 

El problema es cuando hago clic en el botón Guardar y salgo de la aplicación. Cuando ejecuto la aplicación de nuevo todavía en el RegisterPage, no en LoginPage.

Haga clic en el botón Comprobar después de insertar datos en SQLite, para que pueda confirmar que sus datos se han guardado correctamente y puede continuar con la siguiente pantalla.

Encontrar mis comentarios en el código a continuación y editar su código: –

 public class Register extends AppCompatActivity { Button buttonSave; boolean clicked=false;//remove this @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_register); appGetFirstTimeRun();//call this method here buttonSave=(Button)findViewById(R.id.button); buttonSave.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { clicked=true;//remove this int appCurrentBuildVersion = BuildConfig.VERSION_CODE; SharedPreferences appPreferences = getSharedPreferences("MyAPP", 0); appPreferences.edit().putInt("app_second_time", appCurrentBuildVersion).apply(); String name = editTextName.getText().toString(); String pass = editTextPassword.getText().toString(); String confirm = editTextConfirm.getText().toString(); if ((editTextName.getText().toString().trim().length() == 0) || (editTextPassword.getText().toString().trim().length() == 0) || (editTextConfirm.getText().toString().trim().length() == 0)) { Toast.makeText(getApplicationContext(), "Field cannot be null", Toast.LENGTH_LONG).show(); } else { insertData(name, pass, imageUri); // insert to SQLite appPreferences.edit().putBoolean("btn_clicked", true).apply();//add this line Intent intent = new Intent(Register.this, AddMonthlyExpenses.class); intent.putExtra("name", name); startActivity(intent); } } }); } private int appGetFirstTimeRun() { //Check if App Start First Time SharedPreferences appPreferences = getSharedPreferences("MyAPP", 0); int appCurrentBuildVersion = BuildConfig.VERSION_CODE; int appLastBuildVersion = appPreferences.getInt("app_first_time", 0); boolean is_btn_click=appPreferences.getBoolean("btn_clicked",false);//add this line if ((appLastBuildVersion == appCurrentBuildVersion) && is_btn_click) { //edit this line like this Intent intent = new Intent(Register.this,LoginPage.class); startActivity(intent); return 1; } else { appPreferences.edit().putInt("app_first_time", appCurrentBuildVersion).apply(); if (appLastBuildVersion == 0) { Toast.makeText(getApplicationContext(), "First time", Toast.LENGTH_SHORT).show(); return 0; //es la primera vez } else { return 2; //es una versión nueva } } } } 

Dependiendo de SharedPreferences , así como de la variable SharePreferences , puede depender de SharePreferences pero no de la variable, ya que en cada ejecución se establece el valor de clic en false.

1) Guardar la versión actual de preferencia cuando se hace clic en el botón

 appPreferences.edit().putInt("app_first_time", appCurrentBuildVersion).apply(); 

2) guardar el valor de clic de preferencia cuando se hace clic en el botón

 appPreferences.edit().putBoolean("clicked", true).apply(); 

Ahora dentro de su appGetFirstTimeRun() el valor de la versión y SharedPreferences clic en SharedPreferences

 int appLastBuildVersion = appPreferences.getInt("app_first_time", 0); boolean clicked = appPreferences.getBoolean("clicked", false); 

También debe cambiar el valor de las preferencias compartidas al hacer clic en el botón Guardar. Entonces, sólo la próxima vez que abra el método appGetFirstTimeRun app, cargará la página de inicio de sesión.

En usted btnSalve el oyente del tecleo donde usted está comenzando la intención para la actividad apenas antes de startActivity añada este código

 int appCurrentBuildVersion = BuildConfig.VERSION_CODE; SharedPreferences appPreferences = getSharedPreferences("MyAPP", 0); appPreferences.edit().putInt("app_first_time", appCurrentBuildVersion).apply(); 

En el inicio de onCreate(); Método, call checkStages();

En el final del método buttonSave.onClick() , llame a Prefs.putStage(this, 1); Seguido de checkStages();

 /*Prefs.getStage(this) default value is 0*/ public void checkStages() { switch(Prefs.getStage(this)) { case 1: //Login Page startActivity(new Intent(this, LoginPage.class)); finish(); break; default: break; } } 

Esta es la muestra de la plantilla de aplicaciones para Android que utilizo, para escribir cualquiera de mis aplicaciones de Android.

Puedes obtener la clase Prefs de este proyecto

Agrega este código a tu pantalla de bienvenida

  SharedPreferences wmbPreference = PreferenceManager.getDefaultSharedPreferences(context); boolean isFirstRun = wmbPreference.getBoolean("FIRSTRUN", false); if (!isFirstRun) { startActivity(new Intent(context,RegirstorActivity.class)); }else{ startActivity(new Intent(context,LoginActivty.class)); } 

Así que básicamente decidirá ¿Es la primera vez (usuario registrado) o no, después de la actualización de registro SharedPreferences

Su está usando la variable del tecleo para identificar si el botón se chasquea o no pero cuando usted existe de la aplicación y otra vez entonces chasca valor reajustado a falso así que en vez de ahorrar valor en la variable del tecleo usted puede utilizar preferencia compartida para ahorrar valor verdadero o falso en tecleo del botón Y obtener el valor de la preferencia compartida para comprobar

Al hacer clic en el botón Guardar

  appPreferences.edit().putInt("app_second_time", appCurrentBuildVersion).apply(); 

Intente usar el siguiente método getter y setter personalizado.

 private static SharedPreferences getInstance(Context context) { context.getSharedPreferences("MY_APP", Context.MODE_PRIVATE); return sharedPreferences; } public boolean getAppStatus(Context context) { return getInstance(context).getString("FIRST_TIME", false); } public void setAppStatus(Context context, boolean status) { getInstance(context).edit().putString("FIRST_TIME", status).commit(); } 

Ahora, cuando por primera vez cuando llame a getAppStatus () o en caso de que el usuario no ha hecho clic en el botón Guardar una sola vez. Se devolverá falso. Puede actualizar el valor de la variable "FIRST_TIME" cuando el usuario hace clic en el botón de guardar en true. Por lo tanto, la validación, si el usuario ha interactuado con la página del registro o no.

 @Override public void onClick(View v) { if(v.getId()==R.id.save_button) setAppStatus(context,true); } 

Creo que esta puede ser la respuesta. En su código, la variable clicked boolean no se almacena en las preferencias compartidas, pero está comprobando la condición dentro de appGetFirstTimeRun () (el botón no se puede hacer clic en el segundo lanzamiento, pero su condición debe ser cierta), por lo que cambie el código agregando this line appPreferences.edit().putBoolean("first_run", true).apply(); En buttonSave clicklistener y luego agregue esta línea clicked = appPreferences.getBoolean("first_run", false); En la función appGetFirstTimeRun() y el código completo sería.

 appGetFirstTimeRun(); boolean clicked=false; buttonSave.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int appCurrentBuildVersion = BuildConfig.VERSION_CODE; SharedPreferences appPreferences = getSharedPreferences("MyAPP", 0); appPreferences = appPreferences.edit().putBoolean("first_run", true).apply(); //***Add this **** appPreferences.edit().putInt("app_second_time", appCurrentBuildVersion).apply(); String name = editTextName.getText().toString(); String pass = editTextPassword.getText().toString(); String confirm = editTextConfirm.getText().toString(); if ((editTextName.getText().toString().trim().length() == 0) || (editTextPassword.getText().toString().trim().length() == 0) || (editTextConfirm.getText().toString().trim().length() == 0)) { Toast.makeText(getApplicationContext(), "Field cannot be null", Toast.LENGTH_LONG).show(); } else { insertData(name, pass, imageUri); // insert to SQLite Intent intent = new Intent(MainActivity.this, AddMonthlyExpenses.class); intent.putExtra("name", name); startActivity(intent); } } }); private int appGetFirstTimeRun() { //Check if App Start First Time SharedPreferences appPreferences = getSharedPreferences("MyAPP", 0); int appCurrentBuildVersion = BuildConfig.VERSION_CODE; int appLastBuildVersion = appPreferences.getInt("app_first_time", 0); clicked = appPreferences.getBoolean("first_run", false); //*** Add this *** if (appLastBuildVersion == appCurrentBuildVersion && clicked) { Intent intent = new Intent(MainActivity.this,LoginPage.class); startActivity(intent); return 1; } else { appPreferences.edit().putInt("app_first_time", appCurrentBuildVersion).apply(); if (appLastBuildVersion == 0) { Toast.makeText(getApplicationContext(), "First time", Toast.LENGTH_SHORT).show(); return 0; //es la primera vez } else { return 2; //es una versión nueva } } } 
  //Use shared preference to save. SharedPreferences preferedName=getSharedPreferences("firstrun", Activity.MODE_PRIVATE); SharedPreferences.Editor editor = preferedName.edit(); editor.putboolean("firstrun",value); editor.apply(); editor.commit(); //and to retrive. SharedPreferences preferedName=getSharedPreferences("firstrun", Activity.MODE_PRIVATE); boolean rstate =preferedName.getString("firstrun",false); 

Compruebe si "rstste" es falso show register page else mostrar la página de inicio de sesión.

  • SharedPreferences lee valores antiguos
  • Cómo burlar una SharedPreferences usando Mockito
  • SharedPreferences no se actualiza
  • Ciclo de vida de Android SharedPreference
  • No se puede poner doble SharedPreferences
  • Lectura de preferencias compartidas
  • Hacer que una actividad aparezca sólo una vez, cuando se inicia la aplicación
  • Android Almacenamiento interno VS Preferencias compartidas
  • Preferencias compartidas vs base de datos
  • ¿Por qué preferences.getString ("key", "DEFAULT") devuelve siempre "DEFAULT"?
  • SharedPreferences no guarda valor
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.