android - 列表项到列表视图
问题描述
我想将此程序转换为动态程序。从服务器获取 JSON 并返回到列表项。
public List<Item> getData() {
return Arrays.asList(
new Item(1, "Everyday" , "$12.00 USD"),
new Item(2, "Small Porcelain Bowl", "$50.00 USD"),
new Item(3, "Favourite Board", "$265.00 USD"),
);
}
我解析了 json 但返回类型错误。
Error:(73, 8) error: incompatible types: List<String> cannot be converted to List<Item>
错误:任务“:app:compileDebugJavaWithJavac”执行失败。
编译失败;有关详细信息,请参阅编译器错误输出。信息:BUILD FAILED in 13s 信息:2 个错误
这是我的代码:
List<String> listItems = new ArrayList<String>();
try {
URL arc= new URL(
"https://arc.000webhostapp.com/data/Cse.json");
URLConnection tc = arc.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
tc.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
JSONArray ja = new JSONArray(line);
for (int i = 0; i < ja.length(); i++) {
JSONObject jo = (JSONObject) ja.get(i);
listItems.add(jo.getString("text"));
}
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return listItem;
解决方案
您已声明您的函数将返回 a List
of 个Item
对象,但您返回的是 a List
of 个String
对象。在解析从服务器获取的 JSON 时,您必须将其转换为与Item
您在代码的离线版本中所做的相同的对象。
根据您的代码判断,您从服务器下载的 JSON 如下所示:
[
{
id: 1,
text: "Everyday",
price: "$12.00 USD"
},
{
id: 2,
text: "Small Porcelain Bowl",
price: "$50.00 USD"
},
{
id: 3,
text: "Favourite Board",
price: "$265.00 USD"
},
]
然后,您的函数应如下所示:
public List<Item> getData() {
List<Item> listItems = new ArrayList<Item>();
try {
URL arc= new URL(
"https://arc.000webhostapp.com/data/Cse.json");
URLConnection tc = arc.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
tc.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
JSONArray ja = new JSONArray(line);
for (int i = 0; i < ja.length(); i++) {
JSONObject jo = (JSONObject) ja.get(i);
listItems.add(new Item(jo.getInt("id"), jo.getString("text"), jo.getString("price")));
}
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return listItems;
}
推荐阅读
- sql-server - 触发器适用于 UPDATE/INSERT,但在通过 BCP 运行时失败(日期格式问题)
- javascript - 将鼠标光标悬停在左列的滚动条上时保存右列的内容
- perl - ld:无法识别的选项'-Wl,-O1'
- amazon-web-services - AWS QuickSight:将视觉对象连接到多个数据集
- python - 使用类时出现 NameError
- javascript - 当我提交表单时,onsubmit 功能似乎不起作用
- java - Activity 如何从后台服务获取最新更新?
- javascript - CSS长宽比和-webkit-aspect-ratio不起作用
- tensorflow - TensorFlow Keras 预测 one-hot-vectors
- azure - 使用 terraform 将 Azure rbac 角色分配给虚拟机