lundi 13 avril 2015

getActivity() in fragment returns null after orientation change


Vote count:

0




I have set up an app to use the master/detail pattern, i.e. showing a listview and details about the selected item at the same time in landscape mode, and only the listview + start new activity for detail view in portrait mode.


Everything seemed to work perfectly, until I got a NullPointerException when trying to use getActivity() within my Master-fragment after I had changed orientation to landscape mode. Strange thing is, it works in portrait mode both before and after I change orientation (and change back to portrait)!


I'm calling getActivity() when the user presses a button, wo it's definitely after the activity has been created, so getActivity should not return null, right?



asked 1 min ago


1 Answer



Vote count:

0




It seems that the problem originated from my XML layouts. I have different layouts in portrait mode and landscape mode, something like this:


portrait.xml



<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >


<fragment
android:id="@+id/PageFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="com.magnuswikhog.adrlibrary.MasterFragment" />


</LinearLayout>


landscape.xml



<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:baselineAligned="false" >


<fragment
android:id="@+id/MasterFragment"
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="com.magnuswikhog.adrlibrary.MasterFragment" />

<fragment
android:id="@+id/DetailsFragment"
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="com.magnuswikhog.adrlibrary.DetailsFragment" />

</LinearLayout>


Notice that the MasterFragment element has id="PageFragment" in portrait.xml and id="MasterFragment" in landscape.xml. When I changed this to "MasterFragment" in portrait.xml as well the problem dissapeared! So make sure your id's are identical for the same fragment in all your layouts.



answered 1 min ago






getActivity() in fragment returns null after orientation change

Aucun commentaire:

Enregistrer un commentaire