我想从存储在asset文件夹中的本地文件解析JSON,并将其设置为android中的recyclerview。但是,Recyclerview并没有填充。
任何人都可以告诉我这有什么问题吗? 我从这里尝试了许多答案,但它没有用。
JSON
{
"box": [
{
"text" : "text1 "
},
{
"text" : "text2"
},
{
"text" : "text3"
},
...............
]
}
CODE
private String loadJSONFromAsset() {
String json = null;
try {
InputStream is = getAssets().open("file.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
private void RequestJson() {
recyclerView = findViewById(R.id.mRecycler);
List<Box> data=new ArrayList<>();
try {
JSONObject json = new JSONObject(loadJSONFromAsset());
JSONArray tablelist = json.getJSONArray("box");
for (int i = 0; i < tablelist.length(); i++) {
JSONObject AllTable = tablelist.getJSONObject(i);
Box items2 = new Box();
items2.setText(AllTable.getString("text"));
data.add(items2);
}
mAdapter = new BoxAdapter(MainActivity.this, data);
recyclerView.setAdapter(mAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_LONG).show();
}
}
答案 0 :(得分:0)
改变这一点。并确保数据不为空。
mAdapter = new BoxAdapter(MainActivity.this, data);
recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
recyclerView.setAdapter(mAdapter);
mAdapter.notifyDataSetChanged();