【问题标题】:In android my pojo class instance are getting null value在 android 中,我的 pojo 类实例正在获取空值
【发布时间】:2017-01-27 15:46:56
【问题描述】:

我创建了一个 pojo 类.. 我存储从 api 获取的数据..

在 MainActivity.java 我使用 loopj 来解析 json 数据

storeList = new ArrayList<AllStore>();
                try {
                    JSONArray jsonArray = new JSONArray(new String(responseBody));
                    for (int i = 0; i < jsonArray.length(); i++) {
                        store = new AllStore();

                        store.setLocation(jsonArray.getJSONObject(i).getString("storeName"));
                        store.setAddress(jsonArray.getJSONObject(i).getString("address"));

我的pojo课

AllStore.java

public class AllStore{

String storeName;
String address;

public AllStore(String storeName, String address){
this.storeName= storeName;
this.location = location;
}

public AllStore{

}

public String getLocation() {
        return location;
    }

    public void setLocation(String location) {
        this.location = location;
    }

public String getStoreName() {
        return storeName;
    }

    public void setStoreName(String storeName) {
        this.storeName = storeName;
    }

}

在其他java类中..而不是我在做的适配器类

AllStore allStore = new Allstore();

mText.setText(allStore.getStoreName);

这里 allStore.getStoreName 值为 null 显示..如何解决这个问题..

请帮忙

【问题讨论】:

  • 使用调试器,顺便说一下 this.location = location;虽然构造函数中没有名为 location 的参数
  • 您在此处提供的代码存在多个问题。它甚至不应该编译。
  • 为什么是@lupz ??它的编译

标签: java android json instance pojo


【解决方案1】:
AllStore allStore = new Allstore();

mText.setText(allStore.getStoreName());

在这里,您正在使用默认构造函数创建一个新对象 Allstore

public AllStore{

}

如果您调用 .getStoreName,它将返回 null,因为您还没有设置任何值。

在另一种方法中,您必须将存储对象添加到数组列表中

store.setLocation(jsonArray.getJSONObject(i).getString("storeName"));        
store.setAddress(jsonArray.getJSONObject(i).getString("address"));
storeList.add(store);

稍后如果您想使用列表中的项目名称,您可以这样做:

mText.setText(storelist.get(index).getStoreName());

其中index 是项目列表中的位置。

【讨论】:

  • 是的,我已经添加了 storeList.add(store);在 mainActivity.. 我在一个非常不同的类中使用此文本.. 那么我将如何到达 storelist.get(position) 位置我无法获得 r8 ??
  • 你必须得到你想要使用的对象,在这种情况下,必须将商店列表发送到班级。您可以创建一个异步任务以从 json 获取项目并放入 storelist 中,然后将其返回到您需要的地方。
猜你喜欢
  • 2016-06-16
  • 2023-03-28
  • 2018-07-04
  • 1970-01-01
  • 2018-10-23
  • 1970-01-01
  • 2012-10-12
  • 1970-01-01
  • 2016-12-20
相关资源
最近更新 更多