Refresh Fragment at Reload

Refresh Fragment at reload

I think you want to refresh the fragment contents upon db update

If so, detach the fragment and reattach it

// Reload current fragment
Fragment frg = null;
frg = getSupportFragmentManager().findFragmentByTag("Your_Fragment_TAG");
final FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.detach(frg);
ft.attach(frg);
ft.commit();

Your_Fragment_TAG is the name you gave your fragment when you created it

This code is for support library.

If you're not supporting older devices, just use getFragmentManager instead of getSupportFragmentManager

[EDIT]

This method requires the Fragment to have a tag.

In case you don't have it, then @Hammer's method is what you need.

Method to refresh Fragment content when data changed ( like recall onCreateView)

Detach and attach it with

Fragment currentFragment = getFragmentManager().findFragmentByTag("YourFragmentTag");
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.detach(currentFragment);
fragmentTransaction.attach(currentFragment);
fragmentTransaction.commit();

or search fragment with

Fragment currentFragment = getActivity().getSupportFragmentManager().findFragmentById(R.id.container);

refresh the fragment when getting back from an activity or pressing back

I fixed the issue by replacing onStop() function to onPause() since the activity is not getting destroyed and it no longer loop the createRecentlyViewedButton() function hope this help somebody

here are the changes I made though

override fun onPause() {
super.onPause()
shouldRefreshOnResume = true
}

and

   override fun onResume() {
super.onResume()
//shoudRefreshOnResume is a global var
if (shouldRefreshOnResume) {
val recentlyViewed = activity?.findViewById<LinearLayout>(R.id.recently_viewedView)
createRecentlyViewedButton(recentlyViewed!!)
}
}

refresh fragment after changing data in database

I think you are having this issue because of the below code in your MainActivity:

FragmentOne fragmentOne = new FragmentOne();
fragmentOne.getFragmentManager().beginTransaction().replace(R.id.card_view, fragmentOne).commit();

You try to get the instance of the fragment manager with getFragmentManager() who call Activity.getFragmentManager but your fragmentOne isn't attach to the activity so the method return null and you get a java.lang.NullPointerException

Instead of fragmentOne.getFragmentManager() use getSupportFragmentManager() directly from the activity.

Hope this helps.



Related Topics



Leave a reply



Submit