3

I create a AsyncTask instance that calls a web service, gets Data and converts that to string. I want to update some picture based on the string taken from AsyncTask. (String includes some image URL I want to download if they aren't already exist in my app data folder)
My problem is: UI thread and AsyncTask thread execute parallel and I want to be sure that result string (from AsyncTask) isn't null and then decide to whether I need to downlaod new images or not. If needed, download photos and change a layout somewhere in my app.
How can I make sure that AsyncTask has done its task?

Please help me by telling your suggestion or writing code.

Here's my code,
Activity:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.more_apps_layout);

    android.os.Debug.waitForDebugger();

    DisplayMetrics displaymetrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
    height = displaymetrics.heightPixels;
    width = displaymetrics.widthPixels;

    ReceiveTask r = new ReceiveTask();
    r.execute();

    if (DataFromWebService != null)
        Log.v("sina", DataFromWebService); // !! DataFromWebService is null because AsyncTask hasn't done its task
    else
        Log.v("sing", "null");
}  

AsynTask:

class ReceiveTask extends AsyncTask<Void, Void, String>{
    @Override
    protected String doInBackground(Void... params) {
        String result = null;
        JSONObject json = new JSONObject();
        try {
            json.put("command", "adv");
        } catch (JSONException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        HttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_MILLISEC);
        HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
        HttpClient client = new DefaultHttpClient(httpParams);


        // ??? here coms web service!!!
        String url = "http://sina.greenbirdstudio.com/adv.php";

        try {
            HttpPost request = new HttpPost(url);
            request.setEntity(new ByteArrayEntity(json.toString().getBytes("UTF8")));
            request.setHeader("json", json.toString());
            HttpResponse response = client.execute(request);
            HttpEntity entity = response.getEntity();

            // If the response does not enclose an entity, there is no need
            if (entity != null) {
                InputStream instream = null;
                instream = entity.getContent();

                //result = RestClient.convertStreamToString(instream);

                BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
                StringBuilder sb = new StringBuilder();

                String line = null;
                try {
                    while ((line = reader.readLine()) != null)
                        sb.append(line + "\n");
                } catch (IOException e) {
                    e.printStackTrace();
                    DataFromWebService = e.toString();
                } finally {
                    try {
                        instream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                        DataFromWebService = e.toString();
                    }
                }
                result = sb.toString();
            } else {
                Log.v("chize khar", " chize khar");
            }
        } catch (Exception t) {
            result = t.toString();
        }
        return result;
    }

    @Override
    protected void onPostExecute(String result) {
        DataFromWebService = result;
    }
Alireza Farahani
  • 2,238
  • 3
  • 30
  • 54
  • 1
    as u make your AsyncTask as AsyncTask means you get some String after your task in doInBackground completed in doPostExecute().so just send any string from doInBackground,so u know that your process is completed and check that particular string into doPostExecute method. – Rupesh Nerkar Aug 05 '13 at 08:42

2 Answers2

4

As the name suggest AsyncTask runs Asynchronous not Synchronously So put,

if (DataFromWebService != null)
        Log.v("sina", DataFromWebService); // !! DataFromWebService is null because AsyncTask hasn't done its task
    else
        Log.v("sing", "null");
}  

in onPostExecute() of AsyncTask.

Or just use get() method of AsyncTask which will wait till Completion of AsyncTask But it will block the UI Thread.

Note: But I not suggest to use .get() method. Simply use DataFromWebService in onPostExecute() its a good practice.

user370305
  • 108,599
  • 23
  • 164
  • 151
  • Thank for help. Can you advise me how and WHERE I download the photos? Inside `doInBackGround` running another thread or something else. – Alireza Farahani Aug 05 '13 at 08:50
  • Download photos in `doInBackground()` of AsyncTask and Update that Photos in `onPostExecute()` of ASyncTask.. – user370305 Aug 05 '13 at 08:57
0

Do everything you want to do inside onPostExecute() method.

Uniruddh
  • 4,427
  • 3
  • 52
  • 86
Tsunaze
  • 3,204
  • 7
  • 44
  • 81