Click here to Skip to main content
15,881,852 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have 2 AsyncTask, one was nested inside other in the loop, I want to invisible the progress bar and also do other functions after both AsyncTask is finished. I don't know how to do that? Please help me.

Java
public class GalleryFragment extends Fragment {
	
	ProgressBar progressBar;
	
	JSONParser jsonParser = new JSONParser();
	    
	private static String url_download_photo_id = Global.url+"/clubs/download_photo_id.php";
	private static String url_download_photo = Global.url+"/clubs/download_photo.php";
	 
	private static final String TAG_SUCCESS = "success";
	private static final String TAG_CLUBS = "clubs";
	private static final String TAG_PHOTO = "photo";
	private static final String TAG_PHOTO_ID = "photo_id";
	 
	 // News JSONArray
	JSONArray clubs = null;
	
	AsyncTask<String, String, String> a,b;
	 
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.fragment_gallery, container, false);
		
	    //Progress Bar
		progressBar = (ProgressBar) rootView.findViewById( R.id.progressBar1); 

		a = new DownloadPhotoId().execute();

		return rootView;
	}
	
    class DownloadPhotoId extends AsyncTask<String, String, String> {
		
        protected String doInBackground(String... args) {
        	
        	Log.v("DownloadPhotoId","doInBackground");
  
            // check for success tag
            try {
            	
                // Building Parameters
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("club_id", ClubActivity.club_id));
     
                JSONObject json = jsonParser.makeHttpRequest(url_download_photo_id,
                "GET", params);
     
                // check log cat for response
                Log.d("Download Image Id", json.toString());
                
                int success = json.getInt(TAG_SUCCESS);
 
                if (success == 1) {       
                	
               	 getActivity().runOnUiThread(new Runnable() {
          		    public void run() {
          		       progressBar.setVisibility(View.VISIBLE);
          		    }
          		});
                	
                	clubs = json.getJSONArray(TAG_CLUBS);
               	 
               	 	progressBar.setMax(clubs.length());

               	 	int i;
                    for (i = 0; i < clubs.length(); i++) {
                   	 JSONObject c = clubs.getJSONObject(i);
                 
                        // Storing each json item in variable
                        String photo_id = c.getString(TAG_PHOTO_ID);

            			Log.v("Photo id"+i,""+photo_id);

                        b = new DownloadPhoto(photo_id,i).execute();
       
                        progressBar.setProgress(i+1);

                    }
                }
                else 
                {
                	
                }
            
            } catch (JSONException e) {
            	problem();
                e.printStackTrace();             
            }
            catch(Exception e)
            {
            	problem();
            	Log.v("Exception",""+e);           	
            }
       
            return null;
        }
 
        protected void onPostExecute(String file_url) {
        }
    }
    
class DownloadPhoto extends AsyncTask<String, String, String> {
	
	String photo_id = null,photo = null;
	int progress;
	
	DownloadPhoto(String pId, int p)
	{
		photo_id = pId;
		progress = p;
	}
		
        protected String doInBackground(String... args) {
        	
        	Log.v("DownloadPhoto","doInBackground");
  
            // check for success tag
            try {
            	
                // Building Parameters
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("photo_id", photo_id));
     
                JSONObject json = jsonParser.makeHttpRequest(url_download_photo,"GET", params);
     
                // check log cat for response
                Log.d("Download Image Id", json.toString());
                
                int success = json.getInt(TAG_SUCCESS);
 
                if (success == 1) {       
                	
                	clubs = json.getJSONArray(TAG_CLUBS);

                   	 JSONObject c = clubs.getJSONObject(0);
                 
                        // Storing each json item in variable
                        photo = c.getString(TAG_PHOTO);
                        
                        if(photo!=null)
            			{
            				Log.v("Photo id "+photo_id,""+photo);
                			SaveImageToSDCard(photo,photo_id);
							
                			
                			progressBar.setProgress(progress+1);
            			}
                }
                else 
                {
                	
                }
            
            } catch (JSONException e) {
            	problem();
                e.printStackTrace();             
            }
            catch(Exception e)
            {
            	problem();
            	Log.v("Exception",""+e);           	
            }
       
            return null;
        }
 
        protected void onPostExecute(String file_url) {
			//a.notify();
        }
    }

	void problem()
	{
		getActivity().runOnUiThread(new Runnable() {
		    public void run() {
		    	 Toast.makeText(getActivity(),
                        "Something went wrong! Try again!",Toast.LENGTH_LONG).show();
		    	progressBar.setVisibility(View.INVISIBLE);
				progressText.setVisibility(View.INVISIBLE);
			    }
			});
	}
	
	void SaveImageToSDCard(String Image, String photo_id)
	{	
		 byte[] imageBytes=Base64.decode(Image, Base64.DEFAULT);
         InputStream is = new ByteArrayInputStream(imageBytes);
         Bitmap image=BitmapFactory.decodeStream(is);
         
         String mBaseFolderPath = Environment.getExternalStorageDirectory().getAbsolutePath() + 
                                   "/Clubs/"+ClubActivity.club_id;
         
         if (!new File(mBaseFolderPath).exists()) {
        	 
        	Log.v("!new File(mBaseFolderPath).exists()","Folders not exists");
        	 
         	if(new File(mBaseFolderPath).mkdirs())
         		Log.v("new File(mBaseFolderPath).mkdir()","Folders Created");
        	else
        		Log.v("new File(mBaseFolderPath).mkdir()","Folders not Created");
         }
         else
        	 Log.v("!new File(mBaseFolderPath).exists()","Folders exists");
         
         String mFilePath = mBaseFolderPath + "/" + photo_id + ".jpg";

         File file = new File(mFilePath);
         
  		try{   
  			
         if (!file.exists()){
        		
        	 Log.v("!file.exists()","file not exists");
        	 
        	 if(file.createNewFile())
            		Log.v("createNewFile()","FileCreated");
            	else
            		Log.v("createNewFile()","FileNotCreated");
         }         
         else
        	 Log.v("!file.exists()","file exists");
         
         FileOutputStream stream = new FileOutputStream(file);
         
         image.compress(CompressFormat.JPEG, 100, stream);

         is.close();
         image.recycle();
         
         stream.flush();
         stream.close();

         Log.v("Image Saved ",""+file);       	         
		}
		catch(Exception e)
		{
			Log.v("SaveFile",""+e);
			e.printStackTrace();
		}
	}
}
Posted
Updated 2-Jul-14 2:19am
v2

1 solution

You have to push all your task into an array of tasks upon creation. At the point where you want to wait to them add call to Task.WaitAll[^] method...
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900