2

I am using a Fragment to start a new Activity using startActivityForResult(), I am getting the result (Bundle) in onActivityResult() method.Since onActivityResult() called before onResume().I want to make sure, I keep/save the Bundle properly so that when Fragment's onResume() gets called, I get the kept/saved result to perform further action.

What are the different ways to achieve this. I tried using getArguments()/setArguments(), but that seems to be not the right way to achieve this.

Brijesh Thakur
  • 6,768
  • 4
  • 24
  • 29

1 Answers1

2

Try this

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == MY_REQUEST) {
        // Make sure the request was successful
        if (resultCode == RESULT_OK) {
            mResultBundle = data.getExtras(); //mResultBundle is in fragment 
            //scope
        }
    }
}

@Override
protected void onResume(){
    super.onResume();
    if(mResultBundle != null){
       // process saved bundle from activity result here

       // don't forget to set it back to null once you are done
       mResultBundle = null;
    }
}
Much Overflow
  • 3,142
  • 1
  • 23
  • 40
  • I want to try the proper way, using variables or methods may also lead to crash, since Fragment itself may not be available while using member variables. – Brijesh Thakur Feb 18 '16 at 09:33
  • Whenever the onActivityResult method is called. There will be a fragment instance. On that instance you assign the result as a member variable. What do you think could go wrong in this scenario? – Much Overflow Feb 18 '16 at 09:39
  • There may not be a fragment instance, Since onActivityResult() gets called before fragment is ready. Read this : http://steveliles.github.io/android_activity_lifecycle_gotcha.html – Brijesh Thakur Feb 18 '16 at 09:50
  • If you are using the **Fragment's** `onActivityResult` method, In order for that method to be called by the system, there has to be an instance of the fragment, right? Or am I missing something obvious here! – Much Overflow Feb 18 '16 at 10:03
  • Not sure !! You might be right. But is there any other way I can use , For ex: Bundle to pass in onResume() – Brijesh Thakur Feb 18 '16 at 10:13
  • I provided the easy solution here. If you want you can use SharedPreference or a Singleton ViewModel class to hold the data till you hit onResume – Much Overflow Feb 18 '16 at 10:15
  • The solution you have provided, is simple one and I've already tried before posting question. My question is, how can I pass data from onActivityResult() to onResume() – Brijesh Thakur Feb 18 '16 at 10:23
  • You cannot pass any extra info directly to onResume. Your only option is to save the data somewhere until the lifecycle method is hit by the system. – Much Overflow Feb 18 '16 at 10:37