Android - 无法在Application类实例中存储列表

时间:2016-02-14 22:52:46

标签: java android arraylist global-variables

我试图将Application类实例中的列表存储为我的Android个应用程序中的全局变量。以下是我的Application班级代码:

public class DefectsApplication extends Application{

private NormalUser normalUser;

private ArrayList<Complaint> complaintList;

public String getTestString() {
    return testString;
}

public void setTestString(String testString) {
    this.testString = testString;
}

private String testString;

public NormalUser getNormalUser() {
    return normalUser;
}

public void setNormalUser(NormalUser normalUser) {

    this.normalUser = normalUser;
}

public ArrayList<Complaint> getComplaintList() {
    return complaintList;
}

public void setComplaintList(ArrayList<Complaint> m_complaints) {
    this.complaintList = complaintList;
}
}

以下是我的代码,它试图访问Application类实例中的字段:

DefectsApplication defectsApplication = ((DefectsApplication)getApplicationContext());
defectsApplication.setComplaintList(m_complaints);
defectsApplication.setTestString("urghhhhhhhhh");
ArrayList<Complaint> complaintList = defectsApplication.getComplaintList();
String s = defectsApplication.getTestString();

在上面的代码中,m_complaints是一个对象列表。当我尝试存储String时,它可以正常工作。但是对于一个清单,它并没有。请帮我解决这个问题。

1 个答案:

答案 0 :(得分:2)

可能正在发生错字:

public void setComplaintList(ArrayList<Complaint> m_complaints) {
    this.complaintList = complaintList;
}

您已将this.complaintList设置为自己,最初为null。尝试

public void setComplaintList(ArrayList<Complaint> m_complaints) {
    this.complaintList = m_complaints;
}