使用asynctask下载图像后显示图像混乱的列表视图

时间:2015-10-27 11:16:59

标签: android image android-asynctask

我已经使用异步任务下载数据,然后在列表视图中显示这些图像我使用缓存来存储图像,因为它们正在重复但不按顺序存储。但是图像混乱,有时他们不会下载。我试着搜索这个,但无法找到。

这是我的梦想公司问题之一,因此我不清楚。 请帮帮我。

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    private static final String BASE_URL = "https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=android&start=";
    private static final String IMAGE_JSON_KEY = "unescapedUrl";
    private static final String RESULTS_JSON_KEY = "results";
    private static final String RESPONSE_DATA_JSON_KEY = "responseData";

    private int mCurrentPage;
    private ListView mListView;
    private Context mContext;
    ArrayList<String> mImageUrls;
    private LruCache<String, Bitmap> mCache;
    private CustomListAdapter mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Get memory class of this device, exceeding this amount will throw an
        // OutOfMemory exception.
        final int memClass = ((ActivityManager) getSystemService(Context.ACTIVITY_SERVICE)).getMemoryClass();

        // Use 1/8th of the available memory for this memory cache.
        final int cacheSize = 1024 * 1024 * memClass / 8;

        // Initialize variables
        mContext = this;
        mCache = new LruCache<String, Bitmap>(cacheSize) {

            @Override
            protected int sizeOf(String key, Bitmap value) {
                // The cache size will be measured in bytes rather than number of items.
                return value.getByteCount();
            }
        };
        mListView = (ListView) findViewById(R.id.list_view);
        mAdapter = new CustomListAdapter();
        mImageUrls = new ArrayList<>();

        // If the urls are wrong then
        if (mImageUrls.isEmpty() || checkDiff()) {
            fetchNewImageUrls();
        }

        // Set the adapter to the list view
        mListView.setAdapter(mAdapter);
    }

    class BitmapWorkerTask extends AsyncTask<String, Void, Bitmap> {

        private final WeakReference<ImageView> imageViewReference;
        private String mUrl;

        public BitmapWorkerTask(ImageView imageView) {
            // Use a WeakReference to ensure the ImageView can be garbage collected
            imageViewReference = new WeakReference<ImageView>(imageView);
        }

        @Override
        protected Bitmap doInBackground(String... params) {
            String imageUrl = params[0];
            mUrl = imageUrl;
            Bitmap bitmap = getBitmapFromMemCache(imageUrl);

            if (bitmap == null) {
                try {
                    URL url = new URL(imageUrl);
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setDoInput(true);
                    connection.connect();

                    // Closing the stream after getting the sample size
                    InputStream inputStream = connection.getInputStream();
                    byte[] imageByteArray = convertToByteArray(inputStream);
                    bitmap = decodeSampledBitmap(imageByteArray, 200, 200);
                    inputStream.close();

                    if (bitmap != null) {
                        Log.d(TAG, "Image downloaded: " + imageUrl);
                        addBitmapToMemoryCache(imageUrl, bitmap);
                    } else {
                        Log.d(TAG, "Null Bitmap downloaded for: " + imageUrl);
                    }
                    connection.disconnect();
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else {
                Log.d(TAG, "Already present in the Cache");
            }
            return bitmap;
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            if (imageViewReference != null && bitmap != null) {
                final ImageView imageView = (ImageView) imageViewReference.get();

                if (imageView != null && imageView.getTag().equals(mUrl)) {
                    imageView.setImageBitmap(bitmap);
                }
            }
        }
    }

    public class CustomListAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return mImageUrls.size();
        }

        @Override
        public Object getItem(int position) {
            return mImageUrls.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            Log.d(TAG, "Get View is called for position: " + position);

            View view = convertView;
            Holder holder = null;

            // Holder represents the elements of the view to use
            // Here are initialized
            if (view == null) {
                view = LayoutInflater.from(mContext).inflate(R.layout.row_item, parent, false);
                holder = new Holder();
                holder.mRowImage = (ImageView) view.findViewById(R.id.image_view);
                holder.mRowText = (TextView) view.findViewById(R.id.row_text);
                view.setTag(holder);
            } else {
                holder = (Holder) view.getTag();
            }

            // Set default image background
            holder.mRowImage.setImageResource(R.drawable.ic_launcher);

            // here do operations in holder variable example
            holder.mRowText.setText("Image Number: " + position);

            // Set the tag for the imageview
            holder.mRowImage.setTag(mImageUrls.get(position));

            new BitmapWorkerTask(holder.mRowImage).execute(mImageUrls.get(position));
            return view;
        }
    }

    public static class Holder {
        TextView mRowText;
        ImageView mRowImage;
    }

    public void addBitmapToMemoryCache(String key, Bitmap bitmap) {
        if (getBitmapFromMemCache(key) == null) {
            mCache.put(key, bitmap);
        }
    }

    public Bitmap getBitmapFromMemCache(String key) {
        return (Bitmap) mCache.get(key);
    }

    public Bitmap decodeSampledBitmap(byte[] imageByteArray, int reqWidth, int reqHeight) {
        Bitmap bm = null;

        // First decode with inJustDecodeBounds=true to check dimensions
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeByteArray(imageByteArray, 0, imageByteArray.length, options);

        // Calculate inSampleSize
        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
        options.inJustDecodeBounds = false;
        bm = BitmapFactory.decodeByteArray(imageByteArray, 0, imageByteArray.length, options);
        return bm;
    }

    public int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        // Raw height and width of image
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {
            if (width > height) {
                inSampleSize = Math.round((float) height / (float) reqHeight);
            } else {
                inSampleSize = Math.round((float) width / (float) reqWidth);
            }
        }

        Log.d(TAG, "Sample size is: " + inSampleSize);
        return inSampleSize;
    }

    private void fetchNewImageUrls() {
        new AsyncTask<String, Void, Boolean>() {

            @Override
            protected Boolean doInBackground(String... params) {
                try {
                    StringBuilder response = new StringBuilder();

                    URL url = new URL(params[0]);
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    connection.connect();
                    BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                    String inputLine;
                    while ((inputLine = in.readLine()) != null)
                        response.append(inputLine);
                    in.close();
                    connection.disconnect();

                    String resp = response.toString();
                    Log.d(TAG, "Response is: " + response);

                    // Parsing the response
                    JSONObject jsonObject = new JSONObject(resp);
                    JSONObject jsonObject1 = jsonObject.getJSONObject(RESPONSE_DATA_JSON_KEY);
                    JSONArray jsonArray = jsonObject1.getJSONArray(RESULTS_JSON_KEY);

                    for (int i = 0; i < 4; i++) {
                        JSONObject dataObject = jsonArray.getJSONObject(i);
                        mImageUrls.add(dataObject.getString(IMAGE_JSON_KEY));
                    }
                    mCurrentPage++;
                    Log.d(TAG, "Number of image urls are: " + mImageUrls.size());
                    return true;
                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return false;
            }

            @Override
            protected void onPostExecute(Boolean value) {
                super.onPostExecute(value);

                if (checkDiff() && value) {
                    Log.d(TAG, "Again fetching the Images");
                    fetchNewImageUrls();
                }

                if (!value) {
                    Log.d(TAG, "Error while getting the response");
                }
                mAdapter.notifyDataSetChanged();
            }
        }.execute(BASE_URL + mCurrentPage);
    }

    private boolean checkDiff() {
        int diff = mImageUrls.size() - mCurrentPage * 4;
        Log.d(TAG, "Diff is: " + diff);
        return diff < 8;
    }

    public static byte[] convertToByteArray(InputStream input) {
        byte[] buffer = new byte[8192];
        int bytesRead;
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        try {
            while ((bytesRead = input.read(buffer)) != -1) {
                output.write(buffer, 0, bytesRead);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return output.toByteArray();
    }
}

1 个答案:

答案 0 :(得分:1)

由于您未取消未完成的“视野外”下载,因此可能会干扰您的gui。

实施例

  • listview第1行显示第1项,其中包含异步任务以下载图像“a”尚未完成
  • 向下滚动,第1行现在是不可见的;
  • listview line8成为可见的回收项目#1新的异步任务,以下载图像“x”
  • 下载图像“a”的异步任务完成显示错误的图像。 Line8显示图像“a”而不是“x”

要解决此问题,您必须取消待处理的不必要的未完成异步任务-s

public static class Holder {
    ImageView mRowImage;
    String mImageUrl;

    // neccessary to cancel unfinished download
    BitmapWorkerTask mDownloader;
}

static class BitmapWorkerTask extends AsyncTask<Holder, Void, Bitmap> {
    Holder mHolder;
    protected Bitmap doInBackground(Holder... holders) {
        mHolder = holders[0];
        ...
    }
    protected void onPostExecute(...) {
        mHolder.mDownloader = null; 
        if (!isCancelled()) {
            this.mHolder.mRowImage.setImageBitmap(image);
        }
        this.mHolder = null;
    }
}

public class CustomListAdapter extends BaseAdapter {
    @Override
    public View getView(int position, ...) {
        ...
        if (view == null) {
            holder = ...
            ...
        } else {
            holder = (Holder) view.getTag();
        }
        ...
        // cancel unfinished mDownloader
        if (holder.mDownloader != null) {
            holder.mDownloader.cancel(false);
            holder.mDownloader = null;
        }
        holder.mImageUrl = mImageUrls.get(position);
        holder.mDownloader = new BitmapWorkerTask()
        holder.mDownloader.execute(holder); 
    }
}

Here是Adapter + Holder + AsyncTask

组合的一个工作示例

[更新] 此解决方案的潜在问题。