Exception in parsing json object in android -
i making connection url inorder retrieve json data , later parsing it. here code
protected string doinbackground(object... params) { int responsecode = -1; try { url headingurl = new url("http://blog.teamtreehouse.com/api/get_recent_summary/?count=10"); // create url object httpurlconnection connection = (httpurlconnection) headingurl.openconnection(); //we make connection object connect url connection.connect(); // connection required url & may throw io exception responsecode = connection.getresponsecode(); if (responsecode == httpurlconnection.http_ok) { inputstream inputstream = connection.getinputstream(); // catching data in input stream can of type reader reader = new inputstreamreader(inputstream); //reading inputstream byte byte int contentlength = connection.getcontentlength(); // creating size store data character character char[] chararray = new char[contentlength]; //character array store data reader.read(chararray); // reading inputstream , storing in char array string responsedata = new string(chararray); //converting char string jsonobject jsonresponse = new jsonobject(responsedata); string status = jsonresponse.getstring("status"); // test log.v(tag, status); // test purpose jsonarray jsonarray = jsonresponse.getjsonarray("posts"); (int = 0; <= jsonarray.length(); i++) { jsonobject individualpost = jsonarray.getjsonobject(i); string title = individualpost.getstring("title"); log.v(tag, "title" + + ":" + " loop "); } } else { log.i(tag, "unsuccesful code :" + responsecode); } } catch (malformedurlexception e) { log.e(tag, "exception caught ", e); } catch (ioexception e) { log.e(tag, "exception caught ", e); } catch (exception e) { log.e(tag, "exception caught ", e); } return "code : " + responsecode; }
after getting json data in responsedata string not able parse it, , catching exception (3rd catch block) ,can tell problem , how overcome this. thanks
i think problem reading input stream .try function read input stream.
public static string gettextfromstream(inputstream inputstream)throws ioexception{ stringbuilder total = new stringbuilder(); string line=""; bufferedreader reader = new bufferedreader(new inputstreamreader(inputstream)); while ((line = reader.readline()) != null) { total.append(line); } return total.tostring(); }
use :
string responsedata=gettextfromstream(inputstream);
Comments
Post a Comment