RapsFan1981
RapsFan1981

Reputation: 1197

How can I persist a variable across Activities?

I have a File object called currentFile. When currentFile has been changed and the user attempts to open a new file without saving first a Save dialog is presented and if Yes is clicked currentFile is saved. The problem I'm having is that when I start a new Activity and press the Android back button, currentFile is set to null so changing the file, attempting to open a new one results in a NullPointerException. How can I persist currentFile across Activities?

Upvotes: 0

Views: 273

Answers (3)

Martin Cazares
Martin Cazares

Reputation: 13705

There's several ways to do this, depending on what you want to do you should put on a balance what's better for your needs, one way is using extras to pass the variable value to another activity

Bundle extras = new Bundle();
extras.putString(key, value);
Intent intent = new Intent("your.activity");
intent.putExtras(extras);
startActivity(intent);

Another approach is to set a variable in your application context, creating a class that extends from Application and which reference you will be able to get from any activity using

YorApplicationClass app = (YorApplicationClass)getApplication();
app.getYourVariable();

And the last i can think of is using SharedPreferences, storing variables as key/value pairs that can be used for any activity...

            SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
            Editor edit = pref.edit();
            edit.putString(key, value);
            edit.commit();

            //Any activity
            SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
            pref.getString(key, defValue);

Regards!

Upvotes: 3

William Morrison
William Morrison

Reputation: 11006

You could also do this using the Application class. I find it easier to work with than using bundles and intents.

To access your application class, just call getApplicationContext in any activity, and cast it to your class type which extends Application like so:

public class MyActivity extends Activity{

    public void onCreate(Bundle bundle){
        MyApplicationClass app = (MyApplicationClass)this.getApplication();
    }
}

Upvotes: 0

BlackHatSamurai
BlackHatSamurai

Reputation: 23483

You can do this using Intents & Extras.

String yourFileName = "path/to/your/file"; 
Intent intent = new Intent(currentActivity, newActivity.class);
intent.putExtra("FileName", yourFileName);
startActivity(intent);

Then in your new activity:

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

Here is some reading on Intents: http://developer.android.com/reference/android/content/Intent.html

Upvotes: 0

Related Questions