列出项目到列表视图

时间:2018-06-27 15:05:47

标签: android listview arraylist

我想将此程序转换为动态程序。从服务器获取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'的执行失败。

  

编译失败;有关详细信息,请参见编译器错误输出。   信息:13秒内失败   信息: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;

1 个答案:

答案 0 :(得分:0)

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