1

How to get values from bundle in AsyncTask doInBackground() method, which consist of URL and string?

In Activity:

Bundle bundle = new Bundle();
bundle.putString("url", url);
bundle.putString("json",asyn.toString());
inte.putExtras(bundle);
JSONObject ResponseFromServer = asyn.execute(bundle);

and in AsyncTask I am not still able to extract values.

pmichna
  • 4,800
  • 13
  • 53
  • 90

2 Answers2

0

I would go about making an interface in your AsyncTask which is then implemented by the object calling it. Once your AsyncTask has completed it can call the interface that's been implemented by the calling object. This way you can pass back your JSON response.

Edit: Here's a complete example on SO with code snippets on how to do it.

Another Edit: To pass a bundle to your AsyncTask you could implement something like the following:

public class YourAsyncTask extends AsyncTask<Object, Void, Void> {
    @Override
    protected Void doInBackground(Object... params)
    {
        Bundle dataForPost = (Bundle)params[0];
        String url = dataForPost.getString("url");
        String jsonString = dataForPost.getObject("json");
        /*
            your http post code here
        */
    }
}
Community
  • 1
  • 1
skyjacks
  • 1,154
  • 9
  • 7
0

There is really no need to use a Bundle here, you can just pass in the Strings to the varargs that doInBackground() takes.

You would just call it like this, where json is a JSONObject:

 asyn.execute(url, json.toString());

Then, you would make doInBackground() take String varargs:

class Asyn extends AsyncTask<String, Void, Void> {
    @Override
    protected Void doInBackground(String... arg0) {
        String url = arg0[0];
        String json = arg0[1];
        JSONObject obj = new JSONObject(json);
    }   
}

If you really want to use a Bundle, you could call it as you are now:

Bundle bundle = new Bundle();
bundle.putString("url", url);
bundle.putString("json",json.toString());
//inte.putExtras(bundle); //not needed
asyn.execute(bundle);

Then make doInBackground() take Bundle varargs:

class Asyn extends AsyncTask<Bundle, Void, Void> {
    @Override
    protected Void doInBackground(Bundle... arg0) {
        Bundle b = arg0[0];
        String url = b.getString("url");
        String json = b.getString("json");
        JSONObject obj = new JSONObject(json);
    }   
}

In addition, you should not be trying to capture a return value from the AsyncTask. If the AsyncTask is a subclass of the Activity, then you could just set the value in onPostExecute(), and call a method in your enclosing Activity.

For other ways to do it, see this post.

Community
  • 1
  • 1
Daniel Nugent
  • 43,104
  • 15
  • 109
  • 137