gpt4 book ai didi

java - 无法在android中保存实例状态

转载 作者:行者123 更新时间:2023-12-01 04:27:04 25 4
gpt4 key购买 nike

在我的应用程序中,我尝试使用 onSaveInstanceState 中的 putSerialized 方法保存 ArrayList 状态。并在onCreate和onRestoreInstanceState中恢复它。在我的应用程序中,如果没有保存该对象的实例,它将根据互联网数据创建。但我一直尝试测试这个解决方案ArrayList开始从网络下载。谁能帮我吗?

public class Activity extends SherlockActivity {

ListView listView;
SlidingMenu slidingMenu;
ArrayList<HashMap<String, String>> newsList = null;
String url = "/////here_my_url////";

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setTitle(R.string.news_vatican);
listView = (ListView) findViewById(R.id.newslist);

slidingMenu = new SlidingMenu(this);
slidingMenu.setMode(SlidingMenu.LEFT);
slidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
slidingMenu.setFadeDegree(0.35f);
slidingMenu.attachToActivity(this, SlidingMenu.SLIDING_CONTENT);
slidingMenu.setMenu(R.layout.slidingmenu);
slidingMenu.setBehindOffset(150);

if (savedInstanceState != null){
newsList = (ArrayList<HashMap<String, String>>) savedInstanceState.getSerializable("list");
Log.e("Activity", "RESTORING");
} else {
Log.e("Activity", "PARSING NEW");
JSONParser parser = new JSONParser(this);
parser.execute(url);
try {
newsList = parser.get();
} catch (InterruptedException e) {
e.printStackTrace();
Log.e("Activity", "Failed to get newslist");
} catch (ExecutionException e) {
e.printStackTrace();
Log.e("Activity", "Failed to get newslist");

}

}


listView.setAdapter(new NewsAdapter(getApplicationContext(), newsList));

}

@Override
protected void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putSerializable("list", newsList);
super.onSaveInstanceState(savedInstanceState);
}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);

newsList = (ArrayList<HashMap<String, String>>) savedInstanceState.getSerializable("list");

}

最佳答案

如果列表不太大,一个简单的选择是将其保存到共享首选项。但是,您需要序列化 ​​ArrayList,因为您只能存储字符串。

您可以在 onSaveInstanceState() 中尝试类似的操作...

  1. 获取 SharedPreferences 编辑器
    SharedPreferences.Editor editor = getSharedPreferences("shared_preferences", 0).edit();
  2. 增加您的值(value)
    editor.putString("myList", serialize(myList));
  3. 提交更改
    editor.commit()

之后您可以在任何地方访问此列表,例如在 onCreate() 方法中,即使您的 Activity 已被执行操作杀死

SharedPreferences preferences = getSharedPreferences("shared_preferences",0);
ArrayList<HashMap<String,String>> newsList = deserialize(preferences.getString("newsList", "");

同样,这需要创建方法来序列化和反序列化 ArrayList 的额外工作,但如果这是您需要保留的唯一数据,那么这肯定是一个简单的选择。

关于java - 无法在android中保存实例状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18411863/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com