Close app and reopen Continue read text

70 views Asked by At

This is simple code with multi text in one textview,

int stringIdList[] = {R.string.text1, R.string.text2, R.string.text3, R.string.text4};
    int stringListCounter = 0;
    TextView text1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

       Button next = (Button) findViewById(R.id.next1);
        Button previous = (Button) findViewById(R.id.pre1);
        text1 = (TextView) findViewById(R.id.textView1);
        next.setOnClickListener(this);
        previous.setOnClickListener(this);

    @Override
    public void onClick(View v) {
          int id = v.getId();
          if(id == R.id.next1 && stringListCounter < stringIdList.length - 1) {
                stringListCounter++;

              } else if (id == R.id.pre1 && stringListCounter > 0) {
                stringListCounter--;
              }
              text1.setText(stringIdList[stringListCounter]);  
            }

My problem :when I the close app and again reopen the app I want Continue last text that I read before close apps but when close and reopen app begin first text now.

1

There are 1 answers

2
Vaizadoo On BEST ANSWER

U should use SharedPreference class to save your text index.

@Override
public void onPause() {
    super.onPause();

    SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(getActivity());
    pref.edit().putInt("stringListCounter", stringListCounter).commit();
}

@Override
public void onResume() {
    super.onResume();
    SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(getActivity());
    stringListCounter = pref.getInt("stringListCounter", 0);
}