Save sentence in TextView when closing the app

0

I have many sentences that will be displayed in a TextView, whereas I will click on the button and there will be new sentences, I would like to know if the phrase that is in index 0, when clicking it is to index 1, if I close the app and open again I want you to stay where you left to close, in index 1

    
asked by anonymous 16.10.2017 / 19:11

2 answers

0

To help follow example using SharedPreferences that I got 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 that you have previously saved, 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));

    
21.10.2017 / 16:34
0

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

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

In OnCreate, you can retrieve the data, whenever application returns it 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");
    }
    
21.10.2017 / 17:38