0

I want my app to have unique ID combined from integer number and iteration of it, also i want to make it unique every time it starts.

For example

If it first time start with zer,increment it after just before finish, and start with new walue, in this example 1.

I'm trying to make it via sharedPrefs but the checking Toast show the same value (0) why is that?

Here is my code :

public final String SHARED_PREFS_NAME = "dowolna";
private SharedPreferences prefs;
static int valueYouWant;


onCreate(...) {
    .
    .
    .

     prefs =  getSharedPreferences(SHARED_PREFS_NAME, Context.MODE_PRIVATE);
         valueYouWant = prefs.getInt("lol", 0); 
         Toast.makeText(getApplicationContext(), String.valueOf(valueYouWant), Toast.LENGTH_SHORT).show();

    .
    .
    .
}

and then

@Override
protected void onDestroy() {
    super.onDestroy();
    SharedPreferences.Editor edit = prefs.edit();
    edit.putInt("lol", valueYouWant++);
    edit.commit();
}
morgano
  • 17,210
  • 10
  • 45
  • 56
user3310467
  • 45
  • 1
  • 5

1 Answers1

0

Try to do it in onPause not in onDestroy. Its not necessary that it would be called when the activity is finishing. onPause is sure to be called. If you read the documentation of onDestroy, it says:

Note: do not count on this method being called as a place for saving data! For example, if an activity is editing data in a content provider, those edits should be committed in either onPause() or onSaveInstanceState(Bundle), not here.

If you see this question Activity OnDestroy never called? , the answer here says:

onDestroy() is called only when system is low on resources(memory, cpu time and so on) and makes a decision to kill your activity/application or when somebody calls finish() on your activity.

So, its not necessary that onDestroy will be called. You can check inside onPause if activity is finishing by using isFinishing() method.

Community
  • 1
  • 1
Shobhit Puri
  • 25,769
  • 11
  • 95
  • 124