同时调用多个asynctask

时间:2016-01-10 22:13:13

标签: android

我的asynctaskimageloader2崩溃了。如何同时多次从URL加载位图?如果我删除asynctaskloader2,它可以很好地工作,并且在5.0或更高版本中它可以很好地工作,但在API17中,它不起作用。

private void getProfileInfo() {
    // istek iptali için tag
    String tag_string_req = "req_profile_info";

    pDialog.setMessage(getContext().getResources().getString(R.string.please_wait));
    showDialog();

    StringRequest strReq = new StringRequest(Method.POST, AppConfig.URL_USERS, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            hideDialog();
            try {
                JSONObject jObj = new JSONObject(response);
                boolean error = jObj.getBoolean("error");

                if (!error) {
                    //başarılı
                    JSONObject user = jObj.getJSONObject("user");

                    txtProfileName.setText(user.getString("name"));
                    email = user.getString("email");

                    String profileUri = AppConfig.URL_MAIN + user.getString("profile_img");
                    String coverUri = AppConfig.URL_MAIN + user.getString("cover_img");
                    AsyncImageLoader1 ail1 = new AsyncImageLoader1();
                    ail1.execute(profileUri);


                    AsyncImageLoader2 ail2 = new AsyncImageLoader2();
                    ail2.execute(coverUri);

                    txtFollowers.setText(user.getString("follower"));
                    txtFollowing.setText(user.getString("following"));

                    String follow = user.getString("follow");
                    followOrUnfollow = follow;
                    if (follow.equals("follow"))
                        btnFollow.setText(getContext().getResources().getString(R.string.profile_follow));
                    else
                        btnFollow.setText(getContext().getResources().getString(R.string.profile_unfollow));

                    btnLike.setText(user.getString("total_like") + " " + getContext().getResources().getString(R.string.profile_likes));

                    at_contest = user.getString("at_contest");
                    if(at_contest.equals("1")){
                        imgStatus.setImageResource(R.mipmap.ic_at_contest_true);
                    }
                    else{
                        imgStatus.setImageResource(R.mipmap.ic_at_contest_false);
                    }

                    images = user.getJSONArray("images");
                    JSONArray image_ids = user.getJSONArray("image_id");
                    JSONArray image_likes = user.getJSONArray("like");
                    imageList.clear();
                    adapter.notifyDataSetChanged();
                    int limit;
                    if (MainActivity.PROFILE_UID.equals(MainActivity.USER_UID))
                        limit = 4;
                    else if (!image_ids.getString(0).equals("null"))
                        limit = images.length();
                    else
                        limit = 0;
                    for (int i = 0; i < limit; i++) {
                        ImageList imageSingleList = new ImageList();
                        if (i < images.length() && !images.getString(i).equals("null")) {
                            String image = images.getString(i);
                            imageSingleList.setImageId(image_ids.getString(i));
                            imageSingleList.setImageUrl(AppConfig.URL_MAIN + image);
                            imageSingleList.setImageLike(image_likes.getString(i));
                        } else if (MainActivity.USER_UID.equals(MainActivity.PROFILE_UID)){
                            imageSingleList.setImageId("default");
                            imageSingleList.setImageUrl(AppConfig.URL_MAIN + "user_images/default_images/ic_default_img.png");
                            imageSingleList.setImageLike("0");
                        }
                        imageList.add(imageSingleList);
                    }

                    adapter.notifyDataSetChanged();
                } else {
                    // başarısız
                    Toast.makeText(getActivity().getApplicationContext(), R.string.error_occured, Toast.LENGTH_LONG).show();
                }
            } catch (JSONException e) {
                // JSON hatası
                e.printStackTrace();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Toast.makeText(getActivity().getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
            hideDialog();
        }
    }) {
        @Override
        protected Map<String, String> getParams() {
            // users url' e bilgileri gönder
            Map<String, String> params = new HashMap<String, String>();
            params.put("tag", "profileinfo");
            params.put("follower_id", MainActivity.PROFILE_UID);
            params.put("followed_id", MainActivity.USER_UID);

            return params;
        }
    };

    // istek kuyruğuna isteği ekle
    AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}


private class AsyncImageLoader1 extends AsyncTask<String, Void, Bitmap> {
    Bitmap bitmap2;

    protected void onPreExecute() {
        pDialog.setMessage(getContext().getResources().getString(R.string.please_wait));
        showDialog();
    }

    @Override
    protected Bitmap doInBackground(String... params) {
        hideDialog();
        URL url = null;
        HttpURLConnection connection = null;
        try {
            url = new URL(params[0]);
            connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.connect();
            InputStream input = connection.getInputStream();
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            bitmap2 = BitmapFactory.decodeStream(input);

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            connection.disconnect();
        }

        return bitmap2;
    }

    @Override
    protected void onPostExecute(Bitmap bm) {
        imgProfile.setImageBitmap(bm);
        if (MainActivity.PROFILE_UID.equals(MainActivity.USER_UID))
            FragmentDrawer.imgProfileNavDrawer.setImageBitmap(bm); // Sol drawer' da çıkan yuvarlak resmi güncellemek için
    }
}

private class AsyncImageLoader2 extends AsyncTask<String, Void, Bitmap> {
    Bitmap bitmap1;

    protected void onPreExecute() {
        pDialog.setMessage(getContext().getResources().getString(R.string.please_wait));
        showDialog();
    }

    @Override
    protected Bitmap doInBackground(String... params) {
        hideDialog();
        URL url = null;
        HttpURLConnection connection = null;

        try {
            url = new URL(params[0]);
            connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.connect();
            InputStream input = connection.getInputStream();
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            bitmap1 = BitmapFactory.decodeStream(input);

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            connection.disconnect();
        }

        return bitmap1;
    }

    @Override
    protected void onPostExecute(Bitmap bm) {
        imgCover.setImageBitmap(bm);
    }
}

1 个答案:

答案 0 :(得分:2)

你可以这样做:

FirstAsyncTask asyncTask = new FirstAsyncTask(); // First
        if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.HONEYCOMB) // Above Api Level 13
        {
            asyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
        }
        else // Below Api Level 13
        {
            asyncTask.execute();
        }
SecondAsyncTask asyncTask2 = new SecondAsyncTask(); // Second
        if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.HONEYCOMB)// Above Api Level 13
        {
            asyncTask2.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
        }
        else // Below Api Level 13
        {
            asyncTask2.execute();
        }

希望这会对你有所帮助。

相关问题