本文介绍了如何确保完成所有AsyncTask?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个AsyncTask,一个嵌套在循环中的其他内容中,我想隐藏进度条,并在AsyncTask完成后也执行其他功能。我不知道怎么做?请帮帮我。



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.

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

推荐答案


这篇关于如何确保完成所有AsyncTask?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 21:56
查看更多