Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I found this to be a HIGHLY confusing issue (one of many that litter the Android landscape). </p> <p><code>setArguments()</code> is a workaround for Android's very unhelpful need to have a parameter-less constructor available for Fragments. </p> <p>My confusion came in waves. First, the methods you naturally override in your <code>Fragment</code> (e.g. <code>onCreate</code>, <code>onCreateView</code>) receive a <code>Bundle</code> parameter that represents the <code>savedInstanceState</code> of your <code>Fragment</code>. This instance state apparently has <strong>NOTHING</strong> whatsoever to do with the values you store via <code>setArguments()</code> and retrieve via <code>getArguments()</code>. Both use a <code>Bundle</code>, both <code>Bundles</code> are likely to be accessed within the same overridden method, neither have anything to do with each other. </p> <p>Second, it's unclear how Android uses <code>setArguments()</code>. Android calls your parameter-less constructor to rebuild your <code>Fragment</code> on rotate, but apparently ALSO will call whichever <code>setArguments()</code> method was last called when the <code>Fragment</code> was constructed. </p> <p>Huh???? </p> <p>Amazing, but true. All of this creating <code>Bundles</code> with <code>setArguments()</code> madness exists to compensate for the need of a parameter-less <code>Fragment</code> constructor. </p> <p>In short, I'm using the static <code>newInstance</code> method to create my <code>Fragment</code>.</p> <pre><code>public MyFragment() { //satisfy Android } public static MyFragment newInstance(long record_id) { Log.d("MyFragment", "Putting " + record_id + " into newInstance"); MyFragment f = new MyFragment(); Bundle args = new Bundle(); args.putLong("record_id", record_id); f.setArguments(args); return f; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); /** * Perform an immediate check of arguments, * which ARE NOT the same as the bundle used * for saved instance state. */ Bundle args = getArguments(); if(args != null) { record_id = args.getLong("record_id"); Log.d("MyFragment", "found record_id of " + String.valueOf(record_id)); } if(savedInstanceState != null) { //now do something with savedInstanceState } } </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