从数据库中填充JSONArray的问题

时间:2019-04-09 22:16:33

标签: java android json rest

我正在尝试更新我的旧应用程序,该应用程序基本上是一个共享的购物清单。它以前已链接到我学校的网站和数据库,但是由于无法访问,我对其进行了反向工程。 该应用最初是为SDK 23创建的 问题是它似乎没有使用this api填充JSONArray。
代码如下:

//MainActivity.java
@Override
    protected Long doInBackground(String... params) {
        HttpsURLConnection connection = null;
        try {
            URL itemListURL = new URL(itemList_URI);
            connection = (HttpsURLConnection) itemListURL.openConnection();
            connection.connect();
            int status = connection.getResponseCode();
            Log.d("HTTPS GET", "status " + status);
            if (status == HttpsURLConnection.HTTP_OK){
                InputStream is = connection.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(is));
                String responseString;
                StringBuilder sb = new StringBuilder();
                while ((responseString = reader.readLine()) != null) {
                    sb = sb.append(responseString);
                }
                String itemData = sb.toString();
                itemArrayList = Item.createItemList(itemData);
                .......
//Item.java
//Create ItemList
public static ArrayList<Item> createItemList(String jsonItemsString)
        throws JSONException, NullPointerException {
    ArrayList<Item> itemList = new ArrayList<Item>();

    JSONObject jsonData = new JSONObject(jsonItemsString);
    JSONArray jsonItemTable = jsonData.optJSONArray(TABLE_NAME)    
    for (int i = 0; i <= jsonItemTable.length(); i++) {
        JSONObject jsonItem = (JSONObject) jsonItemTable.get(i);
        Item thisItem = new Item(jsonItem);
        itemList.add(thisItem);
    }
    return itemList;
}

for循环抛出NullPointerException,这使我不相信JSONArray未填充。 这是网址和响应的图片:
URL-Results

所以要么无法读取值,要么数据库连接失败(我怀疑,因为没有错误表明它),但是我不知道如何验证这一点
对不起,这可能是一个麻烦的问题。我已经进行了将近4年的编程工作,所以有点生锈。我会很乐意提供所需的任何信息。

编辑:有人建议一个线程询问NullPointerException是什么,也许可以解决我的问题,但是我知道npe是什么,我只是弄不清楚为什么它会被抛出

更新:D / HTTP GET:状态200,应为“确定”?
我记录了itemData字符串,并获取了它,因此它至少可以获取数据: enter image description here 与jsonItemsString相同: enter image description here 可能是{“ records”:-弄乱了一部分吗?它曾经不在那里,但是似乎对api的更新添加了它。

1 个答案:

答案 0 :(得分:0)

好的,所以我找出问题出在哪里。 我所做的就是交换

JSONArray jsonItemTable = jsonData.optJSONArray(TABLE_NAME);

使用

JSONArray jsonItemTable = jsonData.getJSONArray("records");

在Item.java中
不知道为什么它在我的第一个版本中起作用,但是感谢所有评论并让我走上正轨的人!

相关问题