user3121574
user3121574

Reputation:

Lifecycle of a fragment when startActivityForResult() is called

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!

Upvotes: 1

Views: 1663

Answers (1)

user3121574
user3121574

Reputation:

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!

Upvotes: 2

Related Questions