滚动图像列表时出现OutOfMemory异常

时间:2010-01-15 09:00:46

标签: android listview out-of-memory

我有一个包含图像图标的70个文本项目列表(存储在drawables文件夹中)。 如果我第一次启动应用程序并慢慢滚动列表 - 则不会发生异常。

第一次启动应用程序时,我使用'fling'动作滚动列表时会发生以下异常:

java.lang.OutOfMemoryError: bitmap size exceeds VM budget
 at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)
 at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:439)
 at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:322)
 at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:688)
 at android.content.res.Resources.loadDrawable(Resources.java:1710)
 at android.content.res.Resources.getDrawable(Resources.java:585)

之后,如果我使用DDMS终止应用程序,再次启动它并使用'fling'动作滚动它,不会发生异常。因此,只有在第一次安装和启动应用程序时才会出现异常。

这是我用于列表的适配器:

public class AuthorAdapter extends ArrayAdapter<Author> {

private ArrayList<Author> items;
private Context context;
private LayoutInflater inflater;

public AuthorAdapter(Context context, int textViewResourceId, ArrayList<Author> items) {
    super(context, textViewResourceId, items);
    this.items = items;
    this.context = context;
    inflater = LayoutInflater.from(this.context);
}

static class ViewHolder {
    ImageView authorFace;
    TextView authorName;
    TextView authorWho;
}

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

    ViewHolder holder;

    if (convertView == null) {
        convertView = inflater.inflate(R.layout.autor_data, null);

        holder = new ViewHolder();
        holder.authorFace = (ImageView) convertView.findViewById(R.id.authorFaceImageView);
        holder.authorName = (TextView) convertView.findViewById(R.id.authorNameTextView);
        holder.authorWho = (TextView) convertView.findViewById(R.id.authorWhoTextView);
        convertView.setTag(holder);
    } else {
        holder = (ViewHolder) convertView.getTag();
    }

    Author author = items.get(position);
    if (author != null) {
        if (holder.authorFace != null) {
            String faceFileName = author.getFace();
            String facePlaceName = context.getPackageName() + ":drawable/" + faceFileName.subSequence(0, faceFileName.lastIndexOf("."));
            int faceFileId = context.getResources().getIdentifier(facePlaceName, null, null);
            holder.authorFace.setImageResource(faceFileId);
        }
        if (holder.authorName != null) {
            holder.authorName.setText(author.getName());
        }
        if (holder.authorWho != null) {
            holder.authorWho.setText(author.getWho());
        }
    }
    return convertView;
}

}

有没有办法避免异常? 我应该抓住异常并以某种方式逃避记忆吗?

有任何建议如何实现这一目标?

感谢。

1 个答案:

答案 0 :(得分:3)

你无法抓住java.lang.OutOfMemoryError。他们非常致命。

现在,您说问题仅在您第一次运行应用程序时发生。这让我认为视图代码的问题不是。如果用户使用资源繁重的视图,它可以使用大量内存,但正如您所说,通常您的应用程序正常工作。

那么 - 你第一次运行你的应用程序时做了什么初始化?是否有可能首次运行一次任务之一是泄漏内存意味着没有足够的空间来使用您的视图?