Всем привет. Дело вот в чем.
Пишу апп, в принципе ничего сложного. Отображение товара в мобилке. При первом запуске скачиваю базу с сервера, и потом по категориям отображаю товары в ListView
.
Картинки загружаю при помощи AsyncTask
, в адаптере, если их еще нет. Естественно при первом запуске нет ни одной, так что все скачиваются.
И вот тут начинается непонятное для меня.
Открывается категория, и в течении секунды-двух подгружаются картинки для видимых элементов. При скроллинге в ImageView
других элементов сначала показываются уже загруженные, а потом те, что подгружаются следом(правильные).
Выглядит так - я скроллю, и вижу одни и те же картинки для всех элементов, которые заменяются другими, пока не загрузятся все. После чего все отображается как надо.
Вот код загрузчика.
public class ImageLoader extends AsyncTask<String, Void, Bitmap> {
ImageView image;
int productId = 0;
int catId = 0;
Core core;
String path = "";
public ImageLoader (ImageView image, int productId, int catId) {
this.image = image;
this.productId = productId;
this.catId = catId;
core = Core.getInstance();
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
ContextWrapper cw = new ContextWrapper(core.context.getApplicationContext());
String name = "";
if(productId == 0) {
name = "cat_image_" + catId;
} else {
name = "product_image_" + productId;
}
File dir = cw.getDir(core.images, Context.MODE_PRIVATE);
File image = new File(dir, name);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(image);
mIcon11.compress(Bitmap.CompressFormat.PNG, 1, fos);
} catch (Exception e) {
} finally {
fos.close();
}
path = image.getAbsolutePath();
mIcon11 = BitmapFactory.decodeFile(path);
} catch (Exception e) {
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
if(image != null) {
image.setImageBitmap(result);
}
if(productId == 0) {
//core.dbHelper.updateCatImage(catId, path);
} else {
//core.dbHelper.updateProductImage(productId, path);
}
}}
Вот адаптер
public class ItemsCursorAdapter extends CursorAdapter {
Core core;
public ItemsCursorAdapter(Activity context, Cursor cursor) {
super(context, cursor);
core = Core.getInstance();
}
public void bindView(View view, Context context, Cursor cursor) {
VHolder v = (VHolder) view.getTag();
int nameIndex = cursor.getColumnIndex("name");
String sName = cursor.getString(nameIndex);
v.name.setText(sName);
int priceIndex = cursor.getColumnIndex("price");
double dPrice = cursor.getDouble(priceIndex);
v.price.setText(String.valueOf(dPrice) + " сом");
int opriceIndex = cursor.getColumnIndex("old_price");
double doPrice = cursor.getDouble(opriceIndex);
v.oldPrice.setText(String.valueOf(doPrice) + " сом");
v.oldPrice.setPaintFlags(v.oldPrice.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
int idIndex = cursor.getColumnIndex("prod_id");
int id = cursor.getInt(idIndex);
int imageIndex = cursor.getColumnIndex("image");
String imageUrl = cursor.getString(imageIndex);
v.btn.setTag(id);
v.btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
/*int id = (int) v.btn.getTag();
Core core = Core.getInstance();
core.addToCart(id);*/
}
});
int cacheIndex = cursor.getColumnIndex("cached_image");
int isCached = cursor.getInt(cacheIndex);
int fileIndex = cursor.getColumnIndex("device_image");
String filePath = cursor.getString(fileIndex);
v.image = (ImageView) view.findViewById(R.id.product_item_image);
String fileName = "SOME_PATH" + id;
if (new File(fileName).exists()) {
Bitmap bitmap = BitmapFactory.decodeFile(fileName);
v.image.setImageBitmap(bitmap);
} else {
new ImageLoader(v.image, id, 0).execute(imageUrl);
}
}
public View newView(Context context, Cursor cursor, ViewGroup viewGroup) {
LayoutInflater lInflater = LayoutInflater.from(context);
View view = lInflater.inflate(R.layout.product_item, null);
VHolder holder = new VHolder();
holder.image = (ImageView) view.findViewById(R.id.product_item_image);
holder.name = (TextView) view.findViewById(R.id.product_item_name);
holder.price = (TextView) view.findViewById(R.id.product_item_price);
holder.oldPrice = (TextView) view.findViewById(R.id.product_item_old_price);
holder.btn = (Button) view.findViewById(R.id.product_item_buy);
view.setTag(holder);
return view;
}}
Проблема видимо в том, что я неправильно передаю ImageView
в ImageLoader
, но не могу понять как это исправить. Буду признателен всем, кто что-то посоветует.