java - Android App using OpenWeatherMap crashes when user inputs invalid City, how to handle 404 code from API? -
this question has answer here:
- what nullpointerexception, , how fix it? 12 answers
my app has weather implemented , using data openweathermap.
the user can input city weather via alert dialog code app crashes when input invalid city.
which in turn changes url to:
http://api.openweathermap.org/data/2.5/weather?q={invalid city here} &units=metric&appid={app id here}
and api returns {"cod":"404","message":"city not found"}, causes app crash!
my question is: how handle 404 code app doesn't crash notifies user need type in valid city. - apologise if waste of time guys, still learning , quite new this... more detailed explanations , non-condescending guidelines appreciated , me learn!
the alert dialog below:
private void showchangecitydialog() { alertdialog.builder builder = new alertdialog.builder(mainactivity.this); builder.settitle(r.string.change_city_title); final edittext cityinput = new edittext(mainactivity.this); cityinput.setinputtype(inputtype.type_class_text); cityinput.sethint("sofia,bg"); builder.setview(cityinput); builder.setpositivebutton(r.string.submit, new dialoginterface.onclicklistener() { @override public void onclick(dialoginterface dialog, int which) { if (cityinput.gettext().tostring().equals("")) { toast.maketext(mainactivity.this, "please type city name!", toast.length_long).show(); return; } citypreference citypreference = new citypreference(mainactivity.this); citypreference.setcity(cityinput.gettext().tostring()); string newcity = citypreference.getcity(); renderweatherdata(newcity); } }); builder.show(); }
this code renderweatherdata:
public void renderweatherdata(string city) { weathertask weathertask = new weathertask(); weathertask.execute(new string[]{city + "&units=metric"}); }
the error upon crashing is:
07-25 19:03:28.507 24691-25279/? e/androidruntime: fatal exception: asynctask #2 process: com.vladimirtumbev.android.footballscorekeeper, pid: 24691 java.lang.runtimeexception: error occurred while executing doinbackground() @ android.os.asynctask$3.done(asynctask.java:309) @ java.util.concurrent.futuretask.finishcompletion(futuretask.java:354) @ java.util.concurrent.futuretask.setexception(futuretask.java:223) @ java.util.concurrent.futuretask.run(futuretask.java:242) @ android.os.asynctask$serialexecutor$1.run(asynctask.java:234) @ java.util.concurrent.threadpoolexecutor.runworker(threadpoolexecutor.java:1113) @ java.util.concurrent.threadpoolexecutor$worker.run(threadpoolexecutor.java:588) @ java.lang.thread.run(thread.java:818) caused by: java.lang.nullpointerexception: attempt invoke virtual method 'int java.lang.string.length()' on null object reference @ org.json.jsontokener.nextcleaninternal(jsontokener.java:116) @ org.json.jsontokener.nextvalue(jsontokener.java:94) @ org.json.jsonobject.<init>(jsonobject.java:156) @ org.json.jsonobject.<init>(jsonobject.java:173) @ data.jsonweatherparser.getweather(jsonweatherparser.java:24) @ com.vladimirtumbev.android.footballscorekeeper.mainactivity$weathertask.doinbackground(mainactivity.java:465) @ com.vladimirtumbev.android.footballscorekeeper.mainactivity$weathertask.doinbackground(mainactivity.java:458) @ android.os.asynctask$2.call(asynctask.java:295) @ java.util.concurrent.futuretask.run(futuretask.java:237) @ android.os.asynctask$serialexecutor$1.run(asynctask.java:234) @ java.util.concurrent.threadpoolexecutor.runworker(threadpoolexecutor.java:1113) @ java.util.concurrent.threadpoolexecutor$worker.run(threadpoolexecutor.java:588) @ java.lang.thread.run(thread.java:818)
both classes extend asynctask:
private class downloadimageasynctask extends asynctask<string, void, bitmap> { @override protected bitmap doinbackground(string... params) { return downloadimage(params[0]); } @override protected void onpostexecute(bitmap bitmap) { iconview.setimagebitmap(bitmap); } private bitmap downloadimage(string code) { final defaulthttpclient client = new defaulthttpclient(); final httpget getrequest = new httpget(utils.weather_icon_url + code + ".png"); try { httpresponse response = client.execute(getrequest); final int statuscode = response.getstatusline().getstatuscode(); if (statuscode != httpstatus.sc_ok) { log.e("downloadimage", "error:" + statuscode); return null; } final httpentity entity = response.getentity(); if (entity != null) { inputstream inputstream = null; inputstream = entity.getcontent(); //decode contents stream final bitmap bitmap = bitmapfactory.decodestream(inputstream); return bitmap; } } catch (ioexception e) { e.printstacktrace(); } return null; } } private class weathertask extends asynctask<string, void, weather> { @override protected weather doinbackground(string... params) { string data = ((new weatherhttpclient()).getweatherdata(params[0])); weather = jsonweatherparser.getweather(data); weather.icondata = weather.currentcondition.geticon(); new downloadimageasynctask().execute(weather.icondata); return weather; } @override protected void onpostexecute(weather weather) { super.onpostexecute(weather); decimalformat decimalformat = new decimalformat("#.#"); string tempformat = decimalformat.format(weather.currentcondition.gettemperature()); cityname.settext(weather.place.getcity() + "," + weather.place.getcountry()); temp.settext("" + tempformat + "°c"); description.settext(weather.currentcondition.getcondition() + "(" + weather.currentcondition.getdescription() + ")"); } }
my http helper class:
public class weatherhttpclient { public string getweatherdata(string place){ httpurlconnection connection = null; inputstream inputstream = null; try { connection = (httpurlconnection) (new url(utils.weather_base_url + place + utils.weather_api_key)).openconnection(); connection.setrequestmethod("get"); connection.setdoinput(true); // connection.setdooutput(true); connection.connect(); if(connection.getresponsecode() == 200) // 200 ok { //read response stringbuffer stringbuffer = new stringbuffer(); inputstream = connection.getinputstream(); bufferedreader bufferedreader = new bufferedreader(new inputstreamreader(inputstream)); string line = null; while ((line = bufferedreader.readline()) != null) { stringbuffer.append(line + "\r\n"); } inputstream.close(); connection.disconnect(); return stringbuffer.tostring(); } } catch (ioexception e) { e.printstacktrace(); } return null; } }
my json weather parser class:
public class jsonweatherparser { public static weather getweather(string data){ weather weather = new weather(); //create json object data try { jsonobject jsonobject = new jsonobject(data); place place = new place(); jsonobject coordobj = utils.getobject("coord", jsonobject); place.setlat(utils.getfloat("lat", coordobj)); place.setlon(utils.getfloat("lon", coordobj)); //get sys object jsonobject sysobj = utils.getobject("sys", jsonobject); place.setcountry(utils.getstring("country",sysobj)); place.setcity(utils.getstring("name",jsonobject)); weather.place = place; //get weather info jsonarray jsonarray = jsonobject.getjsonarray("weather"); jsonobject jsonweather = jsonarray.getjsonobject(0); weather.currentcondition.setweatherid(utils.getint("id", jsonweather)); weather.currentcondition.setdescription(utils.getstring("description", jsonweather)); weather.currentcondition.setcondition(utils.getstring("main", jsonweather)); weather.currentcondition.seticon(utils.getstring("icon", jsonweather)); jsonobject mainobj = utils.getobject("main", jsonobject); weather.currentcondition.settemperature(utils.getdouble("temp", mainobj)); jsonobject cloudobj = utils.getobject("clouds", jsonobject); weather.clouds.setprecipitation(utils.getint("all", cloudobj)); return weather; } catch (jsonexception e) { e.printstacktrace(); return null; }
i have more model classes setters , getters , can add them if needed.
thank help!!!
here line stack trace important
caused by: java.lang.nullpointerexception: attempt invoke virtual method 'int java.lang.string.length()' on null object reference
you've got nullpointerexception (npe). trying length of string null, causes crash. there line number in stack trace points call occurs. find line , surround
try { //line throws exception } catch (exceptiontype name) { //do in case of exception }
Comments
Post a Comment