Search code examples
androidandroid-fragmentsrefreshadapter

Is there a way to reload a fragment from its adapter?


I have a fragment with a custom recycerview that is filled using a REST call. When i click a list item pops up a dialog. I want to reset that list whenever i get out of the dialog. I found the following code:

FragmentManager manager = ((AppCompatActivity) context).getSupportFragmentManager();
Fragment currentFragment = manager.findFragmentByTag("productTag");
FragmentTransaction fragmentTransaction = manager.beginTransaction();
fragmentTransaction.detach(currentFragment);
fragmentTransaction.attach(currentFragment);
fragmentTransaction.commit();

When i hit the onClick button (a way to get out of dialog) app crashes and logcat says:

Attempt to invoke virtual method 'void androidx.fragment.app.Fragment.setNextAnim(int)' on a null object reference

As much as I understood i should be able to call the fragment with the code above though it keeps on crashing. So is that the problem or maybe something entirely different?


Solution

  • You can follow a process like below.

    In your Adapter set a listener which will be implemented in Fragment used to update whatever you want in fragment.

    1. Create a listener and add function update() for example in it.
    2. Make your fragment implements this listener update() method will be overridden in your fragment and here add the code you want, in your case you want to refresh the fragment so reload your data.
    3. Pass this listener to your adapter.
    4. In your adapter, see where you want to update your fragment lets say for example on-click method of button, here you call update() method from listener, and your fragment will be updated.