(Android java, JSON) Why it lose the stored values?

Viewed 54

I have a JSONParser named class that finds all needed informations I need. I make an ArrayList variable and fill the data as it has to do. But... if I try to get this ArrayList from other activity, it does not give back any value...

public class JSONParser {
    ArrayList<Day> days = new ArrayList<>();

public JSONParser() {
    new getAllURLs().execute("https://...");
}

public ArrayList<Day> getDays() {
        return days;
}

public void writeout() {
        for (Day i : days) Log.e("Writeout", i.getDate());
    }
}

For example if I call the writeout() function from a function that's also in this JSONParser class, it works perfectly, I get all the dates in Logcat as I have to. But if I try this in the main activity:

    JSONParser jsonParser = new JSONParser();
    jsonParser.writeout();

It does not do anything... Does not write anything in Logcat. If I type this

jsonParser.writeout();

In main activity, and a simple

writeout();

in the activity where I parsed the json files and I run the app when both is in the code, I get the dates only once...

Maybe anyone knows why is this?

1 Answers

So whenever you call JSONParser jsonParser = new JSONParser(); you are creating a whole new object with its own arraylist (which may not have your URLs in it). What you want is a single object that all your classes can share. A simple and common way to do this is by using the singleton pattern.

https://www.javaworld.com/article/2073352/core-java/core-java-simply-singleton.html

public class JSONParser {
    private static JSONParser instance;

    private ArrayList<Day> days = new ArrayList<>();

    public static JSONParser getInstance(){
        if (instance == null){
            instance = new JSONParser();
        }
        return instance;
    }

    private JSONParser() {
        new getAllURLs().execute("https://...");
    }

    public ArrayList<Day> getDays() {
        return days;
    }

    public void writeout() {
        for (Day i : days) Log.e("Writeout", i.getDate());
    }
}

Now you'll call JSONParser.getInstance(); each time you need to use it instead of new JSONParser() and you'll get a single instance of the class.

Make sure to be careful that you're not trying to have multiple classes make writes on the arraylist at the same time! Or one writes while the other reads. This can lead to race conditions.

Related