【问题标题】:Display Image in Listview with AsyncTask使用 AsyncTask 在 Listview 中显示图像
【发布时间】:2016-05-27 09:13:18
【问题描述】:

我正在尝试使用 AsyncTask 在列表视图中显示图像,但出现错误。说...

尝试调用虚拟方法'java.lang.String 空对象引用上的 java.lang.Object.toString()'

这是错误发生在

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

还有

    LoadImage loadImage = new LoadImage(imageView);
    Bitmap bitmap = loadImage.doInBackground();

这里是 LoadImage.java

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.os.Environment;
import android.view.View;
import android.widget.ImageView;

import java.io.File;

/**
 * Created by Yudii on 27/05/2016.
 */
class LoadImage extends AsyncTask<Object, Void, Bitmap>{

    private ImageView imv;
    private String path;

    public LoadImage(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){
            imv.setVisibility(View.VISIBLE);
            imv.setImageBitmap(result);
        }else{
            imv.setVisibility(View.GONE);
        }
    }

}

这里是 CustomList.java

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.ArrayList;

public class CustomList extends ArrayAdapter<String>{

    private final Activity context;
    private final Integer[] imageId;

    public CustomList(Activity context,
                      String[] web, Integer[] imageId) {
        super(context, R.layout.list_single, web);
        this.context = context;
        this.imageId = imageId;

    }
    @Override
    public View getView(int position, View view, ViewGroup parent) {

        LayoutInflater inflater = context.getLayoutInflater();
        View rowView= inflater.inflate(R.layout.list_single, null, true);

        ImageView imageView = (ImageView) rowView.findViewById(R.id.img);


        LoadImage loadImage = new LoadImage(imageView);
        Bitmap bitmap = loadImage.doInBackground();


        imageView.setImageResource(imageId[position]);

        return rowView;

    }
}

这里是 MainActivity.java

import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends Activity {

    ListView list;
    String[] web = {
            "Google Plus",
            "Twitter",
            "Tall",
    };

    Integer[] imageId = {
            R.drawable.gggggggggg,
            R.drawable.hhhhhhhhhh,
            R.drawable.ttttttttttt
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);



        CustomList adapter = new
                CustomList(MainActivity.this, web, imageId);


        list=(ListView)findViewById(R.id.list);
        list.setAdapter(adapter);
        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                Toast.makeText(MainActivity.this, "You Clicked at " +web[+ position], Toast.LENGTH_SHORT).show();

            }
        });

    }
}

【问题讨论】:

    标签: java android image listview android-asynctask


    【解决方案1】:

    您需要更改loadImage.execute(); 而不是Bitmap bitmap = loadImage.doInBackground();

    【讨论】:

    • @YudiMoszkowski 发布完整的 java 代码以填充列表视图
    • 否,但图片没有加载到 ListView 中
    • 在您的 AsyncTask 构造函数中,您使用this.path = imv.getTag().toString();,但您在哪里设置了标签。?
    • 我不确定在哪里
    • 所以你为什么使用它,取决于你从External Storage获取图像并尝试在imageview上显示
    【解决方案2】:

    为什么需要 AsyncTask?尝试使用库Picasso并通过一个字符串打开图像:

    File file = new File(Environment.getExternalStorageDirectory()
                .getAbsolutePath() + path);
    Picasso.with(context).load(file).into(imageView);
    

    Bitmap 对象非常重,您需要在每个 Bitmap 图像之后清理内存以防止 OutOfMemoryError。我建议你使用库。

    【讨论】:

    • 我将如何实现这个?
    • compile 'com.squareup.picasso:picasso:2.5.2' 添加到您的 build.gradle 并在 UI 线程中使用它。 :)
    • 我这样做了,但我从哪里获取图像?
    • Picasso.with(context).load(file).into(imageView); 其中 file 可以是文件、字符串 url 或可绘制资源。
    • 我使用了一个 rawable,它显示“解析失败:Lcom/squareup/picasso/Picasso;”
    【解决方案3】:

    将此添加到您的依赖项中:-

      compile 'com.squareup.picasso:picasso:2.5.2'
    

    然后加载你的图片:-

       Picasso.with(this)
                    .load(drawerImage) // ImagePath
                    .placeholder( R.mipmap.download)
                    .error( R.mipmap.add_photo)
                    .into(imageDrawerView); //ImageView 
    

    【讨论】:

    • 它说 Failed resolution of: Lcom/squareup/picasso/Picasso;
    • 我不确定,但这一定是您的 targetSdkVersion 。您现在使用的是什么版本???
    【解决方案4】:

    1、原因:

    如我所见,在您的 getView 函数中:

    ImageView imageView = (ImageView) rowView.findViewById(R.id.img);
    // You need to set tag to your image view
    // Ex: imageView.setTag("your_image_file_path") below this line
    

    你的imageView 没有标签,所以下面的代码将得到NullPointerException

    public LoadImage(ImageView imv) {
        this.imv = imv;
        this.path = imv.getTag().toString(); // Crashed here.
    }
    

    另外,我在你的getView 函数中看到了这个代码:

    imageView.setImageResource(imageId[position]);
    

    这意味着“您的ImageView 将设置与定义的imageId 数组相对应的资源”。所以你不需要AsyncTask 类,让我们删除它并改变你的getView,如下所示:

    @Override
        public View getView(int position, View view, ViewGroup parent) {
            LayoutInflater inflater = context.getLayoutInflater();
            View rowView= inflater.inflate(R.layout.list_single, parent, false);
            ImageView imageView = (ImageView) rowView.findViewById(R.id.img);
            // Remove below code
            // LoadImage loadImage = new LoadImage(imageView);
            // Bitmap bitmap = loadImage.doInBackground();
            imageView.setImageResource(imageId[position]);
            return rowView;
        }
    

    每当您使用图像文件的路径而不是可绘制资源时,都需要您的 Asynctask 类。

    2、改进:

    在使用ListViewRecyclerView 提高性能时,您可以从Google Search 了解有关ViewHolder pattern 的更多信息。以下是您当前代码的示例:

    @Override
            public View getView(int position, View view, ViewGroup parent) {
                View holder = null;
                if (view == null) {
                    holder = new ViewHolder();
                    LayoutInflater inflater = context.getLayoutInflater();
                    view = inflater.inflate(R.layout.list_single, parent, false);
                    holder.imageView = (ImageView) view.findViewById(R.id.img);
                    view.setTag(holder);
                } else {
                    holder = (ViewHolder) view.getTag();
                }
    
                holder.imageView.setImageResource(imageId[position]);
                return view;
            }
          static class ViewHolder { // should be static class
               ImageView imageView;
          }
    

    【讨论】:

    • 该代码导致应用程序非常滞后,并显示“跳过了 49 帧!应用程序可能在其主线程上做的工作过多。”
    • 但是,它有用吗?另外,我建议您使用查看器模式改进您的代码。
    • 是的,但是使用起来太慢了,我又回到了起点,viewholder 会做什么?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多