3

I have in my app data retrieval by using http GET method. Once the task finishes, i wish to display the return vlaue in my mainActivity (I have just 1 activity in my app at the moment)

This is my asyncTask class:

class getAsync extends AsyncTask<String,Void,String> {
    String ret;
    @Override
    protected String doInBackground(String... params) {
        String url = params[0];
        myGetReq myget = new myGetReq();
        ret = myget.get(url);
        Log.d("[RETURN STATUS]",ret);
        return ret;
    }
}

and from my main activity, i use it in the following way:

getAsync get = new getAsync();
get.execute(url);
statText.setText(get.ret);

where statText is a text in my activity window. It stays blank, even tough I can see in logcat the body of the response. How to I deliver this data back, properly, to my activity?

buddy123
  • 5,679
  • 10
  • 47
  • 73

4 Answers4

3

Asynce Task have onPostExecute Method... In this method you can work on UI componetnt so i have settext in onPostExecute ... use below code..

class getAsync extends AsyncTask<String,Void,String> {

    @Override
    protected String doInBackground(String... params) {
        String url = params[0];
        myGetReq myget = new myGetReq();
        String ret = myget.get(url);
        Log.d("[RETURN STATUS]",ret);
        return ret;
    }

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

     }

}
NSetty
  • 140
  • 11
Sanket Kachhela
  • 10,861
  • 8
  • 50
  • 75
  • Do I need to add something in order for my asynctask to recognize statText? Because it doesnt. eclipse 'offers' me to add such local variable. Also, its String result, I think – buddy123 Mar 08 '13 at 06:21
  • statText must have been at globally in your activity... so you can settext at postExecute... – Sanket Kachhela Mar 08 '13 at 06:27
  • @SanketKachhela: kindly update your answer with ,onPostExecute(String result). – Mehul Joisar Mar 08 '13 at 06:31
  • Thanks. I did so, but had to define my statText global. and then, access it by `MainActivity.statText.setText(ret)`. so its also a fix. Other than that..Im pleased :) – buddy123 Mar 08 '13 at 06:39
  • @e-r-a-n: you don't need to access it using your class name like MainActivity.statText.setText(ret),you can simply do statText.setText(ret).PS: unless you have declared statText as static field – Mehul Joisar Mar 08 '13 at 06:48
2

The result is passed from doInBag() to onPostexecute() method of AsyncTask.

Now there you can use Handlers to send data back to your activity like this:

@Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);

        if (mProgressDialog != null) {
            if (mProgressDialog.isShowing()) {
                mProgressDialog.dismiss();
            }
        }
        final Message message = new Message();
        if (result != null && !result.equals("")) {
            if (result.equals("success")) {
                message.what = 1000; // to show SUCCESS
            } else {
                message.what = 1001; // to show FAILURE
            }
        } else {
                message.what = 1001; // to show FAILURE
        }
        mHandler.sendMessage(message);
    }

EDIT: The use of handlers with AsyncTask:

declare a Handler in your activity like this:

    /**
         * Handler to update the UI.
         */
        private static final Handler sHandler = new Handler() {

    @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (msg.what == 1000) {

                        } else {
                         // failure
                       } 
                     }
    };

Now in your activity, call the AsyncTask like this:

YourAsyncTask obj = new YourAsyncTask(context, sHandler);
obj.execute();

Now in your AsyncTask, create a Constructor like this:

public YourAsyncTask(final Context context, final Handler handler) {
this.context = context;
mHandler = handler;
}

Explanation:

Why you should use a handler here because, you may want to get back to your activity after finishing the background operation to do other task based on the AsyncTask result. Here you pass a reference of the Handler to your asyncTask, and eventually sends the result back to your activity.

Please note that, the Handler above is a static handler, otherwise a memory leak may occur if your activity finishes before completion of your async operation.

Shrikant Ballal
  • 7,067
  • 7
  • 41
  • 61
  • Im unfamiliar with handlers. What do I do in my activity class in order to interface with it, and get the message? – buddy123 Mar 08 '13 at 06:31
0

Define public String ret=""; to your Activity Class.

Set it By Below Way :

class getAsync extends AsyncTask<String,Void,String> {

    @Override
    protected String doInBackground(String... params) {
        String url = params[0];
        myGetReq myget = new myGetReq();
        ret = myget.get(url);
        Log.d("[RETURN STATUS]",ret);
        return ret;
    }
}

and Get it with Simple as below way :

statText.setText(ret);
Bhavesh Patadiya
  • 25,740
  • 15
  • 81
  • 107
0

Its a good practice to create a callback Interface for publishing the result to your activity.

public interface AsyncTaskCompleteListener {
    public void onTaskComplete(String result);
}

Do Network operation in separate class

public class RssFeedAsyncTask extends
        AsyncTask<String, Void, String> {
    private ProgressDialog Dialog;
    String response = "";
    Activity _context;
    private AsyncTaskCompletionListener callback;

    public RssFeedAsyncTask(Activity _context) {
        this._context = _context;
        this.callback = (AsyncTaskCompletionListener) _context;
    }

    @Override
    protected void onPreExecute() {
        Dialog = new ProgressDialog(_context);
        Dialog.setMessage("Loading...");
        Dialog.show();

    }

    @Override
    protected String doInBackground(String... urls) {
        try {
            // Your Code
        } catch (Exception e) {
        }
        return null;

    }

    @Override
    protected void onPostExecute(String result) {
        Dialog.dismiss();
        callback.onTaskComplete(result);

    }

}

And finally Your Activity Class and Implement that call back interface

public class RssReaderActivity extends Activity implements AsyncTaskCompletionListener{



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        if(Utility.determineConnectivity(this))
        new RssFeedAsyncTask(this).execute(Yoururl);
        else
            Toast.makeText(this, "No Internet Connection", Toast.LENGTH_SHORT).show();
    }



    @Override
    public void onTaskComplete(String result) {
    //write the code to upadte the UI from the Result
          statText.setText(result);
    }

}

Hope this help you to write well structured and clean separate programming. For More details go through the below blog

http://amitandroid.blogspot.in/2013/02/android-rssfeed-with-async-task-example.html

Thanks,

Amit Gupta
  • 8,914
  • 1
  • 25
  • 33