Rahul Baradia
Rahul Baradia

Reputation: 11951

Loading IMAGE from JSON URL into listview

I am trying to get image from URL then add it to a listview. I can successfully get the image, but I'm struggling with adding it to the listview.

I have tried this way:

    ListView lv = (ListView) findViewById(R.id.list);

    try {

        URL url = new URL("http://devcms.barcodo.com/Images/ProductImages/ThumbnailImages100/EG-BIRT-ST-JA_th.jpg");
        HttpGet httpRequest = null;
        httpRequest = new HttpGet(url.toURI());
        HttpClient httpclient = new DefaultHttpClient();
        HttpResponse response = (HttpResponse) httpclient.execute(httpRequest);
        HttpEntity entity = response.getEntity();
        BufferedHttpEntity b_entity = new BufferedHttpEntity(entity);
        InputStream input = b_entity.getContent();
        Bitmap bitmap = BitmapFactory.decodeStream(input); 

        HashMap<String, Object> docList = new HashMap<String, Object>();
        docList.put("IMAGE", bitmap);

        ArrayList<HashMap<String, Object>> al = new ArrayList<HashMap<String, Object>>();
        al.add(docList);

        simpleAdapter = new SimpleAdapter(this, al, R.layout.list_item,new String[] { "IMAGE" }, new int[] { R.id.image});
        lv.setAdapter(simpleAdapter);

Note: I am able to put it into an ImageView, but want to fetch into a listview.

Upvotes: 1

Views: 13655

Answers (4)

Rahul Baradia
Rahul Baradia

Reputation: 11951

Hello Guys

I have been searching thick and thin, and I am having some issues implementing a ListView with simpleadapter. Then @AYorhan said to use baseadapter and provided the link which helped me lot to solve my problem. Then @Ramesh provided me with an example which too helped me lot.

I am wanting to create my own List Adapter using simpleadapter to show in a listView but din't get success after that I used with BaseAdapter, with multiple items fetching from a server using JSON URL. I got the success.

I am sharing this working code link for some beginners in android might them get a help to retrieve image from server and fetch into the listview using baseadpater.

Regards :::: TechEnd

Upvotes: 1

sanjay kumar thakur
sanjay kumar thakur

Reputation: 77

fetch Images from json data into listview on list selected all the data move to second Activity name SingleContactActivity

ListView list;

ArrayList<FeeStacture> newsFeedList;
DeliveryListAdapter adapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    initializeAdress();


    list = (ListView) findViewById(R.id.list);
    adapter = new DeliveryListAdapter();
    list.setAdapter(adapter);
    list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {


            // getting values from selected ListItem
            String name = ((TextView) view.findViewById(R.id.rank))
                    .getText().toString();
            String cost = ((TextView) view.findViewById(R.id.country))
                    .getText().toString();
            String description = ((TextView) view.findViewById(R.id.population)).getText().toString();

            ImageView employee_id = ((ImageView) view.findViewById(R.id.imagestar));
           employee_id.buildDrawingCache();
            Bitmap bitmap=employee_id.getDrawingCache();





          Intent in = new Intent(getApplicationContext(),
                    SingleContactActivity.class);
            in.putExtra("name", name);
            in.putExtra("email", cost);
            in.putExtra("phone", description);

            in.putExtra("BitmapImage", bitmap);


            startActivity(in);
        }
    });

}


private void initializeAdress() {
    getNewsFeedListFromServer();

    newsFeedList = new ArrayList<FeeStacture>();
}


private void getNewsFeedListFromServer() {

    Fee_Stacture_WebService servics = new Fee_Stacture_WebService(this);
    servics.startTask();
}

public class DeliveryListAdapter extends BaseAdapter

{

    LayoutInflater minflat;

    public DeliveryListAdapter() {
        minflat = LayoutInflater.from(getApplicationContext());
    }

    @Override
    public int getCount() {
        return newsFeedList.size();
        //return MainActivity.size();
    }

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

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


    @Override
    public View getView(int position, View contentView, ViewGroup arg2) {

        ViewHolder holder;

        if (contentView == null) {
            holder = new ViewHolder();

            contentView = minflat.inflate(R.layout.home_custom_listitem, null);


            holder.rank = (TextView) contentView.findViewById(R.id.rank);
            holder.pop = (TextView) contentView.findViewById(R.id.population);
            holder.country = (TextView) contentView.findViewById(R.id.country);
            holder.image = (ImageView) contentView.findViewById(R.id.imagestar);

            contentView.setTag(holder);

        } else
        {
            holder = (ViewHolder) contentView.getTag();

        }

        FeeStacture newsObj = newsFeedList.get(position);



        holder.rank.setText(newsObj.getRank());
        holder.pop.setText(newsObj.getPop());

       holder.country.setText(newsObj.getCountry());
        new DownloadImageTask(holder.image).execute(newsFeedList.get(position).getItemIconStr());

        return contentView;


    }


    public class ViewHolder {
        // ImageView use;
        TextView rank;
        TextView pop;
        ImageView image;
        TextView address;
        TextView country;
        TextView gender;
        TextView phone;
    }

}

@Override
public void onSuccessfullResponse(Object object) {
    newsFeedList = (ArrayList<FeeStacture>) object;

    adapter.notifyDataSetChanged();

}

@Override
public void onErrorResponse(String error) {
    Toast.makeText(getApplicationContext(), error, Toast.LENGTH_SHORT).show();

}

@Override
public void onNetworkError(String error) {
    Toast.makeText(getApplicationContext(), error, Toast.LENGTH_SHORT).show();

}


@Override
public void onBackPressed() {
    // TODO Auto-generated method stub
    //super.onBackPressed();
    new AlertDialog.Builder(this)
            .setIcon(android.R.drawable.ic_menu_zoom)
            .setTitle("Web Service Demo")
            .setMessage("Are you sure you want to quit Web Demo ?")
            .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    finish();

                }

            })
            .setNegativeButton("No", null)
            .show();
}



private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
    ImageView bmImage;

    public DownloadImageTask(ImageView bmImage) {
        this.bmImage = bmImage;
    }

    protected Bitmap doInBackground(String... urls) {
        String urldisplay = urls[0];
        Bitmap mIcon11 = null;
        try {
            InputStream in = new java.net.URL(urldisplay).openStream();
            mIcon11 = BitmapFactory.decodeStream(in);
        } catch (Exception e) {
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }
        return mIcon11;
    }

    protected void onPostExecute(Bitmap result) {
        bmImage.setImageBitmap(result);
    }

}

}

Upvotes: 0

G M Ramesh
G M Ramesh

Reputation: 3412

try the following:

         public class ImageURL extends ListActivity{
        @Override
     public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (android.os.Build.VERSION.SDK_INT > 9) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                .permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }
    try {

        URL url = new URL(
                "http://devcms.barcodo.com/Images/ProductImages/ThumbnailImages100/EG-BIRT-ST-JA_th.jpg");
        HttpGet httpRequest = null;

        httpRequest = new HttpGet(url.toURI());

        HttpClient httpclient = new DefaultHttpClient();
        HttpResponse response = (HttpResponse) httpclient
                .execute(httpRequest);

        HttpEntity entity = response.getEntity();
        BufferedHttpEntity b_entity = new BufferedHttpEntity(entity);
        InputStream input = b_entity.getContent();

        bitmap = BitmapFactory.decodeStream(input);

    } catch (URISyntaxException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();

    } catch (MalformedURLException e) {
        Log.e("log", "bad url");
    } catch (IOException e) {
        Log.e("log", "io error");
    }
    setListAdapter(new StudentListAdapter(this));
}

private class StudentListAdapter extends BaseAdapter {
    private Context mContext;
    private String[] mStudents = { "DurgaPrasad", "Raghu", "Vivek",
            "Satish", "Naga Jyothi", "Vardhika", "Nikhil" };
    private String[] mDetailsStudent = { "Details of DurgaPrasad",
            "Details of  Raghu This row is not created using java",
            "Details of Vivek", "Details of Satish",
            "Details of Naga Jyothi", "Details of Vardhika",
            "Details of Nikhil" };

    public StudentListAdapter(Context context) {
        mContext = context;
    }

    public int getCount() {
        return mStudents.length;
    }

    public Object getItem(int position) {
        return position;
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        View v = convertView;
        if (v == null) {
            System.out.println("111111111111 : " + position);
            LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            /*
             * if (position == 0) {
             * System.out.println("111111111111 : "+position); v =
             * vi.inflate(R.layout.studentdetailsrow, null);
             * System.out.println("111111111111 : "+position); } else
             */
            v = vi.inflate(R.layout.list_item, null);
        }

        ImageView iv = (ImageView) v.findViewById(R.id.icon);
        ImageView iv2 = (ImageView) v.findViewById(R.id.icon2);
        if (position == 0) {
            iv.setImageBitmap(bitmap);
            // iv2.setImageResource(R.drawable.icon);
        } else {
            iv.setImageBitmap(bitmap);
            // iv2.setImageResource(R.drawable.icon);
        }

        TextView tvname = (TextView) v.findViewById(R.id.stuname);
        TextView tvdetail = (TextView) v.findViewById(R.id.studetail);
        tvname.setText(mStudents[position]);
        tvdetail.setText(mDetailsStudent[position]);
        return v;
    }

    };
        }

Upvotes: 3

Arda Yigithan Orhan
Arda Yigithan Orhan

Reputation: 1052

Try this library, does exactly what you need. https://github.com/thest1/LazyList

To display images in a listview, you need to create a list adapter class that extends from BaseAdapter and create each view there.

Upvotes: 1

Related Questions