java - 如何将 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。到目前为止我是对的吗?
这是我卡住的地方,因为我不明白该怎么做。
提前谢谢了!
解决方案
尝试这个:
您需要添加阵列适配器
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它可以工作
推荐阅读
- ruby-on-rails - FriendRequestsControlle#show 中的 ActiveRecord::RecordNotFound 错误
- sql-server - 使用 SQL Server 地理数据类型
- android - Android 从右到左语言支持
- ruby - 删除多余的空格,但在字符串中保留一个空格
- go - 转到通道,tcp/ip 端口映射不返回所有打开的端口
- sql - 查询表的一个城镇中的两列
- r - 传说在 R 中摆脱了多个图的对齐
- google-sheets - 在谷歌表格中查找和替换
- python - Python 类型错误问题 TypeError: unsupported operand type(s) for -: 'Table' and 'float'
- python - Django-Filter:ModelChoiceFilter 使用与当前用户相关的查询集