Android: Parse Json In Listview
I have been trying to parse Json into A ListView but when i do so I get; 03-04 14:43:45.345: E/log_tag(16519): Error parsing data org.json.JSONException: No value for items It som
Solution 1:
By looking at the JSON result (by opening your example url) I see that 'items' is inside another JSONObject. So I believe you need to do:
JSONObject data = json.getJSONObject('data');
JSONArray array = data.getJSONArray('items');
Solution 2:
You dont need getJSON.java, only you should do to make it work is this:
privatestaticStringURL="http://gdata.youtube.com/feeds/api/users/UKFDubstep/uploads?v=2&alt=jsonc";
@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stubsuper.onCreate(savedInstanceState);
setContentView(R.layout.listplaceholder);
ArrayList<HashMap<String, String>> mylist = newArrayList<HashMap<String, String>>();
try{
HttpClienthttpclient=newDefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpGetrequest=newHttpGet(URL);
HttpResponseresponse= httpclient.execute(request);
HttpEntityresEntity= response.getEntity();
String_response= EntityUtils.toString(resEntity); // content will be consume only once
Log.i(".......",_response);
JSONObjectjson=newJSONObject(_response);
JSONArrayjarray= json.getJSONArray("items");
//Loop the Arrayfor(int i=0;i < array.length();i++){
HashMap<String, String> map = newHashMap<String, String>();
JSONObjecte= array.getJSONObject(i);
map.put("id", String.valueOf(i));
map.put("title", "" + e.getString("title"));
map.put("viewCount", "Views: " + e.getString("viewCount"));
mylist.add(map);
}
}catch(JSONException e) {
Log.e("log_tag", "Error parsing data "+e.toString());
}
ListAdapteradapter=newSimpleAdapter(this, mylist , R.layout.dubstep,
newString[] { "title", "viewCount" },
newint[] { R.id.item_title, R.id.item_subtitle });
setListAdapter(adapter);
finalListViewlv= getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(newOnItemClickListener() {
publicvoidonItemClick(AdapterView<?> parent, View view, int position, long id) {
@SuppressWarnings("unchecked")
HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);
Toast.makeText(dubstep.this, "ID '" + o.get("id") + "' was clicked.", Toast.LENGTH_SHORT).show();
}
});
}
But you should now that, parsing JSON data should not be executed in UI thread. You need to extend AsyncTask and do that job there in doInBackgound() method, so you can do parsing in seperate thread, not in UI...AsyncTask
Post a Comment for "Android: Parse Json In Listview"