列表视图显示使用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();
    }
}

由于您没有取消未完成的"视图外"下载,这些下载可能会干扰您的gui。

示例

  • listview第1行显示了项目#1,其中有一个异步任务要下载图像"a",但尚未完成
  • 向下滚动,第1行现在不可见
  • listview line8变为可见回收项目#1下载图像"x"的新异步任务
  • 下载图像"a"的异步任务完成显示错误的图像。第8行显示的是图像"a"而不是"x"

要解决这个问题,你必须取消挂起的不必要的未完成异步任务-

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

以下是适配器+支架+异步任务组合的工作示例

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

  • 大多数现代android版本一次只执行一个异步任务。如果您是通过网络获取图像,则无法同时下载多文件图像。看见running-parallel-asynctask@stackoverflow详细信息
  • 可能会出现配置更改的提示(如方向)。请参阅下面的@Selvin-s评论。我已经发布了这个问题"what-happens-with-view-references-in-unfinished-asynctask-after-orientation-chan@stackoverflow"了解更多信息

最新更新