MKDenys
MKDenys

Reputation: 115

How to use picasso or universal image loader and listview

Load from the internet text data and link to image. I can't understand how to load image in listview. Read, it needs to use picasso or universal image loader, but did not understand how. Correct my code, please

    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);
     }

}

Upvotes: 0

Views: 5855

Answers (2)

piobab
piobab

Reputation: 1352

Create your own adapter which extends from ArrayAdapter. There are a lot of examples:

then in your getView method call (something similar depends on your implementation):

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

For more info refer to Picasso documentation.

Upvotes: 5

Steve M
Steve M

Reputation: 9784

With Picasso, you create a custom adapter for the ListView and place the .load(url) call on your ImageView in getView(). Probably, the solution is the same for the other library you mentioned.

However, it appears in your case you are needing to get the url for the image in an AsycTask ahead of time. In that case you will also need some logic to get urls before creating the adapter or will need some fancy logic in the adapter to load the urls and then reload the view.

Upvotes: 0

Related Questions