Reputation: 589
I am making a master-detail application and I am observing some odd behavior I can't explain / find an answer for.
So my master fragment is just a ListView that when you click on an item, it opens up the detail page. So when you're on the detail page, you can press the back button, and it will go back to the master fragment with no errors.
If you're on the detail change, and then do an orientation change and then press back, still no errors occur.
But when you're on the detail page, and then do an orientation change, and then do an orientation change back (so portrait -> landscape -> portrait), I get a null pointer exception when I am trying to restore the ListView.
Here is the offending code:
if (savedInstanceState == null) {
posts = new ArrayList<Post>();
loading = true;
refreshData();
} else {
loading = false;
posts = savedInstanceState.getParcelableArrayList("posts");
adapter = new ListviewAdapterPost(getActivity(), R.layout.cell_layout_post,
posts);
//This line is the one that throws the null pointer.
listview.setAdapter(adapter);
}
I did a check, and the posts ArrayList is null after the two orientation changes, but not after just one. This code is taking place in the onCreateView method in my master fragment.
If you need any other code, let me know!
Upvotes: 0
Views: 389
Reputation: 4701
you'd use android:configChanges="orientation" to avoid recrating your activity whenever orientation changes.
you can save & retrieve your fragment instance by creating your Fragment instance manually.
in your Fragment create newInstance like:
public static MasterFragment newInstance() {
MasterFragment mf = new MasterFragment ();
Bundle args = new Bundle();
if(posts != null && posts.length > 0)
args.putSerializable("posts", posts);
mf.setArguments(args);
return mf;
}
and create your fragment from newInstance in your activity like this
MasterFragment mf = MasterFragment.newInstance();
*
*transaction
*
Upvotes: 2