java - How to handle with Httpurlconnection exception in android -
i have trouble httpurlconnection exception. when app can't connect server i'm getting error "unfortunately, myapp has stopped". set timeout , after time elapsed doesn't work properly.
here connection class code called in async task class in doinbackground method.
public class httpurlreq { httpurlconnection conn; url url = null; inputstream inputstream; bufferedoutputstream os; public static final int connection_timeout = 15000; public static final int read_timeout = 10000; public string connhttp(jsonobject jsonuserdata, string dburl) { if(jsonuserdata != null) { try { url = new url(dburl); } catch (malformedurlexception e) { e.printstacktrace(); log.d(tag, "httpurl [url]" ); } //establishing connection try { conn = (httpurlconnection) url.openconnection(); conn.setreadtimeout(read_timeout); conn.setconnecttimeout(connection_timeout); conn.setrequestmethod("post"); conn.setdoinput(true); conn.setdooutput(true); conn.setrequestproperty("content-type", "application/json;charset=utf-8"); conn.connect(); //sending data... os = new bufferedoutputstream(conn.getoutputstream()); os.write(jsonuserdata.tostring().getbytes()); os.flush(); os.close(); } catch (ioexception e1) { e1.printstacktrace(); log.d(tag, "httpurl [connection]"); } { try { os.close(); } catch (ioexception e) { e.printstacktrace(); log.d(tag, "httpurl errrrr" ); } } //retrieving data try { int successhttpcode = conn.getresponsecode(); if (successhttpcode == httpurlconnection.http_ok) { inputstream = conn.getinputstream(); bufferedreader reader = new bufferedreader(new inputstreamreader(inputstream)); stringbuilder resultfromapistring = new stringbuilder(); string line = null; while ((line = reader.readline()) != null) { resultfromapistring.append(line); } inputstream.close(); return (resultfromapistring.tostring()); } else { return ("unsuccesful"); } } catch (ioexception e) { e.printstacktrace(); log.d(tag, "httpurl [getdata]" ); } { try { inputstream.close(); if(conn != null){ conn.disconnect(); } } catch (ioexception e) { e.printstacktrace(); log.d(tag, "httpurl errrrr" ); } } }else { return "httpurl: json null"; } return null; } }
if go wrong , catched catch block wanna recreate activity tried like
intent myintent = new intent(currentactivity.this, nextactivity.class); currentactivity.this.startactivity(myintent); this.finish(); or
this.recreate() but app getting stopped error , after activity recreated. question how handle httpurlconnection exception?. when server doesn't response want recreate activity or else wanna make app still working. in addition, whole logic working when turn off wamp server app crashes after timeout reminded , nothing else. i'm checking device internet connection it's not working when server not responding because it's server side problem. how handle this?
thanks answers, regards
wiki
Comments
Post a Comment