Mike T
Mike T

Reputation: 4787

Context and Fragments on orientation change

I'm using the Fragment compatibility package.

In my Fragment in onAttach, I keep a Context reference.

public void onAttach(Activity activity) {
    super.onAttach(activity);
    Log.w(logTag, "Activity is: " + activity);
    mContext = activity;
    Log.w(logTag, "mContext is: " + mContext); // <-- Breakpoint here
}

later on, I use the context

private String loadExampleSuccessXML () {
    try {
        AssetManager assets = this.mContext.getAssets(); // <-- Breakpoint here
        //Other Stuff

When I change orientation, onAttach seems to store the new Context but when I get to loadExampleSuccessXML, mContext is null.

I have breakpoints after mContext has been saved in onAttach, and at mContext.getAsssets().

When I first run the app the debugger shows the value of mContext:

In onAttach(), mContext [MyActivity] (id=830010419632)

In loadExampleSuccessXML(), mContext [MyActivity] (id=830010419632)

But then after a config change

In onAttach(), mContext [MyActivity] (id=830010565472)

In loadExampleSuccessXML(), mContext null

I can't understand why. Any help would be great.

Upvotes: 1

Views: 2007

Answers (2)

BrantApps
BrantApps

Reputation: 6472

Could you provide some more detail as to why you need to maintain a reference to the context? This has never been a requirement for our apps at least and has been shown (albeit not in your case from the code you have posted) to be the prime culprit in Android memory leaks...

If you need to maintain an aspect of a previous activity's state then I would suggest using onSavedInstanceState(). Here you can pass through some simple properties (like the id of an item I last selected in a list). The Manifest config fix is usually the wrong approach despite it's prevalence on help sites such as this. You probably don't want that.

Finally, look into using setRetainInstance(true)...again, in our experience this is quite the dangerous method if used incorrectly! That's probably just us but it does have some bugs with the recent android.support.v4.* libraries at least. When set to true this ensures that the fragment is never destroyed (i.e. onDestroy() is called) but is simply attached and detached as the owing activity is destroyed on rotation and recreated. It will sort your problem but do have a read of the documentation around it's usage...some of the side affects are quite subtle.

Upvotes: 1

user1521536
user1521536

Reputation:

As my experiences, you should handle orientation changing:

<activity
    android:name="com..."
    android:configChanges="orientation|keyboardHidden" />

References:

Upvotes: 1

Related Questions