繁体   English   中英

尝试将JSON数据放入视图列表php + json + java时出现android错误

[英]android error when trying to put json data in viewlist php+json+java

我正在尝试使用PHP,JSON和SQL为我的Andriod应用程序创建搜索页面。

这是给我错误的代码:

  try{
        JSONArray jArray = new JSONArray(result);
        int jArrLeng = jArray.length();
        for(int i=0; i<jArrLeng;i++){
            JSONObject json_data= jArray.getJSONObject(i);

            tempID += json_data.getString("ID") + "\n";
            tempID += json_data.getString("heading") + "\n";
            tempID += json_data.getString("rank") + "\n:";

        }

        arr = tempID.split(":");
        resultLV.setAdapter(new ArrayAdapter<String>(SearchPage.this, android.R.layout.simple_list_item_1,arr));



    }catch (Exception e){
        String errMsg = "error when putting the json data in the list";
        Toast.makeText(getApplicationContext(), errMsg, Toast.LENGTH_LONG).show();
    }

我已经在另一页上使用了此代码,它可以完美地工作,但是当将其用于另一页/活动时,尝试将json数据放入listview时却给了我一个错误。

我猜问题是当我设置ArrayAdapter时,我做错了什么吗?

resultLV.setAdapter(new ArrayAdapter<String>(SearchPage.this, android.R.layout.simple_list_item_1,arr));

要回答您的最后一个问题:

    //array list
     List<String> your_array_list = new ArrayList<String>();
     try{
    JSONArray jArray = new JSONArray(result);
    int jArrLeng = jArray.length();
    for(int i=0; i<jArrLeng;i++){
        JSONObject json_data= jArray.getJSONObject(i);

        your_array_list.add(json_data.getString("ID") + "\n");
        your_array_list.add(json_data.getString("heading") + "\n");
        your_array_list.add(json_data.getString("rank") + "\n:");

      }
    resultLV.setAdapter(new ArrayAdapter<String>(SearchPage.this, android.R.layout.simple_list_item_1,your_array_list));

    //then, to get the items from inside the adapter:
    for(String item_in_list : your_array_list){
        System.out.println(item_in_list);
    }

要回答原始问题:

请访问http://jsonformatter.curiousconcept.com/了解格式问题

尝试查看以下信息: http : //www.json.org/javadoc/org/json/JSONObject.html#JSONObject%28java.lang.String%29

的JSONObject

public JSONObject(java.lang.String source)
           throws JSONException

从源JSON文本字符串构造JSONObject。 这是最常用的JSONObject构造函数。

Parameters:
    source - `A string beginning with { (left brace) and ending with } (right brace).` 
Throws:
    JSONException - If there is a syntax error in the source string or a duplicated key.

仅供参考:内置的JSONObject和JSONArray无法用于获取某些json响应。

您可以尝试从此链接https://json-simple.googlecode.com/files/json-simple-1.1.1.jar下载名为“ json-simple-1.1.1.jar”的小型库。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM