繁体   English   中英

无法在Android中保存实例状态

[英]Can't save instance state in android

在我的应用程序中,我尝试在onSaveInstanceState中使用putSerializable方法保存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. 增加您的价值
    editor.putString("myList", serialize(myList));
  3. 提交更改
    editor.commit()

然后,即使您的活动因执行而被杀死,之后您仍可以在任何地方访问此列表,例如在onCreate()方法中

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM