Save phrase in Textview when closing the app

Asked

Viewed 117 times

0

I have many phrases that will be displayed in a Textview, while I’m clicking on the button will appear new phrases, I wonder if the phrase that is in the Indice 0, when you click it goes to Indice 1, if I close the app and open again I want you to stay where you were when closing, in Indice 1

  • Sharedpreferences

  • 1

    See if that’s the answer of this question or of that help you.

  • Sharedprefences? Sorry, could you specify better? because I’m used to taking an Edittext value and then saving it from there, I never did with already defined Array phrases

2 answers

0

To help follow example using Sharedpreferences I took from a project of mine:


        public static final String MY_PREFS = "MEUAPP";
        SharedPreferences preferences = getSharedPreferences(MY_PREFS, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();
        editor.clear(); // No teu caso pode retirar o clear, eh que eu precisava que começasse vazio
        editor.apply();
        // Utilizo esse objeto collegeData pq estou pegando a informação de um retorno json, mas vc pode utilizar um TextView ali
        editor.putInt("id", Integer.parseInt(collegeData.getString("id")));
        editor.putString("nome", collegeData.getString("nome"));

To get the info you saved earlier just declare Sharedpreferences again in the Activity you want.


        public static final String MY_PREFS = "MEUAPP";
        TextView name = (TextView) header.findViewById(R.id.nome_menu);

        SharedPreferences prefs = getSharedPreferences(MY_PREFS, MODE_PRIVATE);
        name.setText(prefs.getString("nome", null));

0

You need to overwrite the method onSaveInstanceState(Bundle savedInstanceState), in this method you must put the value of your variable that stores the index, follow the example:

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
  super.onSaveInstanceState(savedInstanceState);
  savedInstanceState.putInt("MeuIndice", suaPropriedadeQueArmazenaOIndice);
}

In onCreate, you can recover the data, whenever application returns it goes back to the onCreate method, follow the example:

@Override
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.telainicial);

        suaPropriedadeQueArmazenaOIndice = savedInstanceState.getInt("MeuIndice");
    }
  • is giving error, when button to run, says the application stopped, will not be missing onRestoreInstanceState?

Browser other questions tagged

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