简体   繁体   中英

onStop() is being called right after onCreate()

I need to use onStop() to free resources as bitmaps and bgms, and I'm facing the problem that onStop() takes too long to execute. So in the worst case scenario, the user would exit an activity and re-enter it (in less than 1 second lets say), so the activity runs onCreate() and then it proceed to call onStop() (which I suppose it's called from when the user exited it).

So obviously, onCreate() is loading resources, but the onStop() call are freeing them right after, causing a null pointer exception.

Any possible solutions?

It's hackish, but you could work out how long it usually takes to free the resources and set a timer in onCreate() that waits until onStop() is surely done, then re-load any null resources. Almost surely there is a better solution, but if nothing else then you could do this.

Tried this solution, but it's not the way I was planning to do this.

Since the error I'm getting is a NullPointerException caused by the fact that the late onStop() call is releasing every resourse loaded onCreate() , I'm just adding a try-catch block catching the NullPointerException and calling a function to reload the resources

If you use the onStart() callback method to create all the resources that are released in onStop() , the problem will be resolved.

You get NullPointerException because you think onCreate () is called but it is not.
OnStop () can be called without the Activity be destroyed, in this case onStart () is called instead of onCreate() , so, if the the resources been created in onStart() , this will prevent the NullPointerException .
See Android documentation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM