[英]Android: How can I retain the state of an object on back button Action bar and back button of device
I have ActivityA and ActivityB. 我有ActivityA和ActivityB。 ActivityB is called from ActivityA.
从ActivityA调用ActivityB。
I wanted to retain the object of ActivityA, when I press back button of ActionBar or back button of device. 当我按下ActionBar的后退按钮或设备的后退按钮时,我想保留ActivityA的对象。
I have created a Singleton object to save my object and to get my object. 我创建了一个Singleton对象来保存我的对象并获取我的对象。
onPause() I am saving the object and onResume() method I am getting the object. onPause()我正在保存对象,而onResume()方法正在获取对象。
My problem here is the behaviour is different, the object that I get when back button of Action (in ActivityB) is different from the object that I get when back button of back button is clicked. 我的问题是行为不同,在ActionB的后退按钮(在ActivityB中)获得的对象与在单击后退按钮的后退按钮时获得的对象不同。
Here is the code: 这是代码:
protected void onPause() {
//resetSort();
super.onPause();
MySingleton.getInstance().setMyObject(myObject);
}
@Override
protected void onResume() {
super.onResume();
myObject = MySingleton.getInstance().getMyObject();
}
Here is my manifest file. 这是我的清单文件。
<activity
android:name=".ActivityA"
android:configChanges="orientation|keyboardHidden|screenSize"
android:label="@string/app_name"
>
</activity>
<activity
android:name=".ActivityB"
android:configChanges="orientation|keyboardHidden|screenSize"
android:label="@string/app_name" >
</activity>
Code from ActivityB: 来自ActivityB的代码:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
Any solution is appreciated. 任何解决方案表示赞赏。 Thanks
谢谢
The most reliable way is to use SharedPreferences . 最可靠的方法是使用SharedPreferences 。 It's both thread safe and remains even if your app is killed off.
它既是线程安全的,而且即使您的应用程序被杀死也仍然保留。
Google's Storage Options guide is also definitely worth a look if you haven't had a chance to review it yet. 如果您还没有机会查看Google的《 存储选项》指南,那么它也绝对值得一看。
To save a String you would use: 要保存一个字符串,您可以使用:
String str = "abc";
getSharedPreferences("filename", Context.MODE_PRIVATE).edit().putString("String Name", str).commit();
And then to retrieve it: 然后检索它:
String str = getSharedPreferences("filename", Context.MODE_PRIVATE).getString("String Name", "default string")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.