我正在构建一个应用程序,它接收json数组数据并将其添加到recyclerview。我能够在下面的代码中成功解析数据。
private void parseJsonDetails(String jsonDetails) throws JSONException {
JSONObject parentObject = new JSONObject(jsonDetails);
JSONArray parentArray = parentObject.getJSONArray("stores");
final DataModel[] models = new DataModel[parentArray.length()];
for (int i = 0; i < parentArray.length(); i++) {
JSONObject storeObject = parentArray.getJSONObject(i);
DataModel dataModel = new DataModel();
dataModel.setCity(storeObject.getString("city"));
dataModel.setName(storeObject.getString("name"));
dataModel.setLatitiude(storeObject.getDouble("latitude"));
dataModel.setLongtitude(storeObject.getDouble("longitude"));
dataModel.setZipcode(storeObject.getInt("zipcode"));
dataModel.setStoreLogoUrl(storeObject.getString("storeLogoURL"));
dataModel.setPhone(storeObject.getString("phone"));
dataModel.setStoreId(storeObject.getString("storeID"));
dataModel.setState(storeObject.getString("state"));
dataModel.setAddress(storeObject.getString("address"));
models[i] = dataModel;
}
解析后我尝试将其添加到recyclerview(如下所示)。通过将models []数组和上下文传递给recyclerview适配器。但我得到了错误 - &#34;只有创建视图层次结构的原始线程才能触及其视图&#34;
models[i] = dataModel;
}
storeAdapter = new StoreAdapter(models, this);
recyclerView.setAdapter(storeAdapter);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
}
}
现在我在这个网站上对这个错误进行了一些研究,并指出更新视图的后台任务应该在UI线程上运行。但是如何通过recyclerview完成这项工作?如何将解析后的数据添加到recyclerview适配器而不会出现此错误?
在API调用之后,从onResponse方法调用parseJsonDetails。
@Override
public void onResponse(Response response) throws IOException {
//Add catch around these methods
String jsonDetails = response.body().string();
if (response.isSuccessful()) {
try {
parseJsonDetails(jsonDetails);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
});
}