Conditional Change of Activity

Asked

Viewed 62 times

0

Hello, I have a problem, I want to create a conditional on an Activity, inside a button, to open another Activity in my app.

But how would that parole?

My app has buttons in main Activity that leads to other activityies. One of these activityies is a registration, where the user fills in some data in Editexts and saves them, I used Sharedpreferences to Save this data.

//Exemplo
SharedPreferences anonacpref = getSharedPreferences("anonac", Context.MODE_PRIVATE);
SharedPreferences.Editor edanonac = anonacpref.edit();
edanonac.putString("anonac_texto", anonactxt.getText().toString());
edanonac.commit();

Anyway, I would like that when the data were already saved, when the user pressed the button in main Activity it was taken to another Activity instead of being taken to the database completion Activity.

how do I test if you already have something saved in Sharedpreferences?

1 answer

1


SharedPreferences anonacpref = getSharedPreferences("anonac", Context.MODE_PRIVATE);
String texto = anonacpref.getString("anonac_texto", null);
if (texto != null) {
    System.out.println("Já preenchido com: " + texto);
} else {
    System.out.println("Texto não encontrado em shared preferences.");
}

The second parameter of getString() is the default value to be returned if you do not find the "anonac_texto" in the Shared preferences file. In case I am using null.

  • Thank you for your help, Piovezan. I understood that in the code you posted, you are saving the value saved in Shared preferences in a variable of type string, but if the data were saved, using Shared preferences, in an Activity and then stored in the variable in that same Activity, can I use this variable as a parameter in another Activity? If yes, how do I do it?

  • No. You search for Shared preferences in one Activity, and in another Activity search for Shared preferences again. If you want to avoid code duplicity, create a class that reads specific fields from Shared preferences.

  • Could you give me an example of code?

  • See the Sharedpreference class (no s at the end) of this tutorial and used in the Mainactivity and Secondactivity classes.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.