Question

I've recently started Android programming and have run into many problems, but have been able to solve all except this one. For the sake of simplicity, I'll try to sum up what is happening.

  • I have a MainActivity, which has a static ArrayList
  • I go into a sub-activity, where I change the value of the ArrayList of MainActivity
  • I leave the sub-activity, entering MainActivity
  • I check the value of this ArrayList, and it now contains null values

Putting Logcat statements before and after the super.oncreate() call in MainActivity.onCreate(), I can see that some part of super.onCreate() changes the previous correct values in the ArrayList to null.

In case it is important, this static ArrayList contains custom (serializable) objects, each of which contains an ArrayList of custom (serializable) objects whose values themselves are null.

If that's confusing, I'll try to represent it in pseudo-code:

static ArrayList<CustomObject>

CustomObject{ 
      ArrayList<OtherCustomObject> //values of this ArrayList become null
}

Of course if more information is needed, I will try to provide as much as I can.

Was it helpful?

Solution

Regardless of why this happening in your case, storing a list like this in a static variable and expecting it to be there (with no plan to recreate it) is not a good idea since the system could decide to kill your process when it's low on memory. When the user attempts to reenter your app, you will have null values as the system tries to recreate the activity.

If the data is important, write it out to a file (you said it was already Serializable) and read it when you start the main activity.

OTHER TIPS

Static data lives until either

  1. the VM shuts down,
  2. the process terminates, or
  3. the class is unloaded.

None of these are happening in your described case. The VM is up, process is running and Dalvik doesn't unload classes. Please provide additional info to repro the issue.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top