0

I have looked for this everywhere and all possible sources but none seems to work. I found many tutorials that showed fetching and displaying image from URL in ListView but they just don't work for fragments.

Here is my code which I'm using to fetch title and links from url but images just dont come

public class FindPeopleFragment extends ListFragment {  

 TextView txtdesc;
 TextView txtdesc2;
 TextView txtdesc3;

    String flags=Integer.toString(R.drawable.logo);

    String posts;

 @Override
  public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);        

   new Description().execute();   

  }

class Description extends AsyncTask<Void, Void, Void> {

    String title;
    String link;
    Bitmap bitmap = null;
    int i=0;
    List<HashMap<String,String>> aList = new ArrayList<HashMap<String,String>>();

    protected void onPreExecute()    {  }

    protected Void doInBackground(Void... params) {


           try {
            Document document = Jsoup.connect("http://www.marineinsight.com/shipping-news").get();

         Elements links = document.select("article a");
        //  posts = links.text();


            for(Element l : links)
            {
                Elements img = document.select("article a img[src]");
                String imgSrc = img.attr("src");
                URL newurl = new URL(imgSrc); 

                title=l.attr("title");
                if(title==""){ continue; }     
                link=l.attr("href");
                HashMap<String, String> hm = new HashMap<String,String>();
                 hm.put("txt", title);
                 hm.put("cur",link);
                 hm.put("flag",imgSrc);
                 aList.add(hm); 
                 i++;
                    }

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

    }

    protected void onPostExecute(Void result) {

         // Keys used in Hashmap
         String[] from = { "flag","txt","cur" };

         // Ids of views in listview_layout
         int[] to = { R.id.thumb,R.id.title,R.id.date};

         // Instantiating an adapter to store each items
         // R.layout.listview_layout defines the layout of each item
         SimpleAdapter adapter = new SimpleAdapter(getActivity().getBaseContext(), aList, R.layout.list_item, from, to);

      setListAdapter(adapter);      
        }      
}

}

I know that hashmap<string,string> will not be able to display images but I have also tried hashmap<string,object>but it doesn't work as well.

Also I want to implement this through fragments because this list should be a part of side navigation drawer.

Micer
  • 8,731
  • 3
  • 79
  • 73
Swapna Lekshmanan
  • 514
  • 10
  • 30
  • http://stackoverflow.com/questions/23985786/android-display-image-in-imageview-by-simpleadapter Check Alan Deep's answer, you got image url only. Need get image from that url after only you can set that in image view. – SathishKumar Oct 06 '14 at 08:07
  • Have a look at Picasso library, it will save you from a world of hurt.Very easy to use. – Chris Oct 06 '14 at 08:10
  • @SathishKumar I had already tried that helpStack example. but the main problem is i want to do this in FRAGMENT all examples I get are for activity. M not able to figure out what is the reason. thanks – Swapna Lekshmanan Oct 06 '14 at 09:44
  • Do you able to get correct result after parsing the response? Check `aList` have populated correctly. If you get correct parsed data means remaining thing is simple only – SathishKumar Oct 06 '14 at 10:39
  • @SathishKumar yes everything is correct except the image in the list view. dont know what is wrong with the images. can you help me modify the code above so that i can retrieve images as well.. m totally new to android development and was able to get till here after working for 2 weeks. – Swapna Lekshmanan Oct 06 '14 at 10:52

2 Answers2

0

if get image in String then first convert that imageSting to bitmap. try below code

public static Bitmap StringToBitMap(String encodedString) {
        try {
            byte[] encodeByte = Base64.decode(encodedString, Base64.DEFAULT);
            Bitmap bitmap = BitmapFactory.decodeByteArray(encodeByte, 0,
                    encodeByte.length);
            return bitmap;
        } catch (Exception e) {
            e.getMessage();
            return null;
        }

and now you can use HashMap<String,Object>

Lokesh
  • 3,247
  • 2
  • 33
  • 62
0

repo1.maven.org/maven2/com/squareup/picasso/picasso/2.3.4/picasso-2.3.4.jar Download this jar file and add it into libs folder of your project.

Add ImageLoaderAdapter within your FindPeopleFragment

class ImageLoaderAdapter extends BaseAdapter {

            private List<HashMap<String, String>> dataList;

            public ImageLoaderAdapter(List<HashMap<String, String>> list) {
                this.dataList = list;
            }

            @Override
            public int getCount() {
                return dataList.size();
            }

            @Override
            public Object getItem(int arg0) {
                return null;
            }

            @Override
            public long getItemId(int position) {
                return 0;
            }

            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                if (convertView == null) {
                    LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(
                            Context.LAYOUT_INFLATER_SERVICE);
                    convertView = inflater.inflate(R.layout.list_item, null);
                }
                HashMap<String, String> map = dataList.get(position);
                ((TextView) convertView.findViewById(R.id.title)).setText(map.get("txt"));
                ((TextView) convertView.findViewById(R.id.date)).setText(map.get("cur"));
                Picasso.with(getActivity()).load(map.get("flag"))
                        .into(((ImageView) convertView.findViewById(R.id.thumb)));
                return convertView;
            }

        }

update Description's onPostExecute as below,

    protected void onPostExecute(Void result) {

        /*
         * // Keys used in Hashmap String[] from = { "flag","txt","cur"
         * }; // Ids of views in listview_layout int[] to = {
         * R.id.thumb,R.id.title,R.id.date}; // Instantiating an adapter
         * to store each items // R.layout.listview_layout defines the
         * layout of each item SimpleAdapter adapter = new
         * SimpleAdapter(getActivity().getBaseContext(), aList,
         * R.layout.list_item, from, to);
         */
        if (aList != null) {
            ImageLoaderAdapter adapter = new ImageLoaderAdapter(aList);
            setListAdapter(adapter);
        }else{
                Toast.makeText(getActivity(), "Data list being empty", 

Toast.LENGTH_LONG).show();
            }
}

Change for loop with in doInBackground as below

                   for(Element l : links)
                   {
                        Elements img = l.select("img[src]");//This line changed
                        String imgSrc = img.attr("src");//This line changed
                      // URL newurl = new URL(imgSrc); 

                       title=l.attr("title");
                       if(title==""){ continue; }     
                       link=l.attr("href");
                       HashMap<String, String> hm = new HashMap<String,String>();
                        hm.put("txt", title);
                        hm.put("cur",link);
                        hm.put("flag",imgSrc);
                        aList.add(hm); 
                        i++;
                   }

To know more about library check it

SathishKumar
  • 1,644
  • 1
  • 14
  • 28
  • Wow @SathishKumar you just nailed it.. finally i have the image..just one more help pls..the image i get is same for all the items(the thumbnail of first article is seen on all). how do i give each article its respective thumbnail..and yes i just can't thank you enough :) – Swapna Lekshmanan Oct 06 '14 at 12:19
  • you have bug at code `Elements img = document.select("article a img[src]"); String imgSrc = img.attr("src");` in `doInBackground`, please check on it. Here you need to get `img` `src` from `Element` object `l` not from `Elements` object `img` – SathishKumar Oct 06 '14 at 12:26
  • thanks for pointing out the bug... i have realized that it should not be that way but how do i fetch both 'Elements links = document.select("article a");' and 'Elements img = document.select("article a img[src]");' in the same 'for' loop? i tried running individual loops for 'links' and 'img' but then the app crashed. what shd i do now? – Swapna Lekshmanan Oct 06 '14 at 13:54
  • Please post your `article` tag's data – SathishKumar Oct 07 '14 at 04:28