Skip to content Skip to sidebar Skip to footer

Image From Url In Listview Using Simpleadapter

I hope you can help me with this error, I'm stuck in this for a few days. I want to show a ImageView from URL in a ListView using SimpleAdapter, but the image are showing in white.

Solution 1:

Solution 2:

I recently solved the problem, if anyone have the same problem, here is the code to download image from url to ListView.

AsynTask to download json.

classgetAllHousesextendsAsyncTask<String, String, String> {

    @OverrideprotectedvoidonPreExecute() {
        super.onPreExecute();
        pDialog = newProgressDialog(ListAlojamientoFragment.this.getActivity());
        pDialog.setMessage("Loading... please wait a second.");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }


    protected String doInBackground(String... args) {

        List<NameValuePair> params = newArrayList<NameValuePair>();
        JSONObjectjson= jParser.makeHttpRequest(URL_ALL_HOUSES, "GET", params);

        try {
            intsuccess= json.getInt(TAG_SUCCESS);

            if (success == 1) {

                alojamiento = json.getJSONArray(TAG_ALOJAMIENTO);

                for (inti=0; i < alojamiento.length(); i++) {
                    JSONObjectc= alojamiento.getJSONObject(i);

                    StringidAlojamiento= c.getString(TAG_ID);
                    Stringnombre= c.getString(TAG_NOMBRE);
                    Stringcomuna= c.getString(TAG_COMUNA);
                    StringfechaIngreso= c.getString(TAG_FECHA);
                    latitud = c.getString(TAG_LATITUD);
                    longitud = c.getString(TAG_LONGITUD);

                    //URL image downloadStringurlImg="http://es.opendomo.org/files/android-logo.png";
                    //String
                    flag = urlImg;

                    HashMap<String, Object> map = newHashMap<String, Object>();

                    map.put("flag", R.drawable.blank);
                    map.put("flag_path", flag);
                    map.put(TAG_ID, idAlojamiento);
                    map.put(TAG_NOMBRE, nombre);
                    map.put(TAG_FECHA, fechaIngreso);
                    map.put(TAG_LATITUD, latitud);
                    map.put(TAG_LONGITUD, longitud);
                    productsList.add(map);

                }
            } else {
                // 
            }

        } catch (JSONException e) {
                pDialog.dismiss();
                e.printStackTrace();

                getActivity().runOnUiThread(newRunnable() {
                    @Overridepublicvoidrun() {


                        final AlertDialog.Builderalert=newAlertDialog.Builder(getActivity());
                        alert.setTitle("¡Error!");
                        alert.setMessage("No connections are available");
                        alert.setCancelable(false);
                        alert.setPositiveButton("Aceptar", newDialogInterface.OnClickListener() {
                            @OverridepublicvoidonClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                            }
                        });
                        alert.create().show();

                    }
                });

        } catch (NullPointerException e){
            pDialog.dismiss();
            e.printStackTrace();

            getActivity().runOnUiThread(newRunnable() {
                @Overridepublicvoidrun() {


                    final AlertDialog.Builderalert=newAlertDialog.Builder(getActivity());
                    alert.setTitle("¡Error!");
                    alert.setMessage("No connections are available");
                    alert.setCancelable(false);
                    alert.setPositiveButton("Aceptar", newDialogInterface.OnClickListener() {
                        @OverridepublicvoidonClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                        }
                    });
                    alert.create().show();

                }
            });
        }

        returnnull;
    }

    protectedvoidonPostExecute(String file_url) {

        pDialog.dismiss();

        getActivity().runOnUiThread(newRunnable() {
            publicvoidrun() {

                 SimpleAdapteradapter=newSimpleAdapter(
                        ListAlojamientoFragment.this.getActivity(), productsList,
                        R.layout.lista_items, newString[]{"flag", TAG_NOMBRE,
                        TAG_FECHA, TAG_ID, TAG_LATITUD, TAG_LONGITUD},
                        newint[]{R.id.img_row, R.id.idAlojamiento, R.id.nombre, R.id.idAlojamientoDetalle, R.id.id_latitud, R.id.id_longitud});

                 mListView.setAdapter(adapter);

                for(int i=0;i<adapter.getCount();i++) {
                    HashMap<String, Object> hm = (HashMap<String, Object>) adapter.getItem(i);
                    StringimgUrl= (String) hm.get("flag_path");

                    ImageLoaderTaskimageLoaderTask=newImageLoaderTask();

                    HashMap<String, Object> hmDownload = newHashMap<String, Object>();
                    hm.put("flag_path", imgUrl);
                    hm.put("position", i);

                    // Starting ImageLoaderTask to download and populate image in the listview
                    imageLoaderTask.execute(hm);
                }

            }
        });

    }

}

AsynTask To download Images to ListView asynchronous..

privateclassImageLoaderTaskextendsAsyncTask<HashMap<String, Object>, Void, HashMap<String, Object>>{

    @Override
    protected HashMap<String, Object> doInBackground(HashMap<String, Object>... hm) {


        InputStream iStream= null;
        String imgUrl = (String) hm[0].get("flag_path");
        int position = (Integer) hm[0].get("position");

        URL url;
        try {
            url = new URL(imgUrl);

            // Creating an http connection to communicate with url
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

            // Connecting to url
            urlConnection.connect();

            // Reading data from url
            iStream = urlConnection.getInputStream();

            // Getting Caching directory
            File cacheDirectory = getActivity().getBaseContext().getCacheDir();

            // Temporary file to store the downloaded image
            File tmpFile = new File(cacheDirectory.getPath() + "/wpta_"+position+".png");

            // The FileOutputStream to the temporary file
            FileOutputStream fOutStream = new FileOutputStream(tmpFile);

            // Creating a bitmap from the downloaded inputstream
            Bitmap b = BitmapFactory.decodeStream(iStream);

            // Writing the bitmap to the temporary file as png or jpeg file
            b.compress(Bitmap.CompressFormat.JPEG,10, fOutStream);

            // Flush the FileOutputStream
            fOutStream.flush();

            //Close the FileOutputStream
            fOutStream.close();

            // Create a hashmap object to store image path and its position in the listview
            HashMap<String, Object> hmBitmap = new HashMap<String, Object>();

            // Storing the path to the temporary image file
            hmBitmap.put("flag", tmpFile.getPath());

            // Storing the position of the image in the listview
            hmBitmap.put("position", position);


            // Returning the HashMap object containing the image path and positionreturn hmBitmap;



        }catch (Exception e) {
            e.printStackTrace();
        }
        returnnull;
    }

    @Override
    protectedvoid onPostExecute(HashMap<String, Object> result) {
        // Getting the path to the downloaded imageString path = (String) result.get("flag");

        // Getting the position of the downloaded imageint position = (Integer) result.get("position");

        // Getting adapter of the listview
        SimpleAdapter adapter = (SimpleAdapter ) mListView.getAdapter();

        // Getting the hashmap object at the specified position of the listview
        HashMap<String, Object> hm = (HashMap<String, Object>) adapter.getItem(position);

        // Overwriting the existing path in the adapter
        hm.put("flag", path);

        // Noticing listview about the dataset changes
        adapter.notifyDataSetChanged();

    }
}

Post a Comment for "Image From Url In Listview Using Simpleadapter"