Tuesday, 4 December 2012

Image parsed from JSON using Async & fetched into LISTVIEW

Code for parsing json object , from parsed json object taking image URL, with those URL getting image into bitmap, That bitmap put into arraylist. That arraylist image is then fetched to listview using BaseAdapter.

public class product extends ListActivity implements OnClickListener{
    private GetProduct_Thread doSth;

    protected void onCreate(Bundle savedInstanceState) {
        // running Asynctask
        new GetCategoryProduct_Thread().execute();

        Button shopProductList = (Button)findViewById(R.id.shop_button);

    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.home, menu);
        return true;

    public void onClick(View v) {
        switch (v.getId()) {

        case R.id.home_button:


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

        private Void param;

        protected String doInBackground(String... params) {
            }catch (Exception e) {
                // TODO: handle exception
            return null;

        protected void onPostExecute(String result) {
            setListAdapter(new productListAdapter(this));

    JSONArray Product_jsonarray= null;
    JSONObject jo = new JSONObject();
    private List<? extends NameValuePair> postparams;
    static InputStream is = null;
    static JSONObject jObj = null;
    public static String json;
    // Hashmap for ListView
    ArrayList<HashMap<String, String>> categoryNameList = new ArrayList<HashMap<String, String>>();
    private Bitmap bitmap;
    private ImageView imagy;
    // Arraylist for Bitmap Image
    ArrayList<Bitmap> bitmapArray = new ArrayList<Bitmap>();
    private void sendRequest() {

            URL url1 = new URL(JSON_Url._shopNowURL);
            InputSource is = new InputSource(url1.openStream());
            is.setEncoding("ISO-8859-1"); // Also Try UTF-8 or UTF-16
            BufferedReader br = new BufferedReader(new InputStreamReader(
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = br.readLine()) != null) {
                sb.append(line + "\n");

            json = sb.toString();
            System.out.println("resp -- " + json);

        } catch (UnsupportedEncodingException e) {
        } catch (ClientProtocolException e) {
        } catch (IOException e) {
        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
            System.out.println("jjjj -- " + jObj);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());

        try {
            JSONObject get_string = new JSONObject(jObj.toString());

            JSONObject shownowProduct = get_string.getJSONObject("Products");

            jsonProduct_jsonarray = new JSONArray();

            jsonProduct_jsonarray = shownowProduct.getJSONArray("NowProduct");

            // Receive the JSON object from server
            for (int i = 0; i < jsonProduct_jsonarray.length(); i++) {
                System.out.println("GOT JSON VALUE ");
                JSONObject c = jsonProduct_jsonarray.getJSONObject(i);

                String RetailPrice = c.getString("RetailPrice");
                String  WholeSaleCost = c.getString("WholeSaleCost");
                String  Code = c.getString("Code");
                String  Description = c.getString("Description");
                String   LogoInformation = c.getString("LogoInformation");
                String  ID = c.getString("ID");
                String  Name = c.getString("Name");
                String brandName = c.getString("brandName");
                String  DiscountedPrice = c.getString("DiscountedPrice");
                String  Thumbnail = c.getString("Thumbnail");

                StoredVariable.setProductName(i, Name);
                StoredVariable.setProductRetailPriceId(i, RetailPrice);

            for(int k = 0; k <jsonProduct_jsonarray.length() ; k++)
                try {

                    URL url = new URL(StoredVariable.getImageThumbnail(k));
                    HttpGet httpRequest = null;

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

                    HttpClient httpclient = new DefaultHttpClient();
                    HttpResponse response = (HttpResponse) httpclient

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

                    bitmap = BitmapFactory.decodeStream(input);
                    bitmapArray.add(bitmap); // Add a bitmap
  } catch (URISyntaxException e) {
                    // TODO Auto-generated catch block

                } catch (MalformedURLException e) {
                    Log.e("log", "bad url");
                } catch (IOException e) {
                    Log.e("log", "io error");
        } catch (Exception e) {
            // TODO Auto-generated catch block

    private class productListAdapter extends BaseAdapter {
        public productListAdapter(
                GetCategoryProduct_Thread getCategoryProduct_Thread) {


        public int getCount() {
            return shopProduct_jsonarray.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("position  : " + position);
                LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                v = vi.inflate(R.layout.shop_product_list, null);

            ImageView iv = (ImageView) v.findViewById(R.id.image_view);
            //for(int p = 0;p < get_jsonarray.length();p++)
                if (position == 0) {
                } else {
            TextView tvname = (TextView) v.findViewById(R.id.textView1);
            TextView tvdetail = (TextView) v.findViewById(R.id.textView2);
            TextView tvdetailcost = (TextView) v.findViewById(R.id.textView3);
            return v;


  1. can you post complete source code from xml to java
    .it will be very helpful for me..
    Thank for this post ...very nice

    1. Harish did you got the complete source code for above program ..if you had the full code please share it with me it ll be very much helpful ....thank ou

    2. here my mail id karthick.ccsi@gmail.com

  2. Hi rahul please post the complete source code with xml's.Am struggling with this problem for the past one week


  3. It's interesting that many of the bloggers your tips helped to clarify a few things for me as well as giving... very specific nice content.Android Training institute in chennai with placement | Android Training in chennai

  4. This information is impressive; I am inspired with your post writing style & how continuously you describe this topic. After reading your post, thanks for taking the time to discuss this, I feel happy about it and I love learning more about this topic.Android Training institute in chennai with placement | Best Android Training in velachery

  5. It's exciting that multiple of the bloggers your points supported to clarify a few points for me as entirely as giving... very particular helpful content.
    Java Training in Chennai | Best Android Training in Chennai | Android Training with placement in Chennai | Selenium Training Course in Velachery