0

I've been using the static method newInstance to create fragments after reading numerous recommendations to do so here on SO (most notably, here). Before that, I had been putting variables in the constructor (bad) and checking if the fragment exists using 'findFragmentByTag' and reusing that fragment if it exists.

My question... Should I still be using 'findFragmentByTag' if I'm getting my fragment using myFragment.newInstance() or should I just create the new instance and let the garbage collector take care of the previous one?

if I should be using findFragmentByTag, what's the best method of ensuring the reused fragment takes updated parameters.

Example:

String test;

test = "hello";
launchNewFragment();

// User hits back, does something else, then goes back to that fragment
// in this call, how can I ensure the reused fragment is getting the new value of 'test'?
test = "world";
launchNewFragment();

private void launchNewFragment() {
    Fragment f = getSupportFragmentManager.findFragmentByTag("myFragment");

    if (f == null) {
        f = myFragment.newInstance(test);
    }

    getSupportFragmentManager().beginTransaction().replace(R.id.myContainer, f, "myFragment").addToBackStack(null).commit();
}

Thanks all

Community
  • 1
  • 1
Psest328
  • 6,575
  • 11
  • 55
  • 90
  • What do you mean when you say 'best method of ensuring the reused fragment accepts new data?' are you trying to find out how old the data is? – Andy B Feb 03 '15 at 16:33
  • I just edited the op to make it clearer. please take a look – Psest328 Feb 03 '15 at 16:42

1 Answers1

0

If you can find your fragment using findFragmentByTag the GC is not gonna help much since it'll still be in memory. Also, if you restore the fragment there is no need to call beginTransaction again. Move that inside the if clause.

I'm assuming that you are doing this inside an activity so another option would be have the fragment inside the layout like this:

<fragment name="your.package.MyFragment" />

That said we need some more details on how you are using the fragment.

pablisco
  • 14,027
  • 4
  • 48
  • 70
  • The real crux of the question is if the user goes from 1 fragment to another then makes his way back to this one, but the data has changed, how do I make sure the fragment gets the updated data when I use findFragmentByTag? – Psest328 Feb 03 '15 at 17:15
  • `setArguments(updatedData)` It depends on how you send the data to the fragment in the first place – pablisco Feb 03 '15 at 17:28
  • it's passed into the constructor of newInstance... so when it's first created it'd be like: myFragment.newInstance("foo"); – Psest328 Feb 03 '15 at 17:29
  • Ok, then use just a setter instead of using the static factory method – pablisco Feb 03 '15 at 17:40