Cruces
Cruces

Reputation: 3119

Is it better to always instantiate a fragment or keep a reference to it?

I am creating an app that uses a number of fragments, inside a ViewPager.

Up to now I always fed the ViewPager a new instance of each fragment it needed , because all the examples on google developers seem to say that , that is the correct thing to do.

Those fragments used their parent Activity to retrieve their state/data and update themselves in OnCreateView.

One of the new fragments is a NewsFragment which contains either a NewsHeadersFragment or a NewsArticleFragment, and those two need to communicate.

What I do is send the message article_clicked(article) from NewsHeaderFragment to my Activity (unfortunatelly I haven't found a way to communicate with the parent fragment) and the Activity sends a message to the NewsFragment to change its child fragment

In order to do this it seems I must keep a reference to the NewsFragment, so I was thinking that maybe I should not always create a new instance of fragments.

My question is, is it better to always create a new instance of the NewsFragment and just update the reference, or only create an instance when the reference is null and always return the reference.

i.e. is this better:

private static NewsFragment _news;
public static NewsFragment get_news_fragment() {
    _news = NewsFragment.NewInstance();
    return _news;
}

or this?

private static NewsFragment _news;
public static NewsFragment get_news_fragment() {
    if (_news == null) _news = NewsFragment.NewInstance();
    return _news;
}

Thanks in advance for any help you can provide

Upvotes: 1

Views: 176

Answers (3)

rahul sharma
rahul sharma

Reputation: 149

The data you want to share inside your NewsFragment you can have it in system context class and store the data there(getter/setter) , however you just require to call this class method instead of creating your fragment's instance everytime.

Upvotes: 0

JN.Meng
JN.Meng

Reputation: 1

It‘s better to create a new fragment. However, it's also depends on what you want to do in them. If you do something async,or use observer mode, keeping a reference is better

Upvotes: 0

Much Overflow
Much Overflow

Reputation: 3140

I recommend always creating fragments when needed (as done in google developers samples) for one important reason which is to prevent potential OutOfMemoryExceptions. Keeping hard references to a Fragment/Activity outside its lifecycle makes it illegible for garbage collection and pave way for the infamous OOMs.

For your scenario I would recommend you to try some sort of EventBus (pub / sub mechanism) to communicate from your activity to fragment.

Upvotes: 1

Related Questions