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);
}
精彩评论