简体   繁体   中英

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?

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!

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

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();
    }
}

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