0

我目前正在使用 asynctask 加载图像。我参考了一个示例类。但是,Bitmap 结果那里是空的。为什么会这样,我该如何解决这个问题?谢谢。代码如下所示。

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

如何调用 ListView 适配器:

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

1 回答 1

1

改变这个:

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

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

对此:

 Bitmap bitmap = ((BitmapDrawable)imv.getDrawable()).getBitmap();
于 2013-07-30T02:24:46.967 回答