user1699548
user1699548

Reputation:

how to stop execution of UI thread until async task is complete to return value got in AsyncTask in android

I have a class in which I have written a AsyncTask to get Json from net.

public class MyAsyncGetJsonFromUrl extends AsyncTask<Void, Void, JSONObject> {
    Context context_;
    String url_;
    List<NameValuePair> params_;

    public MyAsyncGetJsonFromUrl(Context context_, List<NameValuePair> params_, String url_) {
        this.context_ = context;
        this.params_ = params_;
        this.url_ = url_;
    }

    @Override
    protected JSONObject doInBackground(Void... params) {
        JSONObject jObj_ = null;
        try {
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url_);
            httpPost.setEntity(new UrlEncodedFormEntity(params_));

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            InputStream is_ = httpEntity.getContent();

            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is_.close();
            String json_ = sb.toString();
            Log.e("JSON", json);

            jObj_ = new JSONObject(json_);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return jObj_;
    }

    protected void onPostExecute(JSONObject jObj_) {
        jObj = jObj_;
    }
}

Also in this class there is a method which returns this Json Object to Activity who is calling the method.

public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {
    new MyAsyncGetJsonFromUrl(context, params, url).execute();
    return jObj;
}

Now the problem is after starting AsyncTask new MyAsyncGetJsonFromUrl(context, params, url).execute(); immediately the line return jObj; is called and null is returned. So I want to stop the execution until Async task is complete. And please don't mention this question as duplicate, because no other question is exactly same as this scenario

Upvotes: 2

Views: 4427

Answers (1)

Anup Cowkur
Anup Cowkur

Reputation: 20563

Async tasks are asynchronous. This means that they are executed in the background independent of the programs current thread (they run in a background thread). So you should not try to stop execution of your program until async task is complete.

So you have 2 options:

  • Run your code on the UI thread itself instead of in an async task

  • Assign your value from the async tasks onPostExecute() method

If you decide to go with an async task and go with option B, then you can have some static variable or something like that to which the value of the JSON object can be assigned at the end of the async task and can be accessed later. You can also do whatever post processing you need to do with the JSON object in the onPostExecute() method itself (for ex: parse the object and display it to the user) since this method is running on the UI thread after the async task completes its operations in the background thread.

If you need a return value from your async task, you can do something like:

jObj = new MyAsyncGetJsonFromUrl(context, params, url).execute().get(); 

In this case, the program will wait for the computation to complete except if there is an exception such as the thread being interrupted or cancelled (due to memory constraints etc). But this approach is generally not advised. The point of an async task is to allow asynchronous operations and your program execution should not be stopped because of it.

The return values will be passed from doInBackground() as a parameter to the OnPostExecute() method. You don't have to put a return value in onPostExecute since it's executing on the UI thread itself. Just use the result and do what you need to with it.

Upvotes: 6

Related Questions