As an alternative to an Intent, i'm saving data in a retained headless Fragment during Activity re-creation (my saved object can be pretty large and it wouldn't fit the size limit of an Intent, and i think this is a faster approach than serializing-deserializing into JSON for example).

I've got the idea from this Google documentation, although my implementation is a bit different.

The Fragment:

public class DataFragment extends Fragment {

    private Data data;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRetainInstance(true);
    }

    public void setData(Data data) {
        this.data = data;
    }

    public Data getData() {
        return data;
    }
}

I save my data to this Fragment in the onSaveInstanceState() method of my Activity:

@Override
protected void onSaveInstanceState(Bundle outState) {
    FragmentManager fm = getSupportFragmentManager();
    dataFragment = (DataFragment) fm.findFragmentByTag(TAG_DATA);
    if (dataFragment == null) {
        dataFragment = new DataFragment();
        fm.beginTransaction().add(dataFragment, TAG_DATA).commitNow();
    }
    dataFragment.setData(myData);
    super.onSaveInstanceState(outState);
}

And the relevant part of onCreate():

Data data;
FragmentManager fm = getSupportFragmentManager();
dataFragment = (DataFragment) fm.findFragmentByTag(TAG_DATA);
if (dataFragment == null) {
    // the Fragment is not attached, fetching data from DB
    DatabaseManager dbm = DatabaseManager.getInstance(this);
    data = dbm.getData();
} else {
    // the Fragment is attached, fetching the data from it
    data = dataFragment.getData();
    fm.beginTransaction().remove(dataFragment).commitNow();
}

This works flawlessly on orientation changes.

The problem is, sometimes, when my app is in the background and i'm returning to it, dataFragment.getData() returns null.

In other words, in the following line in onCreate() sometimes data is null:

data = dataFragment.getData();

How is this possible?

It does not throw a NullPointerException, so dataFragment is not null for sure.

Why did its initialized instance variable became null?

  • 1
    Are you able to confirm that the onSaveInstanceState method gets called? Perhaps add a log statement there; I am suspecting that it might be the case of the data not having been saved when Activity is sent to background. – ishmaelMakitla Sep 30 '16 at 7:24
up vote 9 down vote accepted

What you experience is PROCESS DEATH.

Technically it's also called "low memory condition".

The retained fragment is killed along with the application, but the FragmentActivity recreates your retained fragment in super.onCreate(), so you'll find it by its tag but the data in it won't be initialized.

Put the app in background then press the red X in the bottom left in Android Studio to kill the process. That recreates this phenomenon.

terminate button

  • Thank you, i think you're right. I guess the proper approach is to perform a null value check in this line then and load the data from the DB if the data from the Fragment is null. – justanoob Sep 30 '16 at 7:28
  • @EpicPandaForce : but how to resolve these conditions in actual scenario. I mean how to save these data? Other than sharedpreference/DataBase any other advisable way ? – Sreehari Sep 30 '16 at 7:28
  • 2
    @Stallion save to bundle (not recommended for large datasets as it can crash on Nougat), save to shared pref, save to JSON file, save to SQLite, save to some other key value store solution like Paper or SnappyDb, save to Realm, I dunno – EpicPandaForce Sep 30 '16 at 7:31
  • I see.. I would be good if these data handling could be done automatically by android os itself. So that developers can just focus on other areas.. Anyways thank you – Sreehari Sep 30 '16 at 7:34
  • @EpicPandaForce tottaly agree with process death in low mem condition..its the case.. – SRam Sep 30 '16 at 7:37

if activity is recreated after it was previously destroyed, you are able to saved your state from the Bundle that the system passes your activity. Both the onCreate() and onRestoreInstanceState() callback methods receive the same Bundle that contains the instance state information.

Obviously yours onCreate() method is called whether the system is creating a new instance of your activity or recreating a previous one, you need to check whether the state Bundle is null before you attempt to read it. If it is null, then the system is creating a new instance of the activity, instead of restoring a previous one that was destroyed. in oncreate():

Data data;
FragmentManager fm = getSupportFragmentManager();
dataFragment = (DataFragment) fm.findFragmentByTag(TAG_DATA);
**if (dataFragment.getData()== null) {**
    // the Fragment is not attached, fetching data from DB
    DatabaseManager dbm = DatabaseManager.getInstance(this);
    data = dbm.getData();
} else {
    // the Fragment is attached, fetching the data from it
    data = dataFragment.getData();
    fm.beginTransaction().remove(dataFragment).commitNow();
}
  • How is this relevant to the question? He does not use the savedInstanceState bundle at all. – earthw0rmjim Sep 30 '16 at 7:15
  • edited pls go through.. – SRam Sep 30 '16 at 7:20
  • 1
    Have you even read the question? The point of the question is he uses a Fragment instead of a Bundle to save data through the configuration change. It has nothing to do with savedInstanceState. – earthw0rmjim Sep 30 '16 at 7:23
  • null value check is best option instead of we can use sharedpref for largevalue object...edited again – SRam Sep 30 '16 at 7:33

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.