How do I save temporary data on android?

拟墨画扇 提交于 2019-12-23 13:20:31

问题


How can I save some temporary data so that when I close the application all the data is gone? I've tried sharedPreferences but it seems that the data is still there when I open up the application once again.

I've heard that you can save data to some cache memory, but I really don't want the data to be gone if the memory gets "filled" when the app is still up and running. Maybe I should go with some global variables? Not that I know how I could get that to work.

My simple app, which is a "game", opens up and closes activities when you go one step further. It's basically a game filled with stupid pictures ^^. Stuff that has been done in one activity should be saved somewhere, So if i go back I can load the data and make it look like it was before the activity was closed. I hope you understand what I'm saying..

Any ideas how I could store some information that is also easy accessible when you need it.


回答1:


Use global variables.

Before onCreate define variables like:

int i; or String s = "myString"

Then you can access/change them in any function.

Hope I helped :)




回答2:


You could use global variables and then use Intent to pass them from activity to activity. To do that, you use this:

Intent intent = new Intent(getBaseContext(), MYourActivity.class);
intent.putExtra("variableName", value);
startActivity(intent)

and to get it in the next activity

Bundle extras = getIntent().getExtras();
if (extras != null) {
    String value = extras.getString("new_variable_name");
}



回答3:


Hi you're approach is right for saving temp data in to the sharedPreferences. In this way you could update inset and delete all information about the game in the proper way. If you need to delete data after you close the game just erase sharedPreferences on the onDestroy() life circle;

@override
public void onDestroy()
{
    super.onDestroy();
    SharedPreferences myPrefs = this.getSharedPreferences("examlePrefs");
    myPrefs.edit().remove("example");
    myPrefs.edit().clear(); 
    myPrefs.edit().commit();    
}

Or please use.

@override
public void onStop()
{
    super.onStop();
    SharedPreferences myPrefs = this.getSharedPreferences("examlePrefs");
    myPrefs.edit().remove("example");
    myPrefs.edit().clear(); 
    myPrefs.edit().commit();    
}

As i can understand you do not know lifecycle of the activity.So this article will explain how to use them.

http://developer.android.com/training/basics/activity-lifecycle/index.html



来源:https://stackoverflow.com/questions/25294879/how-do-i-save-temporary-data-on-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!