3

I have created an ArrayList in my Application class :

package a.b.layout;

import java.util.ArrayList;
import java.util.List;

import android.app.Application;

public class CommonData extends Application{

    ArrayList<Item> commonList;

    public ArrayList<Item> getList()
    {
        return commonList;
    }

    public void setList(ArrayList<Item> list)
    {
        commonList = list;
    }

}  

I am adding content to this arraylist in different activites and updating it each time.

CommonData objCommonData = ((CommonData)this.getApplication()); 
objCommonData.commonList.addAll(viewData);     //viewData is local arraylist  

But on doing so I get a Null Pointer Exception. Why is it so? Is there something I am missing?

1 Answer 1

1

You need to make sure you instantiate your ArrayList:

ArrayList<Item> commonList = new ArrayList<Item>();

You cannot add data to an ArrayList that hasn't been created yet.

EDIT

To show John's solution (see comments), edit your class:

public class CommonData extends Application{
     static ArrayList<Item> commonList = new ArrayList<Item>();
}  

Then you can do from somewhere else:

public void someWhereElse(){
    getApplication().commonList.add(item);
}
Sign up to request clarification or add additional context in comments.

5 Comments

This is exactly what I thought. But on instantiating it, won't I loose the previous data inside the arraylist. A new instance will be created every time.
In this case, it would be better to declare a separate static class (with a static ArrayList variable) to keep track of your list. You can also just declare a static ArrayList variable within your CommonData class and invoke calls via CommonData.commonList.addAll(), for example. You would then not need the line CommonData objCommonData = ((CommonData)this.getApplication());
I didn't clearly understood what you said. I'll really appreciate if you can put an example.(Edit your answer if possible).
@Stone, Herrmann did the honors. It should be noted though that this only works if your Application is created as a CommonData Object. In Android, this is not usually the case, and the above may not work. If it does not, comment, and I'll post the different code that would do it.
Thank you both for your contribution. I implemented onCreate in application class and followed what you suggested. Things are working fine now :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.