0

我有一个名为 currentFile 的文件对象。当 currentFile 已更改并且用户尝试打开一个新文件而不先保存时,将显示一个 Save 对话框,如果单击 Yes,则保存 currentFile。我遇到的问题是,当我启动一个新 Activity 并按下 Android 后退按钮时,currentFile 设置为 null,因此更改文件,尝试打开一个新文件会导致 NullPointerException。如何跨活动持久化 currentFile?

4

3 回答 3

3

有几种方法可以做到这一点,具体取决于您想要做什么,您应该权衡什么更适合您的需求,一种方法是使用附加值将变量值传递给另一个活动

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

另一种方法是在您的应用程序上下文中设置一个变量,创建一个从 Application 扩展的类,并且您可以使用它从任何活动中获取该引用

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

我能想到的最后一个是使用 SharedPreferences,将变量存储为可用于任何活动的键/值对......

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

问候!

于 2013-07-01T19:29:05.823 回答
0

您也可以使用Application类来执行此操作。我发现它比使用捆绑包和意图更容易使用。

要访问您的应用程序类,只需在任何活动中调用 getApplicationContext,并将其转换为您的类类型,该类类型扩展 Application 如下所示:

public class MyActivity extends Activity{

    public void onCreate(Bundle bundle){
        MyApplicationClass app = (MyApplicationClass)this.getApplication();
    }
}
于 2013-07-01T19:27:43.130 回答
0

您可以使用Intents&来执行此操作Extras

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

然后在您的新活动中:

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

这里有一些阅读Intents:http: //developer.android.com/reference/android/content/Intent.html

于 2013-07-01T19:25:39.440 回答