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

89,960

Solution 1

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);

Solution 2

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();
  }
}

Solution 3

There is one very useful method of Fragment, which can be used for refreshing fragment.

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    if (isVisibleToUser) {
        //Write down your refresh code here, it will call every time user come to this fragment. 
       //If you are using listview with custom adapter, just call notifyDataSetChanged(). 
    }
}

Solution 4

If you have problems with some of the methods listed above (as I had after uprgrading...), I recommend to make some kind of public refresh method in fragment and then simply call it, it is even less code, nicer and faster because fragment doesn't need to be reinitialized...

FragmentManager fm = getSupportFragmentManager();

//if you added fragment via layout xml
Fragment fragment = fm.findFragmentById(R.id.your_fragment_id);
if(fragment instanceof YourFragmentClass) // avoid crash if cast fail
{
    ((YourFragmentClass)fragment).showPrayer();
}

If you added fragment via code and used a tag string when you added your fragment, use findFragmentByTag instead:

Fragment fragment = fm.findFragmentByTag("yourTag");
if(fragment instanceof YourFragmentClass)
{
    ((YourFragmentClass)fragment).showPrayer();
}

Solution 5

If you followed the Material design tutorial, you can just navigate to the same page which will automatically reload it. Don't forget to add "false" by backstack because you don't have to return to the previous fragment because it was the same fragment.

((NavigationHost) getActivity()).navigateTo(new MyNotesFragment(), false);
import androidx.fragment.app.Fragment;

public interface NavigationHost {
    void navigateTo(Fragment fragment, boolean addToBackstack);
}
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

public class MainActivity extends AppCompatActivity implements NavigationHost {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (savedInstanceState == null) {
            getSupportFragmentManager()
                    .beginTransaction()
                    .add(R.id.container, new LoginFragment())
                    .commit();
        }
    }

    @Override
    public void navigateTo(Fragment fragment, boolean addToBackstack) {
        FragmentTransaction transaction =
                getSupportFragmentManager()
                        .beginTransaction()
                        .replace(R.id.container, fragment);

        if (addToBackstack) {
            transaction.addToBackStack(null);
        }

        transaction.commit();
    }
}
Share:
89,960

Related videos on Youtube

Heretyk
Author by

Heretyk

Working in IT for 10 years. Specialized in networking, IT security, server administration, virtualization. Previous experiences in IT project management and staff management. Developping for 5 years front end & backend : Java, React.js, Node.js (TypeScript & ES6) in cloud environments.

Updated on November 24, 2021

Comments

  • Heretyk
    Heretyk over 2 years

    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 ?
    • priyankvex
      priyankvex over 8 years
      Use adapter.notifyDataSetChanged(). It is meant for the exact purpose you are mentioning.
    • Sucho
      Sucho over 8 years
    • Heretyk
      Heretyk over 8 years
      @priyankvex : No it doesn't work because i need to restart a query too. In fact, i have an object 'Query' and i need to relaunch this query ...and then yes, i can use adapter.notifyDataSetChanged()
    • Zar E Ahmer
      Zar E Ahmer over 7 years
      implement a callback(interface) in fragment & when data is changed call it.
    • Zar E Ahmer
      Zar E Ahmer over 7 years
  • Heretyk
    Heretyk over 8 years
    I can't do this - I would like to call the "refresh" from oustide the fragment's instance...from my custom adapter or even from MainActivity So it requires me to call a static method. And 'getFragmentManager' cannot be used in static method.
  • Heretyk
    Heretyk over 8 years
    I used your code through a Handler on my main activity, it allowed me to handle the "static" considerations. Thanks
  • Si8
    Si8 over 7 years
  • Wasi Sadman
    Wasi Sadman about 5 years
    Well @Heretyk, I think you can use EventBus in that case.
  • Whiteq
    Whiteq almost 5 years
    this is the best solution for me
  • androidStud
    androidStud over 4 years
    Really!! It's deprecated guyz! You never know when an update on your user's mobile can cause crash on your app because of this method.
  • vivek modi
    vivek modi over 2 years
    Hey @Tina can you please help me on this issue