0

I am trying to write a Http API in android. I am using a AsyncTask to run the calls to my web service.I am not interested in updating the UI, instead all I want is the data to use in my application logic. This is what I have so far:

public class DataManager{
    public static String result;

    public DataManager ()
    {

    }


    public String get ()
    {
        User user = new User ();
        user.execute("http://someuri/service/users/id/21001");
        return user.getResult();
    }
}


public class User extends AsyncTask <String,Void,String>{

    private String result;
    @Override
    protected String doInBackground(String... arg0) 
    {
        HttpClient client = new DefaultHttpClient();
        HttpGet get = new HttpGet (arg0[0]);

        try
        {
            HttpResponse response = client.execute (get);
            if (response.getStatusLine().getStatusCode () == 200)
            {
                HttpEntity entity = response.getEntity();
                return EntityUtils.toString(entity);
            }

        } 
        catch (ClientProtocolException e) 
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }


    @Override
    protected void onPostExecute(String result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);
        this.result = result;
    }

    public String getResult ()
    {
        return result;
    }

}

I want a typical call to be: DataManager manager = new DataManager (); String value = manager.get ();

But when I run this I get back null. What is causing this and how can I refactor this code to get the desired behavior.

Dipak Keshariya
  • 22,193
  • 18
  • 76
  • 128
Mario Dennis
  • 2,986
  • 13
  • 35
  • 50

1 Answers1

3

The whole idea of a thread is that it runs concurrently. Basically, here's what you're doing:

User user = new User (); // Create User object
user.execute("http://someuri/service/users/id/21001"); // Start thread
return user.getResult(); // Return thread result

However, there is no time for the thread to run between "start" and "return result".

I would suggest using some kind of callback; first, make get() return void, and remove the return statement. Then, you pass in some object which implements YourCallback, and then call onCallback(result) from within onPostExecute().

Your calling code would then look like this:

DataManager x = new DataManager();
x.get(new YourCallback() {
    public void onCallback(String result) {
        // ...
    }
});

There is a much fuller example in this fantastic answer.

Community
  • 1
  • 1
Cat
  • 66,919
  • 24
  • 133
  • 141