【问题标题】:Getting OutOfMemoryError while loading images (as bitmap) from sdcard to gridview将图像(作为位图)从 sdcard 加载到 gridview 时出现 OutOfMemoryError
【发布时间】:2014-04-16 15:03:10
【问题描述】:

我正在开发一个包含大量位图及其处理的 android 应用程序。我经常出现内存崩溃。 我搜索了很多正确和标准的加载位图的方法以及我在这里找到的最好的方法 Loading Large Bitmaps Efficiently

现在,这降低了崩溃的频率,但某些特定区域仍然存在一些崩溃,例如,在将 SDCARD 中存储的图像显示到 gridview 时,即使我正在使用异步任务加载,我每次都会出现内存不足崩溃图片。

我正在添加代码以及这个问题,请看看并建议我代码有什么问题:

LoadImage AsyncTask 的 PostExecute 方法

protected void onPostExecute(final Bundle result) {
        super.onPostExecute(result);
        ImageView view = views.get(result.getInt("pos"));
        view.setImageBitmap(BitmapFactory.decodeFile(result.getString("filePath")));
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i = new Intent(context, Monsterize.class);
                i.putExtra("flagtwo", 3);
                i.putExtra("backbgpath", filepath);
                i.putExtra("backbgname", fileName);
                i.putExtra("backbgpos", result.getInt("pos"));
                i.putExtra("calledFrom", context.getClass().getSimpleName());
                context.startActivity(i);
            }
        });
    }

并且从网格视图适配器的 getview 方法调用异步任务

public View getView(int position, View convertView, ViewGroup parent) {
    View vi = convertView;
    if (convertView == null)
        vi = inflater.inflate(R.layout.gridview_item, null);
    ImageView image = null;
    if (vi != null) {
        image = (ImageView) vi.findViewById(R.id.image);
    }
    Bundle b = new Bundle ();
    b.putString("filePath", filepath[position]);
    b.putInt("pos", position);
    new LoadImage().execute(b);
    views.put(position, image);
    return vi;
}

views 是一个 hashmap,包含 postion 作为 key,Imageview 作为 value。在异步任务中,图像会根据位置在 imageview 中设置。

【问题讨论】:

    标签: java android bitmap android-asynctask


    【解决方案1】:

    您可以使用通用图像加载器来完成这项工作,它将处理与内存相关的问题。 通过下面的链接。

    Android Universal Image loader

    【讨论】:

      【解决方案2】:
      views.put(position, image);
      

      views 是一个 hashmap,包含 postion 作为 key,Imageview 作为 value

      这就是问题所在。当网格视图管理它的视图,重用它们,以便只有可见的视图占用内存时,你将所有的图像视图存储在内存中。目前尚不清楚您为什么这样做 - views 从未在您的源代码中使用过 - 但它始终引用所有图像。

      【讨论】:

        【解决方案3】:

        首先,您解码onPostExecute 中的位图。由于此方法在 UI thread 上执行,它会使您的应用程序变慢。

        位图应在doInBackground 方法中解码,并设置为onPostExecute 中的ImageView

        其次,在适配器中,视图在用户滚动GridView 时创建和销毁。

        您可能希望使用HashMap<String, Bitmap> 来存储位图并避免将同一个位图解码两次。使用文件路径作为键,位图作为值。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2014-08-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-01-29
          • 1970-01-01
          • 2016-10-09
          相关资源
          最近更新 更多