Philip
Philip

Reputation: 47

Changes to TextView lost after onPause() method

I have an activity with a simple TextView showing a number. With buttons, I add or remove value 1 from the number (and from a local variable int points);

The problem is:

If I add 1 to the number and then I open the Settings activity (in the code I don't call the finish() method so the main activity doesn't call the onDestroy() method), or if I press the Home button, when I return to the main activity the number shown (and the int points variable) are shown as they had never been changed.

On the other hand, if I modify the number and then pass the values with an Intent to another copy of the main activity, the values are stored correctly and the changes are shown even after pressing

The code in mainActivity that sets the points (in onResume() )

// Set POINTS

    Points = (TextView) findViewById(R.id.Points);

    if( getIntent().getExtras() != null) //get intent
    {
        points = getIntent().getExtras().getInt("points");
        Points.setText(String.valueOf(points));
    }
    else
    {
        points = Integer.parseInt((String)(Points.getText()));
    }

The code in MainActivity that sends the Intent to another MainActivity:

Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("points", points);
startActivity(toMulti);
overridePendingTransition(R.anim.anim_in, R.anim.anim_out);
finish();

The code in MainActivity that sends the Intent to Settings:

Intent toSettings = new Intent(this, SettingsSingle.class);
startActivity(toSettings);

The buttons code:

 public void plus1(View view)
{
    points = Integer.parseInt((String)(Points.getText()));
    points = points + 1;
    Points.setText(String.valueOf(points));
}

Upvotes: 1

Views: 1195

Answers (1)

Marcus
Marcus

Reputation: 6717

You can should persist your TextView value onPause(); and recreate it onResume();. This can be done using SharedPreference as below.

@Override
public void onPause() {
    super.onPause();  // Always call the superclass method first

    String yourStringValues = yourTextView.getText().toString();

    // We need an Editor object to make preference changes.
    // All objects are from android.context.Context
    SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
    SharedPreferences.Editor editor = settings.edit();
    editor.putString("yourKey", yourStringValue);

    // Commit the edits!
    editor.commit();
}

And when you resume your Activity

@Override
public void onResume() {
    super.onResume();  // Always call the superclass method first

    // Restore preferences
    SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
    String yourRetrievedStringValue = settings.getString("yourKey", "");
    TextView yourTextView = findViewById(R.id.yourTextViewId);
    yourTextView.setText(yourRetrievedStringValue);

}

Upvotes: 1

Related Questions