Read Json File In Android And Populate In Listview
I write this piece of code for reading json file and show it in listview but it return empty list . I would appreciate if anybody advise me. Thanks eventList.json: { 'events'
Solution 1:
The variable sb
holds the consumed JSON data.
There was no reference to actual JSON object as it was empty.
JSONObject jsonObjMain = newJSONObject();
Change the code block:
try {
JSONObject jsonObjMain = newJSONObject(sb.toString());
JSONArray jsonArray = jsonObjMain.getJSONArray("events");
// ...
There is a undefined reference to the JSON field, "msg", maybe it should be "event"?
// Getting data from individual JSONObject
String message = jsonArray.getString(i);
messages.add(message);
Solution 2:
Change to below code :
publicclassJsonActivityextendsAppCompatActivity {
@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_json);
// Reading json file from assets folderStringBuffer sb = newStringBuffer();
BufferedReader br = null;
try {
br = newBufferedReader(newInputStreamReader(getAssets().open(
"eventList.json")));
String temp;
while ((temp = br.readLine()) != null)
sb.append(temp);
} catch (IOException e) {
e.printStackTrace();
} finally {
if ((br != null)) {
try {
br.close(); // stop reading
} catch (IOException e) {
e.printStackTrace();
}
}
}
try {
JSONObject jsonObjMain = newJSONObject(sb.toString());
JSONArray jsonArray = jsonObjMain.getJSONArray("events");
ArrayList<String> messages = newArrayList<String>();
for (int i = 0; i < jsonArray.length(); i++) {
// Creating JSONObject from JSONArrayJSONObjectobject = jsonArray.getJSONObject(i);
String message = object.getString("event");
messages.add(message);
}
ArrayAdapter<String> adapter = newArrayAdapter<String>(JsonActivity.this,
android.R.layout.simple_list_item_1, messages);
ListView list = (ListView) findViewById(R.id.eventList);
list.setAdapter(adapter);
list.setOnItemClickListener(newAdapterView.OnItemClickListener() {
@OverridepublicvoidonItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(JsonActivity.this, "TEST List View", Toast.LENGTH_SHORT).show();
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Post a Comment for "Read Json File In Android And Populate In Listview"