Nested Asynctask And Onpostexecute
I am using a AsyncTask (1) in another AsyncTask (2). AsyncTask 1 fetches online user data, counts the number of entries in the response and for each entry, in onPostExecute display
Solution 1:
It is not quite clear why you are calling setText
of the single TextView
with the name of multiple names. As you have mentioned, although you had setText
of all the names, you only see a single name. May be you need to use a ListView
or something like that.
Now regarding your question: probably you don't need two AsyncTask
s. You can do everything in a single AsyncTask
. The code will be something like below:
//Create a Holder class as a data holder. //For simplicity, public attributes are usedclassHolder{
publicString name;
publicString email;
publicString id;
publicBitmapDrawable imageDrawable;
}
//instantiate the AsyncTasknewAsyncRequest().execute(bundle);
privateclassAsyncRequestextendsAsyncTask<Bundle, Holder, Integer> {
protectedIntegerdoInBackground(Bundle... bundle) {
int amount = 0;
try {
data = request(null, bundle[0]); //request the dataJSONArray data = null;
JSONObject response2 = Util.parseJson(response);
data = response2.optJSONArray("data");
amount = data.length();
//display the datafor(int i=0; i<amount; i++){
Holder holder = newHolder();
holder.email = "";
holder.id = "";
JSONObject json_obj = data.getJSONObject(i);
Log.d("JSONObject ", ""+json_obj);
holder.name = json_obj.getString("name");
if (json_obj.has("email")){
holder.email = json_obj.getString("email");
}
if (json_obj.has("id")){
holder.id = json_obj.getString("id");
}
String picture = "http://www.domain.com/"+id+"/picture";
//Fetch the image and create a Drawable from it - Synchronously
holder.imageDrawable = getImageDrawable(picture, name);
publishProgress(holder);
}
} catch (Exception e) {
e.printStackTrace();
}
return amount;
}// end methodprotectedvoidonProgressUpdate(Holder... holder) {
//Update the user name and imageTextView s2 = (TextView) findViewById(R.id.name_placeholder);
s2.setText(holder[0].name);
ImageView imgView = (ImageView) findViewById(R.id.imageViewId);
imgView.setImageDrawable(holder[0].imageDrawable);
}
protectedvoidonPostExecute(Integer amount) {
TextView s1 = (TextView) findViewById(R.id.some_id);
s1.setText(amount.toString()); //displays number of items
}// end method
Post a Comment for "Nested Asynctask And Onpostexecute"