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;
}