如何使用毕加索或通用图像加载器和列表视图

时间:2014-01-02 23:00:38

标签: android universal-image-loader picasso

从互联网加载文本数据并链接到图像。我无法理解如何在listview中加载图像。阅读,它需要使用毕加索或通用图像加载器,但不明白如何。请更正我的代码

    public class JsonReadTask extends AsyncTask<String, Void, String> {

      @Override
      protected String doInBackground(String... params) {
       HttpClient httpclient = new DefaultHttpClient();
       HttpPost httppost = new HttpPost(params[0]);
       try {
        HttpResponse response = httpclient.execute(httppost);
        jsonResult = inputStreamToString(
          response.getEntity().getContent()).toString();
       }

       catch (ClientProtocolException e) {
        e.printStackTrace();
       } catch (IOException e) {
        e.printStackTrace();
       }
       return null;
      }

      private StringBuilder inputStreamToString(InputStream is) {
       String rLine = "";
       StringBuilder answer = new StringBuilder();
       BufferedReader rd = new BufferedReader(new InputStreamReader(is));

       try {
        while ((rLine = rd.readLine()) != null) {
         answer.append(rLine);
        }
       }

       catch (IOException e) {
        // e.printStackTrace();
        Toast.makeText(getActivity(),
          "Error..." + e.toString(), Toast.LENGTH_LONG).show();
       }
       return answer;
      }

      @Override
      protected void onPostExecute(String result) {
       ListDrwaer();
      }
     }// end async task

     public void accessWebService() {
      JsonReadTask task = new JsonReadTask();
      // passes values for the urls string array
      task.execute(new String[] { url });
     }
     private final String ATTRIBUTE1 = "header"; 
     private final String ATTRIBUTE2 = "short_text";
     private final String ATTRIBUTE3 = "team";
     private final String ATTRIBUTE4 = "datatime";
     private final String ATTRIBUTE5 = "photo_url";
     Drawable drawable;
     // build hash set for list view
     public void ListDrwaer() {          
        // упаковываем данные в понятную для адаптера структуру
            ArrayList<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
                    Map<String, Object> m;

            // массив имен атрибутов, из которых будут читаться данные
            String[] from = {ATTRIBUTE1, ATTRIBUTE2, ATTRIBUTE3, ATTRIBUTE4, ATTRIBUTE5};

            // массив ID View-компонентов, в которые будут вставлять данные
            int[] to = { R.id.header, R.id.short_text,  R.id.team, R.id.datatime, R.id.img_news};

      try {
       JSONObject jsonResponse = new JSONObject(jsonResult);
       JSONArray jsonMainNode = jsonResponse.optJSONArray("news");
       for (int i = 0; i < jsonMainNode.length(); i++) {
        JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
        String header = jsonChildNode.optString("header");
        String short_text = jsonChildNode.optString("short_text");
        String team = jsonChildNode.optString("team");
        String datatime = jsonChildNode.optString("datatime");
        String photo_url = jsonChildNode.optString("photo_url");    


        // создаем новый Map
        m = new HashMap<String, Object>();
        m.put(ATTRIBUTE1, header);
        m.put(ATTRIBUTE2, short_text);
        m.put(ATTRIBUTE3, team);
        m.put(ATTRIBUTE4, datatime);
     //   m.put(ATTRIBUTE5, url_photo);
        // добавляем его в коллекцию
        data.add(m);
       }
      } catch (JSONException e) {
       Toast.makeText(getActivity(), "Error" + e.toString(),
         Toast.LENGTH_SHORT).show();
      }

      SimpleAdapter simpleAdapter = new SimpleAdapter(getActivity(), data,
        R.layout.news_details,
        from, to);        
      Parcelable state = listView.onSaveInstanceState();
      listView.setAdapter(simpleAdapter);
      listView.onRestoreInstanceState(state);
     }

}

2 个答案:

答案 0 :(得分:5)

创建自己的适配器,该适配器从ArrayAdapter扩展。有很多例子:

然后在你的getView方法调用中(类似的东西取决于你的实现):

Picasso.with(context).load(getItem(position).get(ATTRIBUTE5)).into(holder.imageView);

有关更多信息,请参阅Picasso documentation

答案 1 :(得分:0)

使用Picasso,您可以为ListView创建自定义适配器,并在getView()中将.load(url)调用放在ImageView上。也许,您提到的其他库的解决方案是相同的。

但是,在您的情况下,您需要提前获取AsycTask中的图像的URL。在这种情况下,您还需要一些逻辑来在创建适配器之前获取URL,或者在适配器中需要一些奇特的逻辑来加载URL然后重新加载视图。