Weird fragment lifecycle error

EDIT

So it seems that my Fragment is retained in the FragmentManager which tries to reinitialize it. Still not sure why it isn’t destroyed with the Activity. As for the loading message, this is displayed when the ListView does not have an adapter set. I however, set the adapter items in onCreate and onResume so I’m not sure why this loading screen is showing. Still open to any explanations of this behavior

Original

I’m playing around with fragments and noticed a weird error that is popping up when I change the orientation of the screen. This error should not be happening though because all the data is recreated in the onCreate when the screen orientation is changed. Also, the fragment onResume() is called twice after the rotation. Here’s my steps for creating the error and how the debugger is hitting the functions.

  • Activity: onCreate()
  • Activity: onResume()
  • Fragment: onResume()
  • Rotate Screen
  • Activity: onCreate()
  • Activity: onResume()
  • Fragment: onResume() (items are null even though Activity.onResume() set them)
  • Fragment: onResume() (items are not null, why is this being called twice?)

After this last fragment onResume is hit, the tablet displays a “Loading…” message and icon. Why is the data not displayed in the list any more? My suspicions are that the onCreate is creating a second fragment. The first fragment looses its data because of the orientation destroying the views, the second fragment gets the data and the loading screen is the first fragment with no data items and the second fragment is hidden. I may be wrong. Why aren’t the fragments all destroyed when the screen is rotated like the Activity? Please do not critique the code unless its to solve this specific issue. I’m not actually making an app, I’m experimenting with fragment functionality. Thanks!

Main Activity

private ArrayList<Object> items = new ArrayList<Object>();
private MyListFragment mylistFragment;

public MainActivity() {
    items.add("Hello");
    items.add("World");
    items.add("Goodbye");
}

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    FragmentManager fm = getFragmentManager();
    FragmentTransaction ft = fm.beginTransaction();

    mylistFragment = new MyListFragment();
    mylistFragment.setItems(items);

    ft.add(R.id.container, mylistFragment);
    ft.commit();
}

@Override
public void onResume() {
    super.onResume();

    mylistFragment.setItems(items);
    mylistFragment.getListView().setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Toast.makeText(MainActivity.this, ((TextView)view).getText(), Toast.LENGTH_LONG).show();
        }

    });
}

List Fragment

private List<Object> items = null;
private Boolean isSet = false;

@Override
public void onResume() {
    super.onResume();
    if( !isSet && items != null) {
        setListAdapter(new ArrayAdapter<Object>(getActivity(), R.layout.item, items));
        isSet = true;
    }
}

public void setItems(List<Object> items) {
    this.items = items;
    if( this.isResumed() ) {
        setListAdapter(new ArrayAdapter<Object>(getActivity(), R.layout.item, items));
        isSet = true;
    } else {
        isSet = false;
    }
}

onCreateOptionsMenu in a Fragment lifecycle

I found a really strange behavior in the Fragment lifecycle. After several tests on one Fragment, I realized than I got this execution order every time: onCreateView() onStart() onCreateOptionsMenu()

Android: Method in Fragment Lifecycle

I’m looking for a method in the Fragment Lifecycle, but I’m not sure which one. Here’s my situation: I’ve got a Fragment inside a ViewPager. The Fragment displays a List with some information. I fill

Order of Fragment Lifecycle Methods

IF i have multiple fragments in my layout, what exactly is the order in which their lifecycle methods are called? Am i right in thinking Fragment 1’s onAttach(), onCreate(), onCreateView() is run firs

Weird Error inflating class fragment in Android

I just started learning ADT, and am stuck in creating Fragment. What I did follows the tutorial from http://developer.android.com/training/basics/fragments/creating.html . However, when I run it, it g

Can some draw lifecycle of Fragment and its parent FragmentActivity?

In Android docs, I found a specs on Activity lifecycle and on Fragment lifecycle individually, but never together. It does not seem obvious as I attached a debugger to FragmentActivity which hosts my

Difference between add() & replace() with Fragment’s lifecycle

My program has 6 fragments: Fragment1, Fragment2,….->Fragment6. I use the add() and replace() statement to switch between the fragment and track their lifecycle. Fragment1 add Fragment2 add Fragm

View pager and fragment lifecycle

View pager that i created loads three pages at a time. now if i swipe from page 1 to 2 then to 3.when the third page is the current item,the first page(fragment) goes to onPause().now if i swipe to se

Strange fragment lifecycle behavior: onCreate called twice

I’ve created simple fragment. FRAGMENT CLASS public class MyFragment extends Fragment { static int count = 0; static TextView tv; @Override public void onCreate(Bundle savedInstanceState) { super.onCr

Make a Fragment’s Lifecycle Mimic Another

WHAT I HAVE I have a Fragment called MainFragment. This is added from my MainActivity. Within that Fragment in on its onResume method I add another Fragment called SecondFragment like so. @Override p

What Lifecycle Method of a Fragment do I Execute an AsyncTask?

Which lifecycle method of the Fragment class is the best to call the execute() method on a AsyncTask onCreate(), onAttach() or onActivityCreated()? I want to load data into TextViews on the Fragment’s

Answers

The FragmentManager will automatically recreate the Fragments for me. However, the data inside them needs to be reinitialized. Therefore my code was creating a second fragment. The loading screen was because the first fragment no longer had its adapter of items and the second fragment was hidden. What a headache, I almost think the FragmentManager should destroy the Fragments so you can recreate them with the data they hold.

I believe this is why in the various demos via Diane and other google examples… they typically have some way of helping hte initialization via a static method… and setArguments.

IIRC, the fragment creation stuff will call the default constructor to create, but only knows about populating with appropriate data via setArguments. In the example on the android development blog… the id was being passed from the listactivity, to the details fragment. After setParams is called, the fragmentManager should be able to reanimate it.

Documentation seems to be sparse on the subject and I’d like to be doing things right, so if you guys have feedback, I’d appreciate it.

It seems that using FragmentActivity from the support library saves and restores instance automatically. Therefore, only do your fragment transactions if savedInstanceState is null.

For example, in your FragmentActivity’s onCreate(), do the following:

if(savedInstanceState == null){
       FragmentManager fragmentManager = getSupportFragmentManager();
       fragmentManager.beginTransaction()
       .replace(R.id.fragment_container, mFragment).commit(); //mFragment is your own defined fragment
}