Home » Java » How to refresh fragments 'onResume?'

How to refresh fragments 'onResume?'

Posted by: admin December 28, 2021 Leave a comment

Questions:

I want to refresh fragments from an Actvitiy. (Let’s call the activity A)
Activity A contains the fragments.

When I finish Activity B then Activity A should refresh the fragments.

I was thinking this would be done in onResume? I tried simply restarting the activity through an intent but that’s not usability friendly.

So how do I refresh fragments when I resume an activity?

Answers:

Just put this code inside

onResume()

For example you want to update your listview when u return to your fregment.

@Override
public void onResume() {
    super.onResume();
    if (allowRefresh)
    {
        allowRefresh = false;
        lst_applist = db.load_apps();
        getFragmentManager().beginTransaction().detach(this).attach(this).commit();
    }
}

Here getFragmentManager().beginTransaction().detach(this).attach(this).commit();

This line detach and re-attach the fragment so your content will be updated.

###

The onResume() get called always before the fragment is displayed. Even when the fragment is created for the first time . So you can simply move your from onViewCreated() to onResume.

@Override
public void onResume() {
super.onResume();

//move your code from onViewCreated() here 

}

###

I agree with Mehul But u can alse do it this way .if you want to replace your fragment you could just say

@Override
public void onResume() {
    super.onResume();
    if (allowRefresh)
    {
        allowRefresh = false;
        lst_applist = db.load_apps();
        getFragmentManager().beginTransaction().replace(Fragment_Container,fragment).commit();
    }
}