Search code examples
androidandroid-fragmentsscreen-rotationfragmentmanager

Conserving Android session information in fragments during resource changes during rotation, etc


I have developed an Android application that has four tabs. Two of these tabs are used to access data in a Sqlite database, one tab has a scrollable table showing contents of the database, and the fourth tab shows GPS data coming into the device that is updated every 10 seconds. So far the application works great. Below is a list and brief description where needed of the java files in this application.

MainActivity.java

Tab1-DataEntry.java  
    (16) strings
    (3)  integers   

Tab2-DataEdit.java
    (16) strings

Tab3-DataTable.java
    selecting a row in this table loads that record in Tab2-DataEdit

Tab4-GpsData.java
    GPS data updated every 10 seconds, several buttons.

I also have a DbAdapter.java file

I am working on storing state information during device resource changes, (screen rotation, docking, etc.) I have spent a great deal of time reviewing resources online and have recently begun to understand onSaveInstanceState() and onRestoreInstanceState().

Questions: Is using onSaveInstanceState() and onRestoreInstanceState() a good choice for this application? Is onSaveInstanceState/onRestoreInstanceState implemented ONLY in MainActivity, or in the relevant Tab files (Tab1-DataEntry, Tab2-DataEdit) as well?


Solution

  • Fragments can retain their own data if you indicate that via setRetainInstance().

    When the activity is recreated (e.g. after rotating the device) the Fragments will still be there (although their corresponding views will be discarded and recreated -- the changes in the "normal" lifecycle callbacks are explained in the documentation for that method).

    You should also check the Retaining an Object During a Configuration Change section of the documentation.