Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have an Activity with a fragment container in layout. 3 different Fragment can be displayed in it. These fragments contains a Listview which displays data with custom Adapter i made.

So each list elements is created during onCreateView, after i queried a database to have data.

But sometimes some data may changes in my database, so i would like to redraw/recreate it the Listview.

  • What would be the best way (i mean, the less ressources demanding) to refresh my fragment view ?
  • Is there a method to recall onCreateView manually ?
like image 644
Heretyk Avatar asked Sep 02 '15 17:09

Heretyk


People also ask

How do you refresh a Java fragment?

Go to your navigation graph and find the fragment you want to refresh. Create an action from that fragment to itself. Now you can call that action inside that fragment like so.

How do you refresh a fragment after onBackPressed from activity?

Back button should be handled from Activity. You can override onBackPressed in Activity and call a function on corresponding fragment to reloadItems().

How do you refresh a fragment on a resume?

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 . Save this answer.

How do I refresh a ViewPager fragment?

addOnPageChangeListener(new ViewPager. OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { // do this instead, assuming your adapter reference // is named mAdapter: Fragment frag = mAdapter.


1 Answers

Combined two answers and removed if (isVisibleToUser), because it makes the setUserVisibleHint be called in an unpredicted asynchroneous order and fragment can either be refreshed or not. I found this piece of code stable (in your Fragment):

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {

super.setUserVisibleHint(isVisibleToUser);

  // Refresh tab data:

  if (getFragmentManager() != null) {

    getFragmentManager()
      .beginTransaction()
      .detach(this)
      .attach(this)
      .commit();
  }
}
like image 141
Zon Avatar answered Sep 22 '22 18:09

Zon