Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onBackPressed and call refresh function android

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();
}
like image 722
Lester Avatar asked Sep 28 '26 10:09

Lester


1 Answers

Although its a Conventional java.lang.NullPointerException: But I want make few things clear here for the cause of it .

1. super.onBackPressed(); will finish() the Activity so you can not make any transactions on its BackStack.

2. You want to refresh fragment then you should get the current fragment from FragmentManager to Refresh it .

FragmentProfile fragment = new FragmentProfile();

This will give you a new Fragment which is not attached yet and calling anything on it does not make any sense . This is the reason FragmentTransaction is null and getActivity() will be also null for new Fragment.

Cause getFragmentManager() by definition Returns the FragmentManager of Activity. And your new Fragment is not attached yet so it will return null.

getFragmentManager() Return the FragmentManager for interacting with fragments associated with this fragment's activity.

So your code should look like below .

 @Override
public void onBackPressed() {
    if(SomeCondition) {
        FragmentProfile fragment = //Get the Fragment from Fragment Manager Here
        fragment.refreshFragment();
    }else {
        super.onBackPressed();
    }
}

I have put a condition in onBackPressed() cause you do not want to completely disable the Back button. If you are using a Layout as container for Fragments you can get Fragment by following two methods in Activity.

getSupportFragmentManager().findFragmentById();
getSupportFragmentManager().findFragmentByTag();

EDIT:- Question wasn't clear enough . What OP want to achieve can be simply done with startActivityForResult();. Please see How to manage startActivityForResult on Android?.

like image 77
ADM Avatar answered Sep 30 '26 00:09

ADM



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!