gpt4 book ai didi

android - LazyAdapter 复制图像

转载 作者:行者123 更新时间:2023-11-30 03:48:02 27 4
gpt4 key购买 nike

我有一个 Lazy 适配器,可以将标题、副标题和图片添加到 ListView。最近我在我的 ListView 中注意到我的图像被复制了。

这是我将数组添加到适配器的地方

protected void onPostExecute(String result) {                   
LazyAdapter adapter = new LazyAdapter(Services.this,menuItems);
serviceList.setAdapter(adapter);
}

这是我调用异步方法添加图像的地方(它是一个 url,这就是为什么它在异步方法中)

vi.findViewById(R.id.thumbnail).setVisibility(View.VISIBLE);
title.setText(items.get("title")); // Set Title
listData.setText(items.get("htmlcontent")); // Set content
thumb_image.setBackgroundResource(R.layout.serviceborder);//Adds border
new setLogoImage(thumb_image).execute(); // Async Method call

这里是我设置位图图像的地方

private class setLogoImage extends AsyncTask<Object, Void, Bitmap> {
private ImageView imv;

public setLogoImage(ImageView imv) {
this.imv = imv;
}

@Override
protected Bitmap doInBackground(Object... params) {
Bitmap bitmap = null;
try {
bitmap = BitmapFactory.decodeStream((InputStream)new URL(items.get("thumburl")).getContent());

} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

return bitmap;
}
@Override
protected void onPostExecute(Bitmap result) {
imv.setImageBitmap(Bitmap.createScaledBitmap(result, 50, 50, false));
}
}

items 变量是一个存储我的信息的 HashMap。我得到了提供给适配器的数据的位置,并将其分配给项目 HashMap。像这样:

items = new HashMap<String, String>();
items = data.get(position);

这似乎是随机发生的,大约有 30% 的时间在那里看到错误的图片会让人很恼火,尤其是在我尝试调试时。

任何帮助都会很棒。谢谢

这是一张图片,看看发生了什么 enter image description here

最佳答案

任何时候你遇到随机发生的事情,并且你有任何类型的线程,你应该考虑两种方法,Race Condition。基本上,您的 AsyncTasks 都在加载相同的图像。它们应该传入要加载的值。我注意到你没有对参数做任何事情。我不确定您究竟应该做什么,但问题出在您的 AsyncTask 中。

@Override
protected Bitmap doInBackground(Object... params) {
Bitmap bitmap = null;
try {
bitmap = BitmapFactory.decodeStream((InputStream)new URL(items.get("thumburl")).getContent());

} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

return bitmap;
}

您可能应该传入 URL(或它代表的字符串)。在此示例中,我传入了 URL,但您可以根据需要随意更改它。关键是,您应该将图像位置的表示形式传递到函数中,而不是在函数中尝试找出要使用的图像。

new setLogoImage(new Url(items.get("thumburl"))).execute(); // Async Method call


@Override
protected Bitmap doInBackground(Url... input) {
Bitmap bitmap = null;
try {
bitmap = BitmapFactory.decodeStream((InputStream)input[0]).getContent());

} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

return bitmap;
}

关于android - LazyAdapter 复制图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14635453/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com