开发者

Updating arraylist in Application class

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 d开发者_JAVA百科ifferent 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?


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);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜