0

I have a class that loads data from an API and stores/ handles the results as a POJO. It looks roughly like this (some stuff omitted that doesn't concern the question):

public class ResultLoader {

    Search search;
    Result result;

    static ResultLoader instance;

    private ResultLoader() {

    }

    public static synchronized ResultLoader getInstance() {

        if (instance == null) {
            instance = new ResultLoader();
        }

        return instance;

    }

    public void init(@NonNull Search search) {
        this.search = search;
    }
}

The Result object can get so large that it becomes too large to be passed around Activities via Intents, so, as you can see, I designed the ResultLoader as a Singleton so every class can access the Result object.

I simulate the Android device running low on memory by limiting background processes to one, then switch around some apps, go back to my app.

On my ResultLoader's instance, either the Result object became null or the instance was recreated; i checked this with

ResultLoader.getInstance().getResult() == null

How can this be and what can I do to prevent this?

fweigl
  • 21,278
  • 20
  • 114
  • 205

2 Answers2

1

Your objects GC'ed because android killed your app. So it destroyed all loaded classes with static data. Next time when you get back to your app new app created and new ResultLoader class loaded with instance field equals null. When you try to get instance via getInstance method new instance created with empty result.

You should save your Result to persistent memory. E.g. when you get result save it to a file. And when you create ResultLoader check that file exists and load data from a file. Or load result again if your app got killed.

Leonidos
  • 10,482
  • 2
  • 28
  • 37
0

In android, your app can and will be recreated due to numerous reasons (low memory being one of them).

See this answer here to implement a saveinstancestate behavior on a custom class.

Community
  • 1
  • 1
Evripidis Drakos
  • 872
  • 1
  • 7
  • 15