Question

I have an application that is composed of one activity and 3 fragments. The activity creates a menu with buttons that create the appropriate fragments. My code works perfectly without screen rotations, but it breaks when I rotate the screen.

My first attempt did not include a setRetainInstance(true) call when creating the fragments. The issue that I found with that is that after replacing fragments twice (one fragment remains on the back stack), if I rotate the screen, I get a null pointer exception in the fragment that is not currently displayed. Edit: Just a note, the null pointer exception is in the setOnItemClickListener call shown below. lv is declared in the onCreateView() method.

My second attempt, I included a setRetainInstance(true) call when creating the fragments. This solved the first issue. However, one of my fragments is a ListFragment, and when I rotate the screen, the OnItemClickListener does not seem to be set anymore. Here is my code for setting the listener:

ListAdapter adapter = new SimpleAdapter(getActivity(),
        gameslist, R.layout.list_object,
        new String[] { TAG_ID, TAG_NAME, TAG_LOCATION, TAG_CREATED },
        new int[] { R.id.id, R.id.name, R.id.location, R.id.created_date });
setListAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener() {

        public void onItemClick(AdapterView<?> arg0,
                View arg1, int position, long arg3) {
            // ...
        }
});

Any ideas or solutions to this problem? Is my understanding of how to design with fragments just completely off?

Thanks for any help!

edit: also, just for my understanding, where in the code are the fragments being recreated? They are not in the oncreate() function of my activity. Thanks!

Figured it out! I was calling the AsyncTask in the onCreate() function, which was being called when the screen was rotated. However, I was declaring lv in the onCreateView() function, which would not be called until the view is created. Nullpointerexception!

Was it helpful?

Solution

do you have onCreate(...) and onResume() and onCreateView(...) implemented in your fragment?

Which one of the three is that adapter code in?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top