【问题标题】:Image from URL in ListView using SimpleAdapter使用 SimpleAdapter 从 ListView 中的 URL 获取图像
【发布时间】:2015-05-18 23:23:07
【问题描述】:

我希望你能帮助我解决这个错误,我被困了几天。 我想使用 SimpleAdapter 在 ListView 中显示来自 URL 的 ImageView,但图像显示为白色。

我最近刚开始使用 android,所以,我对 LazyList 和其他东西不太了解..

如何实现我的代码以使用来自 URL 的 ImageView?这是我的 AsyncTask 来完成所有工作。

class LoadAllProducts extends AsyncTask<String, String, String> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(ListAlojamientoFragment.this.getActivity());
        pDialog.setMessage("Cargando Alojamientos... Espere por favor.");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }

    protected String doInBackground(String... args) {
        // Creando parametros
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        // Obteniendo JSON string desde url
        JSONObject json = jParser.makeHttpRequest(url_json, "GET", params);

        try {

            int success = json.getInt(TAG_SUCCESS);

            if (success == 1) {

                alojamiento = json.getJSONArray(TAG_ALOJAMIENTO);

                for (int i = 0; i < alojamiento.length(); i++) {
                    JSONObject c = alojamiento.getJSONObject(i);

                    String idAlojamiento = c.getString(TAG_ID);
                    String nombre = c.getString(TAG_NOMBRE);
                    String comuna = c.getString(TAG_COMUNA);
                    String fechaIngreso = c.getString(TAG_FECHA);

                    //Img example
                    String urlImg = "http://www.markpascua.com/wp-content/android.jpg";

                    //AQuery Library
                    aq.id(imageView).image(urlImg, true, true, 1, R.drawable.hotel2_1);

                    HashMap<String, String> map = new HashMap<String, String>();

                    map.put(TAG_IMAGE, urlImg);
                    map.put(TAG_ID, idAlojamiento);
                    map.put(TAG_NOMBRE, nombre);
                    map.put(TAG_FECHA, fechaIngreso);

                    productsList.add(map);
                }
            } else {
                // 
            }
        } catch (JSONException e) {
            pDialog.dismiss();
            e.printStackTrace();

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

        }

        return null;
    }

    protected void onPostExecute(String file_url) {

        pDialog.dismiss();

        getActivity().runOnUiThread(new Runnable() {
            public void run() {

                 ListAdapter adapter = new SimpleAdapter(
                        ListAlojamientoFragment.this.getActivity(), productsList,
                        R.layout.lista_items, new String[]{TAG_IMAGE, TAG_NOMBRE,
                        TAG_FECHA, TAG_ID},
                        new int[]{R.id.img_row, R.id.idAlojamiento, R.id.nombre, R.id.idAlojamientoDetalle});

                setListAdapter(adapter);
            }
        });

    }

}

---------[编辑]---------

我最近解决了这个问题,如果有人遇到同样的问题,这里是从url下载图像到ListView的代码。

AsynTask 下载 json。

class getAllHouses extends AsyncTask<String, String, String> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(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 = new ArrayList<NameValuePair>();
        JSONObject json = jParser.makeHttpRequest(URL_ALL_HOUSES, "GET", params);

        try {
            int success = json.getInt(TAG_SUCCESS);

            if (success == 1) {

                alojamiento = json.getJSONArray(TAG_ALOJAMIENTO);

                for (int i = 0; i < alojamiento.length(); i++) {
                    JSONObject c = alojamiento.getJSONObject(i);

                    String idAlojamiento = c.getString(TAG_ID);
                    String nombre = c.getString(TAG_NOMBRE);
                    String comuna = c.getString(TAG_COMUNA);
                    String fechaIngreso = c.getString(TAG_FECHA);
                    latitud = c.getString(TAG_LATITUD);
                    longitud = c.getString(TAG_LONGITUD);

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

                    HashMap<String, Object> map = new HashMap<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(new Runnable() {
                    @Override
                    public void run() {


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

                    }
                });

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

            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {


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

                }
            });
        }

        return null;
    }

    protected void onPostExecute(String file_url) {

        pDialog.dismiss();

        getActivity().runOnUiThread(new Runnable() {
            public void run() {

                 SimpleAdapter adapter = new SimpleAdapter(
                        ListAlojamientoFragment.this.getActivity(), productsList,
                        R.layout.lista_items, new String[]{"flag", TAG_NOMBRE,
                        TAG_FECHA, TAG_ID, TAG_LATITUD, TAG_LONGITUD},
                        new int[]{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);
                    String imgUrl = (String) hm.get("flag_path");

                    ImageLoaderTask imageLoaderTask = new ImageLoaderTask();

                    HashMap<String, Object> hmDownload = new HashMap<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 异步下载图片到 ListView..

private class ImageLoaderTask extends AsyncTask<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 position
            return hmBitmap;



        }catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

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

        // Getting the position of the downloaded image
        int 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();

    }
}

【问题讨论】:

    标签: android listview url imageview


    【解决方案1】:

    【讨论】:

      【解决方案2】:

      我最近解决了这个问题,如果有人遇到同样的问题,这里是从url下载图像到ListView的代码。

      AsynTask 下载 json。

      class getAllHouses extends AsyncTask<String, String, String> {
      
          @Override
          protected void onPreExecute() {
              super.onPreExecute();
              pDialog = new ProgressDialog(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 = new ArrayList<NameValuePair>();
              JSONObject json = jParser.makeHttpRequest(URL_ALL_HOUSES, "GET", params);
      
              try {
                  int success = json.getInt(TAG_SUCCESS);
      
                  if (success == 1) {
      
                      alojamiento = json.getJSONArray(TAG_ALOJAMIENTO);
      
                      for (int i = 0; i < alojamiento.length(); i++) {
                          JSONObject c = alojamiento.getJSONObject(i);
      
                          String idAlojamiento = c.getString(TAG_ID);
                          String nombre = c.getString(TAG_NOMBRE);
                          String comuna = c.getString(TAG_COMUNA);
                          String fechaIngreso = c.getString(TAG_FECHA);
                          latitud = c.getString(TAG_LATITUD);
                          longitud = c.getString(TAG_LONGITUD);
      
                          //URL image download
                          String urlImg = "http://es.opendomo.org/files/android-logo.png";
                          //String
                          flag = urlImg;
      
                          HashMap<String, Object> map = new HashMap<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(new Runnable() {
                          @Override
                          public void run() {
      
      
                              final AlertDialog.Builder alert = new AlertDialog.Builder(getActivity());
                              alert.setTitle("¡Error!");
                              alert.setMessage("No connections are available");
                              alert.setCancelable(false);
                              alert.setPositiveButton("Aceptar", new DialogInterface.OnClickListener() {
                                  @Override
                                  public void onClick(DialogInterface dialog, int which) {
                                      dialog.cancel();
                                  }
                              });
                              alert.create().show();
      
                          }
                      });
      
              } catch (NullPointerException e){
                  pDialog.dismiss();
                  e.printStackTrace();
      
                  getActivity().runOnUiThread(new Runnable() {
                      @Override
                      public void run() {
      
      
                          final AlertDialog.Builder alert = new AlertDialog.Builder(getActivity());
                          alert.setTitle("¡Error!");
                          alert.setMessage("No connections are available");
                          alert.setCancelable(false);
                          alert.setPositiveButton("Aceptar", new DialogInterface.OnClickListener() {
                              @Override
                              public void onClick(DialogInterface dialog, int which) {
                                  dialog.cancel();
                              }
                          });
                          alert.create().show();
      
                      }
                  });
              }
      
              return null;
          }
      
          protected void onPostExecute(String file_url) {
      
              pDialog.dismiss();
      
              getActivity().runOnUiThread(new Runnable() {
                  public void run() {
      
                       SimpleAdapter adapter = new SimpleAdapter(
                              ListAlojamientoFragment.this.getActivity(), productsList,
                              R.layout.lista_items, new String[]{"flag", TAG_NOMBRE,
                              TAG_FECHA, TAG_ID, TAG_LATITUD, TAG_LONGITUD},
                              new int[]{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);
                          String imgUrl = (String) hm.get("flag_path");
      
                          ImageLoaderTask imageLoaderTask = new ImageLoaderTask();
      
                          HashMap<String, Object> hmDownload = new HashMap<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 异步下载图片到 ListView..

      private class ImageLoaderTask extends AsyncTask<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 position
                  return hmBitmap;
      
      
      
              }catch (Exception e) {
                  e.printStackTrace();
              }
              return null;
          }
      
          @Override
          protected void onPostExecute(HashMap<String, Object> result) {
              // Getting the path to the downloaded image
              String path = (String) result.get("flag");
      
              // Getting the position of the downloaded image
              int 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();
      
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2014-05-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-02-08
        • 1970-01-01
        • 2011-08-23
        相关资源
        最近更新 更多