android - Java Method returns null although its not null -
i have class named webservice cointatins variable content , method called geturl gets url argument , fetches data , returns string. following :
class webservice { string content; string geturl(string url, final context mcontext) { asynchttpclient client = new asynchttpclient(); client.get(url, new texthttpresponsehandler() { @override public void onfailure(int statuscode, header[] headers, string responsestring, throwable throwable) { toast.maketext(mcontext, "sorry, went wrong while connecting net :(", toast.length_short).show(); } @override public void onsuccess(int statuscode, header[] headers, string responsestring) { content = responsestring; log.i("response string", responsestring); log.i("content string", content); } }); log.i("before return",""+ content); return content; } }
the problem method returns null. in onsuccess , check "content" , value responsestring , in log before return turns null. tell me why happens? thanks.
an asynchronous task
will, name suggest it, asynchronous
. means done when it's done. else proceed usual , don't care task - unless want it.
you can achieve various libraries on web or callback.
e.g.
class webservice { public void geturl(string url, final context mcontext, webservicecallback cb) { asynchttpclient client = new asynchttpclient(); client.get(url, new texthttpresponsehandler() { @override public void onfailure(int statuscode, header[] headers, string responsestring, throwable throwable) { cb.onfailure(); } @override public void onsuccess(int statuscode, header[] headers, string responsestring) { cb.onsuccess(responsestring); } }); } public interface webservicecallback{ void onfailure(); void onsuccess(string url); } }
and call that
webservice service = new webservice(); service.geturl("www.test.com", yourcontext, new webservicecallback(){ @override public void onfailure(){} @override public void onsuccess(string url){ youralreadydeclaredstring = url; // smth } });
you skip custom callback , pass texthttpresponsehandler
, design.
Comments
Post a Comment