销毁活动时保存值,然后还原它



ActivityA有两个按钮。这些按钮中的每一个都将打开ActivityB但分别具有不同的片段。两个片段都包含一个EditText 。如果我想在ActivityB时切换片段,我需要返回ActivityA并按另一个按钮。

现在我想做的是在切换片段或关闭应用程序时保存在每个EditText中输入的值,并在重新打开片段时以正确的EditText重新填充值。

当我打开SettingActivity然后回来时,它似乎是自己做的,但如果我破坏了活动,它就不会这样做。最后,我希望片段像我离开时一样重新打开。谢谢。

您必须保存值,然后还原它们。一个好方法是共享首选项。
1-保存:

  SharedPreferences sharedpreferences = getSharedPreferences("mypref", Context.MODE_PRIVATE);
 SharedPreferences.Editor editor = sharedpreferences.edit();
        editor.putString("var1", edittext.getText().toString());
        editor.commit();

2-恢复:

String s = sharedpreferences.getString("var1","DEF");

使用共享首选项来存储值 当您调用新活动时,请使用此

 SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
                    SharedPreferences.Editor editor = settings.edit();
                    editor.putString("userEmail", youredittext.getText().toString());
                    editor.commit();

当您想检索任何活动中的存储值时,请像这样获取它

SharedPreferences getPrefs = PreferenceManager
            .getDefaultSharedPreferences(getBaseContext());
   String mUserEmail = getPrefs.getString("userEmail", null);

是的,如果你有更多的字段,或者你想保持数据的关系......在这种情况下,你也可以使用SQLite。以下是关于SQLite的帖子

http://www.kpblogs.com/mobile-development/sqlite-android-tutorial-with-crud-operations/

相关内容

最新更新