Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>To work with the Android framework and Fragment lifecycle you should implement the <code>onSaveInstanceState</code> method in your Fragment. For simplicity I've assumed that you have an array of String values that you can get to (I generally extend ArrayAdapter to encapsulate view construction and to provide a convenience method to access the entire underlying dataset):</p> <pre><code>public void onSaveInstanceState(Bundle savedState) { super.onSaveInstanceState(savedState); // Note: getValues() is a method in your ArrayAdapter subclass String[] values = mAdapter.getValues(); savedState.putStringArray("myKey", values); } </code></pre> <p>You can then retrieve the data in your onCreate method (or onCreateView or onActivityCreated - see <a href="http://developer.android.com/guide/components/fragments.html#Lifecycle">the Fragment JavaDoc</a>) like this:</p> <pre><code>public void onCreate (Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (savedInstanceState != null) { String[] values = savedInstanceState.getStringArray("myKey"); if (values != null) { mAdapter = new MyAdapter(values); } } ... } </code></pre> <p>This ensures that all lifecycle events will be handled properly, without loss of data, including device rotation and the user switching to other applications. The danger of not using <code>onSaveInstanceState</code> and using memory is the danger of Android reclaiming that memory. Saved state would not be affected by this but using instance variables or hidden fragments would result in loss of data.</p> <p>If <code>savedStateInstance</code> is null then there is no state to restore. </p> <p>The <code>if (values != null)</code> is simply to guard against the possibility that no array was saved, but if you code your ArrayAdapter to handle a null data set you won't need this.</p> <p>The ultimate solution, if your rows are instances of one of your own classes and not single data items, is to implement the Parcelable interface on that class, then you can use <code>savedState.putParcelableArray("myKey", myArray)</code>. You'd be surprised how useful it is to know how to implement Parcelable - it allows you to pass your classes around inside intents and allows you to write much cleaner code.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload