2013-02-17 108 views
6

在我的應用程序我想保存數據在savedInstanceState()。我想保存ArrayList<HashMap<String,String>>。到目前爲止,我無法做到這一點。 這裏是我的代碼是困擾我保存ArrayList的哈希映射

@Override 
    protected void onSaveInstanceState(Bundle outState) { 
     super.onSaveInstanceState(outState); 
     outState.putParcelableArrayList("places", (ArrayList<? extends Parcelable>) places); 

    } 

恢復()方法

private void restore(Bundle savedInstanceState) { 
     // TODO Auto-generated method stub 
     //What should i do here! i have try many things but none of them is helping 

    } 

回答

24

由於ArrayListHashMapStringSerializable可以使用Bundle.putSerializableBundle.getSerializable

@Override 
protected void onSaveInstanceState(Bundle outState) { 
    super.onSaveInstanceState(outState); 
    outState.putSerializable("places", places); 
} 

private void restore(Bundle savedInstanceState) { 
    if (savedInstanceState != null) { 
     places = (ArrayList<HashMap<String,String>>) savedInstanceState.getSerializable("places"); 
    } 
} 

而且,確保你打電話給restore fr OM onRestoreInstanceStateonCreate

+1

喔以及感謝。它工作 – 2013-02-18 03:48:29

+0

也感謝我!也只是添加,如果你使用onRestoreInstanceState你不必做空檢查。 http://developer.android.com/training/basics/activity-lifecycle/recreating.html – piratemurray 2014-11-03 21:15:09

0

可以說u有:

ArrayList< HashMap< String,String>> arr = new ArrayList< HashMap< String,String>>(); 

    @Override 
    protected void onSaveInstanceState(Bundle outState) { 
    super.onSaveInstanceState(outState); 
    outState.putParcelableArrayList("places", (ArrayList< ? extends Parcelable>) arr); 
    } 

    @Override 
    protected void onRestoreInstanceState(Bundle savedInstanceState) { 

    ArrayList<HashMap<String,String>> a = (ArrayList<HashMap<String,String>>)savedInstanceState.get("places"); 
    /*for(int i =0; i< a.size(); i++){ 
     HashMap<String,String> map = a.get(i); 
     for(String s : map.keySet()){ 
      Log.d("log",s+" :: "+map.get(s)); 
     } 
    }*/ 
}