Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Android clean up Activity's member variables when the Activity become stopped

I have an Activity, where I initialize a class member variable in onCreate(). In some case, I need to startActivity() which means this Activity turn into stopped state. When I come back, I need to use the variable.

This works OK in most phones, but I also get some crash from my users because the member become null on their phones. This member just contains some String and a POJO.

Does Android clean up Activity's member variable to free up memory?

like image 923
L. Swifter Avatar asked Mar 23 '16 13:03

L. Swifter


People also ask

What happens when an activity is destroyed android?

Android destroys the activity, and then recreates it. The onCreate() method gets called, and the Bundle gets passed to it.

What does activity finish do?

On Clicking the back button from the New Activity, the finish() method is called and the activity destroys and returns to the home screen.

Which method is called by Android when the activity is freshly created?

onCreate() The Android activity lifecycle starts with the onCreate() method. This method is called when the user clicks on your app's icon, which causes this method to create the activity.

Does finish call onPause?

Android will generally call onPause() if you call finish() at some point during your Activity's lifecycle unless you call finish() in your onCreate() .

What is the difference between onPause and onStop?

If screen times out on your activity, then onPause is called. After sometime if you will not open the screen then onStop will be called.


1 Answers

Those member variables will be cleared out if onDestroy is called, even if the activity isn't finished. You can simulate this by turning on "Don't keep activities alive" in developer settings. Once that's enabled, start your activity and then pause it (i.e. hit the home button)

To get around this, you'll need to store those member variables in onSaveInstanceState, and then restore them using the savedState bundle in onCreate

like image 112
craya Avatar answered Oct 15 '22 22:10

craya