【问题标题】:Android - can't store a list in the Application class instanceAndroid - 无法在 Application 类实例中存储列表
【发布时间】:2016-02-14 22:52:45
【问题描述】:

我正在尝试将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 时,它可以工作。但对于一个列表,它没有。请帮我解决这个问题。

【问题讨论】:

  • “我正在尝试将一个列表作为全局变量存储在 Application 类中”——您为什么认为这是个好主意? “但对于一个列表,它没有”——请解释“它没有”是什么意思。你的症状是什么?你在崩溃吗?您是否收到编译错误?
  • 是的。我会解释得更多。当我试图从 Application 类中获取它时,complaintList 总是为空。实际上,Onik 已经给出了答案。只是Application类中list的setter方法打错了。

标签: java android arraylist global-variables


【解决方案1】:

可能是有错别字:

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

您将 this.complaintList 设置为最初的 null。试试

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

【讨论】:

    猜你喜欢
    • 2015-01-28
    • 2017-04-04
    • 2023-03-22
    • 1970-01-01
    • 2016-06-16
    • 2013-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多