-3

I am running three AsyncTask() each AsyncTask create an object of another class.

This is how i am creating instance of a class from doInBackground(),

        DOM domObject = new DOM;

Now, there is a class level ArrayList in my DOM class,

public class DOM {
    public static ArrayList<HashMap<String, Object>> tempNewsArray = new ArrayList<>();

My main class run three AysncTask object so three separate instance of DOM class should be created for each AsyncTask.

On each execution of AsyncTask, some data is added into the ArrayList.

Example, First AsynTask executed, Some Data added in ArrayList. Second AsyncTask executed, Some Data added in ArrayList (Previous Data should not be there in ArrayList)

But the problem is, the data from the previous instance of DOM class is still there in the ArrayList and not removed when new instance of DOM class is created by another AysnTask instace.

Why is this happening ?

Example, First instance of DOM class created by first Asynctask, Some data is added in ArrayList.

Second instance of DOM class is created by second Asynctask instance, Some new data is added in the ArrayList but the previous data from previous instances is still there.

Why so ?

Joe
  • 1,488
  • 3
  • 16
  • 27
  • The `tempNewsArray` is `static` which means that all instances of `DOM` use the same `tempNewsArray` – Titus Jan 19 '15 at 19:37
  • but if i do like this, `public static ArrayList> tempNewsArray` and then create the instance of it inside another method like this, `new ArrayList<>();` then the data from previous `DOM` instance are not there. Why this behavior since the `ArrayList` is still `static`. – Joe Jan 19 '15 at 19:45

1 Answers1

2

tempNewsArray is static, so all Dom isntances share a single copy of that member, which is initialized just once, when the Dom class is initialized.

If you wish each Dom instance to have its own ArrayList member, change its declaration to :

public ArrayList<HashMap<String, Object>> tempNewsArray = new ArrayList<>();
Eran
  • 387,369
  • 54
  • 702
  • 768
  • but if i do like this, `public static ArrayList> tempNewsArray` and then create the instance of it inside another method like this, `new ArrayList<>();` then the data from previous `DOM` instance are not there. Why this behavior since the `ArrayList` is still `static`. – Joe Jan 19 '15 at 19:44
  • @Joe If you overwrite the `tempNewsArray` reference by assigning to it a new ArrayList isntance, the old ArrayList object is no longer referred by that static variable, but it doesn't change the fact that there is only one `tempNewsArray` member shared by all instances. When you initialize the static member in a static initialization expression (or in a static initializer block), it will be initialized just once. – Eran Jan 19 '15 at 19:50