Pouya Heydari Pouya Heydari - 26 days ago 17
Android Question

Java Method returns null although its not null

I have a class named webservice that cointatins a variable content and a method called getURL that gets an URL as an argument and fetches data and returns it as an string. as 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, Something Went Wrong While Connecting To 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 is method returns null.
In onSuccess , i check the "content" and the value is exactly like responseString , but in the log before return it turns to null.
could you tell me why this happens?
Thanks.

Answer

An asynchronous Task will, as the name suggest it, be asynchronous. This means it will be done when it's done. Everything else will proceed as usual and don't care about that task - unless you want something back from it.

You can achieve this with various libraries on the web or do it yourself with a 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 you call it like 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;
        // do smth with it 
    }
});

You could also skip this custom callback and pass the TextHttpResponseHandler, but this is up to your design.