Method to refresh Fragment content when data changed ( like recall onCreateView)
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();
}
}
Related videos on Youtube
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, 2021Comments
-
Heretyk over 2 years
I have an
Activity
with a fragment container in layout. 3 differentFragment
can be displayed in it. These fragments contains aListview
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 over 8 yearsUse adapter.notifyDataSetChanged(). It is meant for the exact purpose you are mentioning.
-
Sucho over 8 yearsThis is what you want! stackoverflow.com/questions/20702333/refresh-fragment-at-reload
-
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 over 7 yearsimplement a callback(interface) in fragment & when data is changed call it.
-
Zar E Ahmer over 7 years
-
Heretyk over 8 yearsI 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 over 8 yearsI used your code through a
Handler
on my main activity, it allowed me to handle the "static" considerations. Thanks -
Si8 over 7 yearsstackoverflow.com/questions/40095826/… Please help
-
Wasi Sadman about 5 yearsWell @Heretyk, I think you can use EventBus in that case.
-
Whiteq almost 5 yearsthis is the best solution for me
-
androidStud over 4 yearsReally!! 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 over 2 yearsHey @Tina can you please help me on this issue