2013-04-28 111 views
5

ArrayList在類級別上定義。 這些都是我savedInstance方法:在包中保存ArrayList savedInstanceState

@Override 
protected void onSaveInstanceState(Bundle outState) { 
    super.onSaveInstanceState(outState); 
    outState.putStringArrayList("savedList", list); 
} 


@Override 
protected void onRestoreInstanceState(Bundle savedInstanceState) { 
    super.onRestoreInstanceState(savedInstanceState); 
    list=savedInstanceState.getStringArrayList("savedList"); 
} 

但儘管如此,當我改變方向ArrayList中是空白

+1

http://stackoverflow.com/a/4967491/1001401 嘗試從得到的onCreate(捆綁savedInstanceState)您的ArrayList savedInstanceState – nfirex 2013-04-28 16:10:03

回答

2

當您使用onRestoreInstanceState()恢復狀態,onStart()後的調用,所以你保存的狀態更新列表在你定義你的適配器之後。您最好的選擇是以與onRestoreInstanceState()相同的方式恢復onCreate()中的列表。您也可以重新定義適配器或致電notifyDataSetChanged()

3
TextView textviewname; 
String textname; 

@Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
      setContentView(R.layout.activity_main); 

     //declare the ui like this 
    textviewname = (TextView) findViewById(R.id.textviewid); 
     if(savedInstanceState==null){ 
     //the first time the activity was created 
     //do the normal flow of the code 
     //Example:getting the intent data for(savedList)or processing it 
     Intent i = getIntent(); 
     textname = i.getStringExtra("savetext"); 
     //or textname="name_data"; 
     }else{ 
     //this is called when orientation change occur 
     //get the savedata 
     list=savedInstanceState.getStringArrayList("savedList"); 
     textname=savedInstanceState.getString("savetext"); 
     } 

     textviewname.setText(textname); 

} 
@Override 
protected void onSaveInstanceState(Bundle outState) { 
    super.onSaveInstanceState(outState); 
    //saving data when orientation change trigger 
    //saving data before ondestroy happens 
//onSaveInstanceState is called before going to another activity or orientation change 
    outState.putStringArrayList("savedList", list); 
    outState.putString("savetext", textname); 
    //all imnportant data saved and can be restored 
} 


@Override 
protected void onRestoreInstanceState(Bundle savedInstanceState) { 
    super.onRestoreInstanceState(savedInstanceState); 
    //this is only called after ondestroy-> oncreate occur 
    list=savedInstanceState.getStringArrayList("savedList"); 
    textname=savedInstanceState.getString("savetext"); 
    //oncreate->onSaveInstanceState->ondestroy->oncreate->onRestoreInstanceState 
} 
0

嘗試使用

list.addAll(savedInstanceState.getStringArrayList("savedList")); 

代替

list=savedInstanceState.getStringArrayList("savedList");