Note that there are some explanatory texts on larger screens.

plurals
  1. POFragment's onCreateView() causes my app to crash
    primarykey
    data
    text
    <p>I'm having a strange problem. I'm using Fragments in an app that has a host FragmentActivity in which I implemented an internal <code>class FragmentPagerAdapater</code> that constructs the Fragments and puts them into my activity's tabs.</p> <p>In the app, I need to pass on an Object from my Activity to the Fragments. I'm not really sure what the proper way to do this is, so I improvised, and went for a static Fragment <code>newInstance(Object obj)</code> in my Fragments. This method just calls the default Fragment's constructor and sets a instance variable to hold the Object within the Fragment. </p> <p>Now in the Fragment's <code>createView()</code> method, I use the instance's Object informations to fill the layout. This works fine when the app launches, but the app crashes when I change the screen orientation from portrait to landscape (or the opposite). The logs indicates a NullPointerException on the instance Object in <code>createView()</code>. I feel like I missed something in the lifecycle but I can't find the answer. Is there somethign special to do so my Fragments will save their instance variable no matter what ?</p> <p>Here's a code sample to help you understand what the issue is:</p> <pre><code>public class MyFragment extends Fragment { private Object obj; public static MyFragment newInstance(Object obj) { MyFragment fragment = new MyFragment(); fragment.setObject(obj); return fragment; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.layout_fragment, container, false); MyType res = ((Type) (obj)).getSomething(); // This line causes the crash because obj is null when I switch to another orientation // I Do something with res to fill rootView return rootView; } private void setObject(Object obj) { this.obj = obj; } } // In the Activity I simply create the Fragment using MyFragment fragment = MyFragment.newInstance(myObjectToPass); </code></pre> <p>Thanks for your help !</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload