user782104
user782104

Reputation: 13555

Using asyncTask to load image in listview in android

I am currently working on using asynctask to load image. I have reference to a example class . However, the Bitmap result there is null. Why is that and how can I fix the problem ? thanks. The code are shown below.

package com.example.json;

import java.io.File;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

class ImgAdapter extends AsyncTask<Object, Void, Bitmap> {

    private ImageView imv;
    private String path;

    public ImgAdapter(ImageView imv) {
        this.imv = imv;
        this.path = imv.getTag().toString();
    }

    @Override
    protected Bitmap doInBackground(Object... params) {
        Bitmap bitmap = null;
        File file = new File(Environment.getExternalStorageDirectory()
                .getAbsolutePath() + path);

        if (file.exists()) {
            bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
        }

        return bitmap;
    }

    @Override
    protected void onPostExecute(Bitmap result) {
        if (!imv.getTag().toString().equals(path)) {
            /*
             * The path is not same. This means that this image view is handled
             * by some other async task. We don't do anything and return.
             */
            return;
        }

        if (result != null && imv != null) {
            Log.i("test","success");
            imv.setVisibility(View.VISIBLE);
            imv.setImageBitmap(result);
        } else {
            Log.i("test","result=" + String.valueOf(result == null)); //result is null here
            Log.i("test","imv=" + String.valueOf(imv == null));
            Log.i("test","fail");
            imv.setVisibility(View.GONE);
        }
    }
}

How to call in ListView adapter:

public View getView(int arg0, View arg1, ViewGroup arg2) {
ImageView thumbnail = (ImageView) arg1.findViewById(R.id.imageView1);
ShopEntry entry = getItem(arg0);
thumbnail.setTag(entry.image_url);
new ImgAdapter(thumbnail).execute();
return arg1;
}

Upvotes: 0

Views: 2382

Answers (1)

fenix
fenix

Reputation: 1746

change this:

Bitmap bitmap = null;
        File file = new File(Environment.getExternalStorageDirectory()
                .getAbsolutePath() + path);

        if (file.exists()) {
            bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
        }

to this:

 Bitmap bitmap = ((BitmapDrawable)imv.getDrawable()).getBitmap();

Upvotes: 1

Related Questions