Cargar imágenes asincrónicas en listView

Quiero cargar imágenes de un servidor, después de cargar los datos en una vista de lista. Sé que un montón de temas existentes para este problema, pero no he encontrado la solución …

Así que este es mi código:

//asyncTackClass for loadingpictures public class LoadImagesThread extends AsyncTask<Bundle, Void, Bitmap> { private ImageView view; private Bitmap bm; private Context context; private final WeakReference<ImageView> imageViewReference; private final String BUNDLE_URL = "url"; private final String BUNDLE_NAME = "name"; private final String BUNDLE_BM = "bm"; public LoadImagesThread(Context context, ImageView view) { this.context=context; imageViewReference = new WeakReference<ImageView>(view); } @Override protected Bitmap doInBackground(Bundle... b) { Bitmap bm =null; if (StorageHelper.getBitmap(b[0].getString(BUNDLE_NAME)) != null) { // Check the sdcard bm = StorageHelper.getBitmap(b[0].getString(BUNDLE_NAME)); Log.w("LoadImagesThread", "Get image from sdcard : "+b[0].getString(BUNDLE_NAME)); } else { // Check the server bm = ServiceHelper.getBitmapFromURL(b[0].getString(BUNDLE_URL)); StorageHelper.saveBitmap(bm, b[0].getString(BUNDLE_NAME)); // Save image on sdcard Log.w("LoadImagesThread", "Get image from server : "+b[0].getString(BUNDLE_NAME)); } return bm; } @Override protected void onPostExecute(final Bitmap bm) { super.onPostExecute(bm); if (bm != null){ //if bitmap exists... view = imageViewReference.get(); // Fade out Animation fadeOutAnimation = AnimationUtils.loadAnimation(context, R.anim.fadeoutimage); fadeOutAnimation.setAnimationListener(new AnimationListener() { public void onAnimationStart(Animation animation) { } public void onAnimationRepeat(Animation animation) { } public void onAnimationEnd(Animation animation) { // Fade in view.setImageBitmap(bm); Animation fadeInAnimation = AnimationUtils.loadAnimation(context, R.anim.fadeinimage); view.startAnimation(fadeInAnimation); } }); // Launch the fadeout view.startAnimation(fadeOutAnimation); }else{ //if not picture, display the default ressource view.setImageResource(R.drawable.productcarre); } } } 

El código se utiliza para mostrar un mapa de bits en un ImageView

Y este es el adaptador:

 public class ListViewShoplistStoresAdapter extends BaseAdapter { private ArrayList<Shop> shopList; private Activity activity; private HashMap<Integer, ImageView> views; private final String BUNDLE_URL = "url"; private final String BUNDLE_NAME = "name"; private final String BUNDLE_POS = "pos"; private final String BUNDLE_ID = "id"; public ListViewShoplistStoresAdapter(Activity activity, ArrayList<Shop> shopList) { super(); this.activity = activity; this.shopList = shopList; this.views = new HashMap<Integer, ImageView>(); } public int getCount() { return shopList.size(); } public Object getItem(int position) { return shopList.get(position); } public long getItemId(int position) { return shopList.get(position).getId(); } private class ViewHolder { public TextView store; public TextView name; public ImageView ImageStore; } public View getView(int position, View convertView, ViewGroup parent) { ViewHolder view; LayoutInflater inflator = activity.getLayoutInflater(); if(convertView == null) { view = new ViewHolder(); convertView = inflator.inflate(R.layout.listviewshops, null); view.store = (TextView) convertView.findViewById(R.id.store); view.name = (TextView) convertView.findViewById(R.id.name); view.ImageStore = (ImageView) convertView.findViewById(R.id.imgstore); convertView.setTag(view); }else { view = (ViewHolder) convertView.getTag(); } Typeface regular=Typeface.createFromAsset(activity.getAssets(), "fonts/RobotoRegular.ttf"); view.store.setTypeface(regular); Typeface light=Typeface.createFromAsset(activity.getAssets(), "fonts/RobotoLight.ttf"); view.store.setTypeface(light); Brand brand = StorageHelper.getBrand(activity, shopList.get(position).getBrandId()); if (brand == null) { Log.e("SetShopInAdapter","Brand null"); Toast.makeText(activity, "Impossible d'afficher la liste de magasins", Toast.LENGTH_LONG).show(); } else { view.store.setText(brand.getName()); view.name.setText(shopList.get(position).getName()); view.ImageStore.setImageResource(R.drawable.productcarre); } Bundle b = new Bundle(); //url of the pict b.putString(BUNDLE_URL, ServiceHelper.getImageUrl("brand", brand.getName())); // name of image b.putString(BUNDLE_NAME, ServiceHelper.getCleanImageName(brand.getName())); //position in the listView b.putInt(BUNDLE_POS, position); //id of the current object b.putInt(BUNDLE_ID, brand.getId()); //put info in the map in order to display in the onPostExecute if(views.get(position)==null){ views.put(position, view.ImageStore); // launch thread new LoadImagesThread(activity.getApplicationContext(), view.ImageStore).execute(b); } return convertView; } } 

Por lo tanto, cuando utilicé un GridView, no hubo problemas, pero cuando uso un ListView la imagen se cambia sólo en el primer elemento!

Ejemplo : Quiero mostrar las imágenes del producto para los artículos "coche", "casa" y "manzana". El código lanzará el hilo y todas las imágenes (coche luego casa y finalmente manzana) se mostrarán en el primer artículo (el artículo de coche) … Y la casa y la manzana mientras no tienen imágenes !!

¿Sabes lo que debo hacer?

Gracias

Usted debe referirse a este blog. Es impresionante.

http://android-developers.blogspot.in/2010/07/multithreading-for-performance.html

También se ofrece una aplicación de demostración en este enlace. Descárgalo y trata de implementarlo en tu aplicación.

Siga este enlace para Cargar imágenes desde el servidor en ListView.

http://android-er.blogspot.in/2010/07/load-listview-in-background-asynctask.html

Hay mucho acerca de esto aquí en SO .. Asynchrnous carga como que se llama "Lazy Loading"

https://github.com/thest1/LazyList

Para la plena implementación de dicho proceso con

Para cargar imágenes en general recomiendo esto:

https://github.com/nostra13/Android-Universal-Image-Loader

Puede usar volley para mejorar el rendimiento de listview. Echa un vistazo a este sencillo ejemplo: Android ListView personalizado con la imagen y el texto utilizando Volley

  • Android listview obtiene el elemento seleccionado
  • Android: cómo usar SectionIndexer
  • RealmBaseAdapter con encabezados de sección
  • Android - EditTexts dentro de ListView vinculado a Custom ArrayAdapter - manteniendo un registro de los cambios
  • ¿Cómo hacer gradiente transparente?
  • Reiniciar el contador después de hacer clic en el botón
  • Cómo configurar el tamaño y el diseño en onSizeChanged?
  • EditText no recibe eventos clave TAB - stock soft vk
  • Espera unitl El acabado smoothScrollToPosition () de ListView
  • Reciclar vistas en un listview, vale la pena?
  • Cómo mostrar un botón pulsando una vez un elemento de la lista
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.