Skip to content Skip to sidebar Skip to footer

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: ListVie

Solution 1:

try the following:

publicclassImageURLextendsListActivity{
        @OverridepublicvoidonCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (android.os.Build.VERSION.SDK_INT > 9) {
        StrictMode.ThreadPolicypolicy=newStrictMode.ThreadPolicy.Builder()
                .permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }
    try {

        URLurl=newURL(
                "http://devcms.barcodo.com/Images/ProductImages/ThumbnailImages100/EG-BIRT-ST-JA_th.jpg");
        HttpGethttpRequest=null;

        httpRequest = newHttpGet(url.toURI());

        HttpClienthttpclient=newDefaultHttpClient();
        HttpResponseresponse= (HttpResponse) httpclient
                .execute(httpRequest);

        HttpEntityentity= response.getEntity();
        BufferedHttpEntityb_entity=newBufferedHttpEntity(entity);
        InputStreaminput= 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(newStudentListAdapter(this));
}

privateclassStudentListAdapterextendsBaseAdapter {
    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" };

    publicStudentListAdapter(Context context) {
        mContext = context;
    }

    publicintgetCount() {
        return mStudents.length;
    }

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

    publiclonggetItemId(int position) {
        return position;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        Viewv= convertView;
        if (v == null) {
            System.out.println("111111111111 : " + position);
            LayoutInflatervi= (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);
        }

        ImageViewiv= (ImageView) v.findViewById(R.id.icon);
        ImageViewiv2= (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);
        }

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

    };
        }

Solution 2:

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.

Solution 3:

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

Solution 4:

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;

@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    initializeAdress();


    list = (ListView) findViewById(R.id.list);
    adapter = newDeliveryListAdapter();
    list.setAdapter(adapter);
    list.setOnItemClickListener(newAdapterView.OnItemClickListener() {
        @OverridepublicvoidonItemClick(AdapterView<?> parent, View view, int position, long id) {


            // getting values from selected ListItemString 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();





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

            in.putExtra("BitmapImage", bitmap);


            startActivity(in);
        }
    });

}


privatevoidinitializeAdress() {
    getNewsFeedListFromServer();

    newsFeedList = newArrayList<FeeStacture>();
}


privatevoidgetNewsFeedListFromServer() {

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

publicclassDeliveryListAdapterextendsBaseAdapter

{

    LayoutInflater minflat;

    publicDeliveryListAdapter() {
        minflat = LayoutInflater.from(getApplicationContext());
    }

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

    @OverridepublicObjectgetItem(int arg0) {
        returnnull;
    }

    @Overridepublic long getItemId(int arg0) {
        return0;
    }


    @OverridepublicViewgetView(int position, View contentView, ViewGroup arg2) {

        ViewHolder holder;

        if (contentView == null) {
            holder = newViewHolder();

            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());
        newDownloadImageTask(holder.image).execute(newsFeedList.get(position).getItemIconStr());

        return contentView;


    }


    publicclassViewHolder {
        // ImageView use;TextView rank;
        TextView pop;
        ImageView image;
        TextView address;
        TextView country;
        TextView gender;
        TextView phone;
    }

}

@OverridepublicvoidonSuccessfullResponse(Objectobject) {
    newsFeedList = (ArrayList<FeeStacture>) object;

    adapter.notifyDataSetChanged();

}

@OverridepublicvoidonErrorResponse(String error) {
    Toast.makeText(getApplicationContext(), error, Toast.LENGTH_SHORT).show();

}

@OverridepublicvoidonNetworkError(String error) {
    Toast.makeText(getApplicationContext(), error, Toast.LENGTH_SHORT).show();

}


@OverridepublicvoidonBackPressed() {
    // TODO Auto-generated method stub//super.onBackPressed();newAlertDialog.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", newDialogInterface.OnClickListener() {
                @OverridepublicvoidonClick(DialogInterface dialog, int which) {
                    finish();

                }

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



privateclassDownloadImageTaskextendsAsyncTask<String, Void, Bitmap> {
    ImageView bmImage;

    publicDownloadImageTask(ImageView bmImage) {
        this.bmImage = bmImage;
    }

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

    protectedvoidonPostExecute(Bitmap result) {
        bmImage.setImageBitmap(result);
    }

}

}

Post a Comment for "Loading Image From Json Url Into Listview"