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;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.shop_product);
        // running Asynctask
        new GetCategoryProduct_Thread().execute();

        Button shopProductList = (Button)findViewById(R.id.shop_button);
        shopProductList.setOnClickListener(this);
       
    }


    @Override
    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:
            finish();
            break;
        default:
            break;
        }

    }


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

        private Void param;

        @Override
        protected String doInBackground(String... params) {
            try{
                sendRequest();
            }catch (Exception e) {
                // TODO: handle exception
            }
            publishProgress(param);
            return null;
        }

        protected void onPostExecute(String result) {
            super.onPostExecute(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() {

        try{      
            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(
                    is.getByteStream()));
            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) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 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);
                StoredVariable.setSaleCost(i,WholeSaleCost);
                StoredVariable.setImageThumbnail(i,Thumbnail);
            }

            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
                            .execute(httpRequest);

                    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
                    e.printStackTrace();

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



    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) {
                    iv.setImageBitmap(bitmapArray.get(position));
                } else {
                    iv.setImageBitmap(bitmapArray.get(position));
                }
            }
            TextView tvname = (TextView) v.findViewById(R.id.textView1);
            TextView tvdetail = (TextView) v.findViewById(R.id.textView2);
            TextView tvdetailcost = (TextView) v.findViewById(R.id.textView3);
            tvname.setText(StoredVariable.getName(position));
            tvdetail.setText(StoredVariable.getRetailPrice(position));
            tvdetailcost.setText(StoredVariable.getWholeSaleCost(position));
            return v;
        }
    };
}

7 comments:

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

    ReplyDelete
    Replies
    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

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

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

    ReplyDelete

  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

    ReplyDelete
  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

    ReplyDelete
  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

    ReplyDelete