首页 > 解决方案 > 如何将 ArrayAdapter 和 JSONArray 用于 listView

问题描述

到目前为止,我可以向服务器发送一个 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();

}

当我按下按钮 Search 它发送请求:

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。到目前为止我是对的吗?

这是我卡住的地方,因为我不明白该怎么做。

提前谢谢了!

标签: javaandroidjsonarraylist

解决方案


尝试这个:

您需要添加阵列适配器

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它可以工作


推荐阅读