How to save temporary data on Android?

How to save some temporary data so that when you close the application all data is gone? I tried sharedPreferences but it seems that the data still exists when I open the app again.

I've heard that you can save data to some cache memory, but I really don't want the data to go missing if the memory gets full while the app is still running. Maybe I should go with some globals? Not that I know how I can get this to work.

My simple app, which is a "game," opens and closes actions when you take it one step further. It's basically a game filled with silly pictures ^^. Things that were done in one action need to 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. Hope you understand what I'm talking about.

Any ideas on how I can store some information that is also readily available when you need it.

+3


source to share


3 answers


Use global variables.

Before you onCreate

define variables like:

int i;

or String s = "myString"



Then you can get / change them in any function.

Hope I helped :)

+5


source


You can use globals and then use Intent to pass them from activity to activity. To do this, you use this:

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

      



and get it in next action

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

      

+2


source


Hi, you are a good fit for storing temporary data in sharedPreferences

. This way you can update the insert and delete all game information accordingly. If you need to delete data after closing the game, just delete sharedPreferences

in the circle of life onDestroy()

;

@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 understand it, you don't know the lifecycle of your activity. This article explains how to use them.

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

+1


source







All Articles