Android Error with a Json File - E/FetchWeatherTask﹕ Error -
i'm getting error trying json file.
json:
http://api.openweathermap.org/data/2.5/forecast/daily?q=94043&mode=json&units=metric&cnt=7
error:
04-25 04:12:32.086 3875-3897/com.example.g250.dublinweather.app e/fetchweathertask﹕ error
code:
protected void doinbackground(void... params) { // these 2 need declared outside try/catch // can closed in block. httpurlconnection urlconnection = null; bufferedreader reader = null; // contain raw json response string. string forecastjsonstr = null; try { // construct url openweathermap query // possible parameters avaiable @ owm's forecast api page, @ // http://openweathermap.org/api#forecast url url = new url("http://api.openweathermap.org/data/2.5/forecast/daily?q=94043&mode=json&units=metric&cnt=7"); // create request openweathermap, , open connection urlconnection = (httpurlconnection) url.openconnection(); urlconnection.setrequestmethod("get"); urlconnection.connect(); // read input stream string inputstream inputstream = urlconnection.getinputstream(); stringbuffer buffer = new stringbuffer(); if (inputstream == null) { // nothing do. return null; } reader = new bufferedreader(new inputstreamreader(inputstream)); string line; while ((line = reader.readline()) != null) { // since it's json, adding newline isn't necessary (it won't affect parsing) // make debugging *lot* easier if print out completed // buffer debugging. buffer.append(line + "\n"); } if (buffer.length() == 0) { // stream empty. no point in parsing. return null; } forecastjsonstr = buffer.tostring(); //debugging log.v(log_tag, "json string" + forecastjsonstr); } catch (ioexception e) { log.e(log_tag, "error ", e); // if code didn't weather data, there's no point in attemping // parse it. return null; } { if (urlconnection != null) { urlconnection.disconnect(); } if (reader != null) { try { reader.close(); } catch (final ioexception e) { log.e(log_tag, "error closing stream", e); } } } return null; } }
there problem json file, can't figure out how fix it. can me?
thanks!!
just use volley json requests plain simple (see here volley) , here gson. in order include them add following gradle build file
compile 'com.google.code.gson:gson:2.3' compile 'com.mcxiaoke.volley:library:1.0.15'
this example of code make json request via volley. simpler
jsonobjectrequest jsonobjreq = new jsonobjectrequest(request.method.get, urljson, (string)null, new response.listener<jsonobject>() { @override public void onresponse(jsonobject response) { try { // parsing json object response gson gson = new gson(); // stuff here parse in model }catch (exception e) { // log here error } }, new response.errorlistener() { @override public void onerrorresponse(volleyerror error) { volleylog.d(logtag, "error: " + error.getmessage()); log.e(logtag, "error while executing getnetworkfeed"); } }); // adding request request queue getinstance().addtorequestqueue(jsonobjreq);
}
Comments
Post a Comment