asynctask将所有图像下载到listview中的相同项目

时间:2015-01-15 09:21:31

标签: java android image listview android-listview

我正在使用asynctask将图像下载到listview并使用自定义cursoradapter。图像将下载到列表中的第一项,当我向下滚动到第二项时依此类推。它不是同步的,它不是正确的图片。我究竟做错了什么? 我无法上传图片,所以这是我的代码:

类DownloadItemdPoster扩展了AsyncTask {

    @Override
    protected Bitmap doInBackground(String... params) {
        // get the address from the params:
        String address = params[0];

        HttpURLConnection connection = null;
        InputStream stream = null;
        ByteArrayOutputStream outputStream = null;

        // the bitmap will go here:
        Bitmap b = null;

        try {
            // build the URL:
            URL url = new URL(address);
            // open a connection:
            connection = (HttpURLConnection) url.openConnection();

            // check the connection response code:
            if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
                // not good..
                return null;
            }

            // the input stream:
            stream = connection.getInputStream();

            // get the length:
            int length = connection.getContentLength();
            // tell the progress dialog the length:
            // this CAN (!!) be modified outside the UI thread !!!
            // progressDialog.setMax(length);

            // a stream to hold the read bytes.
            // (like the StringBuilder we used before)
            outputStream = new ByteArrayOutputStream();

            // a byte buffer for reading the stream in 1024 bytes chunks:
            byte[] buffer = new byte[1024];

            int totalBytesRead = 0;
            int bytesRead = 0;

            // read the bytes from the stream
            while ((bytesRead = stream.read(buffer, 0, buffer.length)) != -1) {
                totalBytesRead += bytesRead;
                outputStream.write(buffer, 0, bytesRead);

                // notify the UI thread on the progress so far:
                // publishProgress(totalBytesRead);
                Log.d("TAG", "progress: " + totalBytesRead + " / " + length);
            }

            // flush the output stream - write all the pending bytes in its
            // internal buffer.
            outputStream.flush();

            // get a byte array out of the outputStream
            // theses are the bitmap bytes
            byte[] imageBytes = outputStream.toByteArray();

            // use the BitmapFactory to convert it to a bitmap
            b = BitmapFactory.decodeByteArray(imageBytes, 0, length);

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                // close connection:
                connection.disconnect();
            }
            if (outputStream != null) {
                try {
                    // close output stream:
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return b;
    }

    @Override
    protected void onPostExecute(Bitmap result) {

        ImageView itemPoster = (ImageView) findViewById(R.id.imageViewItemPoster);

        if (result == null) {
            // no image loaded - display the default image
            itemPoster.setBackgroundResource(R.drawable.defaultitembackground);
            Toast.makeText(MainActivity.this, "Error Loading Image",
                    Toast.LENGTH_LONG).show();
        } else {
            // set the showactivitybackground to the poster:
            itemPoster.setImageBitmap(result);

        }
    };
}

公共类MovieAdapter扩展了CursorAdapter {

    public MovieAdapter(Context context, Cursor c) {
        super(context, c);
    }

    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        return getLayoutInflater().inflate(R.layout.movies_item_layout,
                parent, false);
    }

    @Override
    public void bindView(View view, Context context, Cursor cursor) {


        String movieName = cursor.getString(cursor
                .getColumnIndex(DbConstants.MOVIE_NAME));
        String movieGenre = cursor.getString(cursor
                .getColumnIndex(DbConstants.MOVIE_GENRE));
        String itemPoster = cursor.getString(cursor
                .getColumnIndexOrThrow(DbConstants.MOVIE_POSTER));
        String movieRuntime = cursor.getString(cursor
                .getColumnIndex(DbConstants.MOVIE_RUNTIME));
        String movieRating = cursor.getString(cursor
                .getColumnIndex(DbConstants.MOVIE_RATING));
        String movieReleasedYear = cursor.getString(cursor
                .getColumnIndex(DbConstants.MOVIE_YEAR_RELEASD));

        TextView name = (TextView) view
                .findViewById(R.id.textViewMovieName);
        TextView genre = (TextView) view
                .findViewById(R.id.textViewMovieGenre);
        TextView runtime = (TextView) view
                .findViewById(R.id.textViewMovieRuntime);
        TextView rating = (TextView) view
                .findViewById(R.id.textViewMovieRating);
        TextView year = (TextView) view
                .findViewById(R.id.textViewMovieYear);
        ImageView setItemPoster = (ImageView) view
                .findViewById(R.id.imageViewItemPoster);

        setItemPoster.setTag(1);


        name.setText(movieName);
        genre.setText("*" + movieGenre);
        runtime.setText("*" + movieRuntime);
        rating.setText("*" + "R:" + " " + movieRating);
        year.setText("*" + movieReleasedYear);

        if (setItemPoster != null) {
            new DownloadItemdPoster().execute(itemPoster);
            adapter.notifyDataSetChanged();

        }

2 个答案:

答案 0 :(得分:0)

您可以使用Glide library 从服务器加载图片。
示例:
    Glide.with(mContext).load(url).into(myImageView);

答案 1 :(得分:-1)

您必须使用图像加载器lib(picasso,volley,universal loader lib),而不是使用aysntask从服务器加载图像。

UniversalLoaderLib

实施例: -

在适配器或活动中启动以下代码。

        DisplayImageOptions options = new DisplayImageOptions.Builder().showImageOnLoading(R.drawable.loading_icon).showImageForEmptyUri(R.drawable.ic_error_transparent).showImageOnFail(R.drawable.ic_error_transparent)
                .cacheOnDisc(true).bitmapConfig(Bitmap.Config.RGB_565)/*.considerExifParams(true)*/.build();
        ImageLoader.getInstance().init(ImageLoaderConfiguration.createDefault(activity.getBaseContext()));

使用以下代码从您要从服务器加载图像。

        ImageLoader.getInstance().displayImage(urladdress, imageview, options);