【问题标题】:How to use ArrayAdapter and JSONArray for a listView如何将 ArrayAdapter 和 JSONArray 用于 listView
【发布时间】:2018-08-06 01:33:16
【问题描述】:

到目前为止,我可以向服务器发送一个 Get 请求,并在 url 中添加一个字母:

private void GetDevice() {

    String deviceId = editTextDeviceId.getText().toString().trim();

    if(TextUtils.isEmpty(deviceId)){
        editTextDeviceId.setError("Please enter deviceId");
        editTextDeviceId.requestFocus();
    }

    HashMap<String, String>params = new HashMap<>();
    params.put("deviceID", deviceId);

    PerformNetworkRequest request = new PerformNetworkRequest(Api.URL_GETBYDEVICEID + deviceId, null, CODE_GET_REQUEST);
    request.execute();

}

当我按下“搜索”按钮时,它会发送请求:

buttonSearch.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            GetDevice();
        }
    });

服务器响应是 JSONArray :

W/System.err: org.json.JSONException: Value [{"DeviceId":"T","TransactionValue":2,"RSSI":2,"Time":"2018-08-02T14:43:00"}] of type org.json.JSONArray cannot be converted to JSONObject

这是我的问题。 根据我的阅读,我知道我需要使用 ArrayList 和 ArrayAdapter 将其转换为 JSONObject。到目前为止我是对的吗?

这就是我卡住的地方,因为我不知道该怎么做。

非常感谢!

【问题讨论】:

  • 看起来您正在尝试将字符串 json 转换为 JSONObject,但字符串结果是 JSONArray
  • 我的意思是这是我理解的,但在这一点上我很困惑。
  • 您的列表数据适配器是什么样的?

标签: java android json arraylist


【解决方案1】:

服务器返回的JSON字符串是一个Json数组,

所以需要如下转换成Jsonarray,这里的jsonString就是返回的JSON字符串。

        try {
            JSONArray array=new JSONArray(jsonString);
        } catch (JSONException e) {
            e.printStackTrace();
        }

【讨论】:

  • 是的,但你确定它不涉及 ArrayAdapter 吗?
  • 服务器返回 JSON 数组,您需要将其转换为数组适配器以显示在列表视图中,但这不是您遇到的问题。如何在列表视图中显示数据,看这里,github.com/MustafizurRahman/ListViewExample
  • 这是你的错误,类型 org.json.JSONArray 无法转换为 JSONObject
【解决方案2】:

你发送的参数是JSONArray,服务器需要的参数是JSONObjectJSONObject的结构类似于{ },而JSONArray类似于[ { } , { } , ...... , { } ]。所以,你可以将你的参数更改为{"DeviceId":"T","TransactionValue":2,"RSSI":2,"Time":"2018-08-02T14:43:00"}或编辑服务器的代码以接收JSONArray的参数。

【讨论】:

  • 我希望可以,但我无权访问服务器。另外我发送的是 GET 请求而不是 POST 请求,所以我不发送参数。
  • 好吧,我错了。你可以试试代码:try { org.json.JSONArray jsonArray = new org.json.JSONArray(json); JSONObject object = jsonArray.getJSONObject(0); } catch (JSONException e) { e.printStackTrace(); }
【解决方案3】:

试试这个:

您需要添加数组适配器

ArrayList<String> items = new ArrayList<String>();
for(int i=0; i < jArray.length() ; i++) {
json_data = jArray.getJSONObject(i);
String deviceID=json_data.getString("deviceID");
items.add(deviceID);
Log.d(deviceID,"Output"+deviceID);
}

ArrayAdapter<String> mArrayAdapter = new ArrayAdapter<String>(this,  
       android.R.layout.simple_list_item, items));
 setListAdapter(mArrayAdapter);

在 Hashmap 中添加设备 ID 就可以了

【讨论】:

  • 谢谢。当您说在 Hashmap 中添加设备 ID 时,您能否更具体一些?
  • 我也看不到变量 jArray, json_data 是什么?对不起,我开始了,这对我来说并不容易。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-10
  • 1970-01-01
  • 1970-01-01
  • 2013-08-24
相关资源
最近更新 更多