首页 > 解决方案 > 列表项到列表视图

问题描述

我想将此程序转换为动态程序。从服务器获取 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;

标签: androidlistviewarraylist

解决方案


您已声明您的函数将返回 a Listof 个Item对象,但您返回的是 a Listof 个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;
}

推荐阅读