Lester :
I want to refresh just one fragment that in an tab bar activity when I press the back button. How can i achieve that? What I tried
java.lang.NullPointerException: Attempt to invoke virtual method 'android.support.v4.app.FragmentTransaction android.support.v4.app.FragmentManager.beginTransaction()' on a null object reference
Fragment Profile
public void refreshFragment(){
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.detach(this).attach(this).commit();
}
Edit profile activity
@Override
public void onBackPressed() {
super.onBackPressed();
FragmentProfile fragment = new FragmentProfile();
fragment.refreshFragment();
}
Wan :
You can use SharedPreferences to do this.
Step 1: create a constants class.
public class Constants {
public static final String REFRESH = "refresh_content";
}
Step 2: put boolean to the constants.REFRESH on Edit Profile Activity,
private SharedPreferences pref;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
pref = PreferenceManager.getDefaultSharedPreferences(getContext());
return inflater.inflate(R.layout.fragment_rostering, container, false);
}
public void onBackPressed() {
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean(Constants.REFRESH, true);
editor.commit();
super.onBackPressed();
}
Step 3: Call refresh function on the onResume on Fragment Profile
private SharedPreferences pref;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
pref = PreferenceManager.getDefaultSharedPreferences(getContext());
return inflater.inflate(R.layout.fragment_profile, container, false);
}
@Override
public void onResume() {
super.onResume();
if(pref.getBoolean(Constants.REFRESH, false)){
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean(Constants.REFRESH, false);
editor.commit();
refreshFragment();
}
}