简体   繁体   中英

How to storesome data after activity is destroyed

I am creating a calculator application, when my activity is sent to background and then brought to front.The result in it becomes zero. How can i save the data nd retrive it next time hen activity is recreated.

Use SharedPreferences like :

SharedPreferences preferences = null;
SharedPreferences.Editor editor = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    preferences = PreferenceManager.getDefaultSharedPreferences(this);
}

in onDestory() write :

@Override
protected void onDestroy() {
    // TODO Auto-generated method stub
    super.onDestroy();
    editor = preferences.edit();
    editor.putInt(YOUR_KEY, YOUR_VALUE);
    editor.commit();
}

and in onStart() write :

@Override
protected void onStart() {
    // TODO Auto-generated method stub
    super.onStart();
    int result = preferences.getInt(YOUR_KEY, YOUR_VALUE);
}

Hope this will help you

For that specific case, you want to use the Activity lifecycle methods onSaveInstanceState and onRestoreInstanceState . Override both those methods, and then save the necessary data in onSaveInstanceState . In the onCreate or the onRestoreInstanceState check for the existence of the saved data and then restore it to the right place.

Note: you can use preferences or a database as well, but those are generally to be used for data that should last more than a single background/restore cycle. The onSaveInstanceState / onRestoreInstanceState methods are specifically for the case where an Activity gets sent to the background and then restored later.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM