I have an app that is supposed to read a json file and inset its contents into a list view, I know this question was asked tons of times here but I can't understand why it's not working. I managed to narrow my problem to 1 line so far, JSONObject object = new JSONObject(readJSON());
. This is all of my code:
public class MainActivity extends AppCompatActivity {
ListView listView;
ArrayList<Post> arrayList;
private static final String TAG = "MyActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.lvPosts);
arrayList = new ArrayList<>();
try {
JSONObject object = new JSONObject(readJSON());
JSONArray array = object.getJSONArray("data");
for (int i = 0; i < array.length(); i++) {
JSONObject jsonObject = array.getJSONObject(i);
String productName = jsonObject.getString("productName");
String locationName = jsonObject.getString("locationName");
String price = jsonObject.getString("price");
String date = jsonObject.getString("date");
String description = jsonObject.getString("description");
String comment = jsonObject.getString("comment");
Log.i(TAG, price);
Post post = new Post();
post.setItemName(productName);
post.setLocationName(locationName);
post.setPrice(price);
post.setDate(date);
post.setDescription(description);
post.setExistingComment(comment);
arrayList.add(post);
}
} catch (JSONException e) {
e.printStackTrace();
}
PostAdapter adapter = new PostAdapter(this, arrayList);
listView.setAdapter(adapter);
}
public String readJSON() {
String json = null;
try {
// Opening data.json file
InputStream inputStream = getAssets().open("MOCK_DATA.json");
int size = inputStream.available();
byte[] buffer = new byte[size];
// read values in the byte array
inputStream.read(buffer);
inputStream.close();
// convert byte to string
json = new String(buffer, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
return null;
}
return json;
}
}
My problem is that once I run the app my listView will remain empty and wont be populated with data.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…