Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object becomes null [closed]

Hi We are facing a strange issue in our android application. In our app we are storing all needed objects/data in a Common object(called as object A) when we start the app(First Activity). We stored the context itself in that object. Whenever we need context in our app we are getting the context from object A and using it. All the cases its working fine except below cases.

i) While our app is in background, we played some high end games. Now we went back to the app via minimized screen(recent apps). Suddenly the app is crashed.
ii) If we do force stop the app via Settings, and came back to the app via minimized screen the same crash happens.

Both the cases, Object A becomes null(it might be removed by GC), so all operations dependent on object A getting exceptions.

Why is it happening? How do we prevent GC from collecting object A? How can we deal with the force stop? Please give any ideas.

like image 563
Ponsuyambu Avatar asked Oct 09 '13 13:10

Ponsuyambu


2 Answers

Why is it happening?

Other apps need memory to run as well. It is unreasonable to assume that Android will keep your data in memory indefinitely.

How do we prevent GC from collecting object A?

Don't. Find a different solution to your problem.

How can we deal with the force stop? Please give any ideas.

In the end, the decision is up to you, but here are a few common options:

  • When the stored data no longer exists, treat this as a fresh launch of the app. Bring the user to the landing page and have him start a new game.
  • Persist the data. Depending on what your are storing, SharedPreferences or SQLite may be good options. See Storage Options for a summary of your storage options.

The second option obviously won't work for your Context, but I would probably architect a different solution for the Context anyway.

like image 125
Bryan Herbst Avatar answered Nov 17 '22 03:11

Bryan Herbst


You better use the application context for that! Simply use getApplicationContext() in your Activity and use this instead. Otherwise your activity leaks as soon as the system needs memory.

Your Activity gets in the background when pressing home, when then playing videoGames or memory consuming apps, your activity gets freed by the system.

Try to understand the Activity Lifecycle to solve this:

enter image description here

Furthermore when seeing it in "normal" java your Wrapped object for the activity gets collected by the GC as soon as its eligable for it, i.e. it isnt referenced by any other objects anymore. This can't be prevented if your whole app gets freed when the system needs memory. Try to check for null in onResume() and re-instantiate your Object again!

I hope this may help you.

like image 2
Thkru Avatar answered Nov 17 '22 02:11

Thkru