Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>When the orientation switches (really whenever Android decides to recreate the <code>Fragment</code>), the existing <code>Fragment</code> is destroyed then recreated. </p> <p>However, when Android recreates your <code>Fragment</code>, it doesn't call your custom <code>newInstance()</code> method. It uses the empty no-args constructor.</p> <p>This means that your <code>Fragment</code> <em>won't</em> have a non-null reference to whatever custom <code>Object</code> you want, resulting in the NPE being thrown.</p> <p>You will need to figure out a way to pass the <code>Object</code>. If the <code>Object</code> is a simple data <code>Object</code> consider passing its fields via the <code>setArguments()</code> method or Serializing it.</p> <pre><code>MyFragment fragment = new MyFragment(); Bundle data = new Bundle(); data.putString ("key_string", "your string here"); fragment.setArguments (data); </code></pre> <p>You could also create an <code>interface</code> that queries the Activity for the Object. For example:</p> <pre><code>public class MyFragment extends Fragment { public interface ObjectProvider { public CustomObject getCustomObject(); } private ObjectProvider provider; @Override public void onAttach (Activity activity) { super.onAttach(activity); try{ provider = (ObjectProvider) activity;//get an instance of the ObjectProvider } catch (ClassCastException e) { e.printStackTrace(); throw new RuntimeException ("This isn't an ObjectProvider."); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.layout_fragment, container, false); provider.getCustomObject().getSomething(); return rootView; } } </code></pre> <p>Then your Activity needs to implement the interface:</p> <pre><code>public class MainActivity implements MyFragment.ObjectProvider{ @Override public CustomObject getCustomObject() { return new CustomObject(); } } </code></pre>
 

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