Java AYSNTASK将所有图像下载到listview中的同一项目

Java AYSNTASK将所有图像下载到listview中的同一项目,java,android,image,listview,android-listview,Java,Android,Image,Listview,Android Listview,我正在使用asynctask使用自定义游标适配器将图像下载到listview。图像下载到列表中的第一项,当我向下滚动到第二项时,依此类推。这不是同步,也不是正确的图片。我做错了什么? 我无法上传图片,因此以下是我的代码: 类DownloadItemdPoster扩展异步任务{ @Override protected Bitmap doInBackground(String... params) { // get the address from the param

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

类DownloadItemdPoster扩展异步任务{

    @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扩展游标适配器{

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

        }

您必须使用图像加载器库(毕加索、凌空、通用加载器库),而不是使用aysntask从服务器加载图像

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

例如:-

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

        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);
您可以使用从服务器加载映像。
示例:

Glide.with(mContext).load(url).into(myImageView);

使用毕加索或UniversalImageLoader。答案中已经给出了链接。