1

I have a snippet of code that calls startActivityForResult() to pick an image from the Android gallery. I have trouble understanding the lifecycle of the fragment from when startActivityForResult() is called and onActivityResult() is activated.

My activity retrieves and loads information onto a listview. It then allows user to insert pictures into the listview by sending an intent to the camera/gallery app using startActivityForResult(). This part works perfectly. The problem is that the list loses its data when the app returns from the intent and has to retrieve the information again. I have setRetainFragment(true) already.

My question is, is there any way to retain this data from when the intent is started and when it is returned? My guess would be to save an instance of it in onPause() and onResumse() but I don't quite understand how its lifecycle goes during this event.

Thank you in advance!

1 Answers1

2

I have found a solution to my problem. To answer my question about the lifecycles, the fragment does go through the onDetach(), onAttach(), onCreateView() process. However, because i set onRetainInstance(true), it skips onDestroy() and onCreate(). The reason why my data is loss, is because I retrieve the data during onCreateView() and since onCreateView() is called everytime, so is retrieving data. From this, all I had to do was check if the list is empty before retrieving my data.

Another side problem, however, is that my variables are not retained. Although the list is retained and therefore my listview remains the same, boolean and int variables are reset and I don't know have a solution for this yet. If anyone can help, that would be great!

  • 1
    It sounds like you need to override `onSaveInstanceState()`. – Code-Apprentice May 18 '14 at 06:55
  • I actually tried that already, but no luck sadly. I override onSaveInstanceState() in my fragment and placed my variable in the outState bundle. However, when I went to retrieve my variables in onCreateView, the savedInstanceState bundle is always null. Any help? –  May 18 '14 at 07:11
  • I suggest checking the `savedInstanceState` bundle that is sent to `onCreate()` instead. – Code-Apprentice May 18 '14 at 07:13
  • I am using setRetainInstance(true) so when the fragment is reattached, it skips onCreate(). I was also reading through http://stackoverflow.com/questions/20550016/savedinstancestate-is-always-null-in-fragment It says that the bundle is always null with setRetainInstance. I'm not sure how to get around this now. –  May 18 '14 at 07:15
  • Can you remove `setRetainInstance()` from your code? – Code-Apprentice May 18 '14 at 07:21
  • Nevermind, I have resolved the problem. SetRetainInstance(true) does in fact persists all variables. I was just logging the wrong variable :D But thanks very much for your help anyways. Your answer would definitely be correct if I wasn't using setRetainInstance(true). –  May 18 '14 at 07:23