简体   繁体   中英

how to get ArrayLists from particular JSONObects in android?

I have made an android activity ,In that i am parsing some data from JSON webservice and display it into a ListView ,Now my problem is in my webservice each jsonObject is having Array of strings(image urls),So i dont know how to get each arrayList seperately,I have tried but got all the Arrayvalues into one arrayList,Please help me how to do seperate array per json object in android,my code and webservice is as: webservice link adapter

package com.eps.blancatours.adapter;

import java.util.ArrayList;
import java.util.HashMap;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.eps.blancatours.R;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;

public class DestinationAdapter extends BaseAdapter {
    public ArrayList<HashMap<String, Object>> detArray;

    private Context mContext;
    private DisplayImageOptions options;
    public static ImageLoader imageLoader;

    @SuppressWarnings("deprecation")
    public DestinationAdapter(Context paramContext,
            ArrayList<HashMap<String, Object>> list) {
        this.mContext = paramContext;
        this.detArray = list;

        imageLoader = ImageLoader.getInstance();
        imageLoader.init(ImageLoaderConfiguration.createDefault(paramContext));

        options = new DisplayImageOptions.Builder().cacheOnDisc(true)
                .showStubImage(R.drawable.noimage)
                .showImageOnFail(R.drawable.noimage).build();
        System.out.println(":::::::::::::::mY rESULTANT aRRALYlIST::::::::::::"
                + list);

    }

    public int getCount() {
        return this.detArray.size();
    }

    public Object getItem(int paramInt) {
        return Integer.valueOf(paramInt);
    }

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

    @SuppressWarnings({ "static-access", "unchecked" })
    public View getView(int paramInt, View paramView, ViewGroup paramViewGroup) {
        LayoutInflater localLayoutInflater = (LayoutInflater) this.mContext
                .getSystemService("layout_inflater");
        Viewholder localViewholder = null;
        if (paramView == null) {
            paramView = localLayoutInflater.inflate(R.layout.raw_dest,
                    paramViewGroup, false);
            localViewholder = new Viewholder();

            localViewholder.destImg = ((ImageView) paramView
                    .findViewById(R.id.iv_dest));
            localViewholder.destName = ((TextView) paramView
                    .findViewById(R.id.tv_city));

            paramView.setTag(localViewholder);

        } else {
            localViewholder = new Viewholder();
            localViewholder = (Viewholder) paramView.getTag();
        }
        for (HashMap<String, Object> desti : detArray) {
            System.out.print("Desti id : " + desti.get("id"));
            System.out.print("Desti name : " + desti.get("name"));

            System.out.print("Desti program : " + desti.get("program"));
            System.out.print("Desti program_link : "
                    + desti.get("program_link"));
            System.out.print("Desti images_array size : "
                    + ((ArrayList<String>) desti.get("images_array")).size());
            ArrayList<HashMap<String, Object>> hotels = (ArrayList<HashMap<String, Object>>) desti
                    .get("hotels");
            for (HashMap<String, Object> hotel : hotels) {
                System.out.print("hotel id : " + hotel.get("id"));
                System.out.print("hotel city_id : " + hotel.get("city_id"));
                System.out.print("hotel name : " + hotel.get("name"));
                System.out.print("hotel images_array size : "
                        + ((ArrayList<String>) hotel.get("images_array"))
                                .size());
            }
            localViewholder.destName.setText(detArray.get(paramInt).desti
                    .get("name"));
            imageLoader.displayImage(detArray.get(paramInt).get(0),
                    localViewholder.destImg, options);

            return paramView;

        }
    }

    static class Viewholder {
        ImageView destImg;
        TextView destName;

    }
}

code

ListView lv_dest;
    DestinationAdapter adapter;
    private ProgressDialog pDialog;
    JSONObject destinations = null;
    JSONArray imgArray = null;
    Header hdr;
    JSONArray hotelArray = null;
    Menu menu;
    ArrayList<HashMap<String, String>> destList;
    ArrayList<String> destiList, hotelList, hotel_images;
    String id;
    String name;
    String program;
    String program_link;
    String hotel_id;
    String city_id;
    String hotel_name;
    JSONArray hotel_images_array;
    Intent i;
private class GetDestinations extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Showing progress dialog
            pDialog = new ProgressDialog(DestinationsActivity.this);
            pDialog.setMessage(getResources().getString(R.string.wait));
            pDialog.setCancelable(false);
            pDialog.show();

        }

        @Override
        protected Void doInBackground(Void... arg0) {
            // Creating service handler class instance
            BackendAPIService sh = new BackendAPIService();
            System.out
                    .println("::::::::::::::::::DESTINATIONS URL:::::::>>>>>>>>>"
                            + Const.API_DESTINATIONS);
            // Making a request to url and getting response
            String jsonStr = sh.makeServiceCall(Const.API_DESTINATIONS,
                    BackendAPIService.GET);

            Log.d("Response: ", "> " + jsonStr);

            if (jsonStr != null) {
                try {
                    JSONArray jsonArr = new JSONArray(jsonStr);

                    // Getting JSON Array node
                    // yes

                    // looping through All Contacts
                    for (int i = 0; i < jsonArr.length(); i++) {

                        JSONObject c = jsonArr.getJSONObject(i);
                        id = c.getString("id");
                        name = c.getString("name");
                        program = c.getString("program");
                        program_link = c.getString("program_link");
                        imgArray = c.getJSONArray("images_array");
                        HashMap<String, String> Destimap = new HashMap<String, String>();
                        Destimap.put("id", id);
                        Destimap.put("name", name);
                        Destimap.put("program", program);
                        Destimap.put("program_link", program_link);

                        if (imgArray != null && imgArray.length() != 0) {
                            for (int j = 0; j < imgArray.length(); j++) {
                                destiList.add(imgArray.getString(j));
                                System.out
                                        .println("::::::::::::::::::IMAGE URL:::::::::::::::::"
                                                + imgArray.getString(j));
                            }
                        }
                        hotelArray = c.getJSONArray("hotels");
                        if (hotelArray != null && hotelArray.length() != 0) {
                            for (int k = 0; k < hotelArray.length(); k++) {

                                JSONObject d = hotelArray.getJSONObject(k);
                                hotel_id = d.getString("id");
                                city_id = d.getString("city_id");
                                hotel_name = d.getString("name");

                                Destimap.put("hotel_id", hotel_id);
                                Destimap.put("city_id", city_id);
                                Destimap.put("hotel_name", hotel_name);

                                hotel_images_array = d
                                        .getJSONArray("images_array");

                                if (hotel_images_array != null
                                        && hotel_images_array.length() != 0) {
                                    for (int l = 0; l < hotel_images_array
                                            .length(); l++) {
                                        hotel_images.add(hotel_images_array
                                                .getString(l));
                                    }
                                }

                            }
                        }
                        destList.add(Destimap);

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                Log.e("ServiceHandler", "Couldn't get any data from the url");
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            // Dismiss the progress dialog
            if (pDialog.isShowing())
                pDialog.dismiss();
            /**
             * Updating parsed JSON data into ListView
             * */
            adapter = new DestinationAdapter(DestinationsActivity.this,
                    destList, destiList);
            lv_dest.setAdapter(adapter);
        }

    }

Try this way,hope this will help you to solve your problem.

String jsonStr ="[{\"id\":\"1\",\"name\":\"Bodrum\",\"program\":null,\"program_link\":null,\"images_array\":[\"http:\\/\\/dev.booking.blancatours.com\\/uploads\\/53d1f3fde123b.jpg\",\"http:\\/\\/dev.booking.blancatours.com\\/uploads\\/53d1f3fde20d4.jpg\",\"http:\\/\\/dev.booking.blancatours.com\\/uploads\\/53d1f3fde21c6.jpg\",\"http:\\/\\/dev.booking.blancatours.com\\/uploads\\/53d1f43b43e37.jpg\"],\"hotels\":[{\"id\":\"3\",\"city_id\":\"1\",\"name\":\"Bodrum Hotel\",\"images_array\":[]}]},{\"id\":\"2\",\"name\":\"Bursa\",\"program\":null,\"program_link\":null,\"images_array\":[\"http:\\/\\/dev.booking.blancatours.com\\/uploads\\/53d1f4ff167a8.jpg\",\"http:\\/\\/dev.booking.blancatours.com\\/uploads\\/53d1f4ff168e1.jpg\",\"http:\\/\\/dev.booking.blancatours.com\\/uploads\\/53d1f4ff169cb.jpg\"],\"hotels\":[{\"id\":\"4\",\"city_id\":\"2\",\"name\":\"Bursa Hotel\",\"images_array\":[]}]},{\"id\":\"3\",\"name\":\"Istanbul\",\"program\":null,\"program_link\":null,\"images_array\":[\"http:\\/\\/dev.booking.blancatours.com\\/uploads\\/53d1f5d1927ce.jpg\"],\"hotels\":[{\"id\":\"2\",\"city_id\":\"3\",\"name\":\"Istanbul Hotel\",\"images_array\":[]}]},{\"id\":\"4\",\"name\":\"Bolu\",\"program\":null,\"program_link\":null,\"images_array\":[\"http:\\/\\/dev.booking.blancatours.com\\/uploads\\/53d1f8f500afc.jpg\"],\"hotels\":[]},{\"id\":\"5\",\"name\":\"Trabzon\",\"program\":null,\"program_link\":null,\"images_array\":[],\"hotels\":[]},{\"id\":\"6\",\"name\":\"Yalova\",\"program\":null,\"program_link\":null,\"images_array\":[],\"hotels\":[]},{\"id\":\"7\",\"name\":\"Sapanca\",\"program\":null,\"program_link\":null,\"images_array\":[],\"hotels\":[]},{\"id\":\"8\",\"name\":\"Antalya\",\"program\":null,\"program_link\":null,\"images_array\":[],\"hotels\":[]}]";
try {
     JSONArray jsonArr = new JSONArray(jsonStr);

     ArrayList<HashMap<String,Object>> list = new ArrayList<HashMap<String, Object>>();
     for (int i = 0; i < jsonArr.length(); i++) {
          HashMap<String, Object> destiMap = new HashMap<String, Object>();
          destiMap.put("id", jsonArr.getJSONObject(i).getString("id"));
          destiMap.put("name", jsonArr.getJSONObject(i).getString("name"));
          destiMap.put("program", jsonArr.getJSONObject(i).getString("program"));
          destiMap.put("program_link", jsonArr.getJSONObject(i).getString("program_link"));

          ArrayList<String> images = new ArrayList<String>();
          JSONArray imagesJsonArray = jsonArr.getJSONObject(i).getJSONArray("images_array");
          for(int j=0;j<imagesJsonArray.length();j++){
              images.add(imagesJsonArray.getString(j));
          }
          destiMap.put("images_array", images);

          ArrayList<HashMap<String,Object>> hotels = new ArrayList<HashMap<String,Object>>();
          JSONArray hotelsJsonArray = jsonArr.getJSONObject(i).getJSONArray("hotels");
          for(int j=0;j<hotelsJsonArray.length();j++){
              HashMap<String,Object> hotelMap = new HashMap<String, Object>();
              hotelMap.put("id",hotelsJsonArray.getJSONObject(j).getString("id"));
              hotelMap.put("city_id",hotelsJsonArray.getJSONObject(j).getString("city_id"));
              hotelMap.put("name",hotelsJsonArray.getJSONObject(j).getString("name"));

              ArrayList<String> hotelImages = new ArrayList<String>();
              JSONArray hotelImagesJsonArray = hotelsJsonArray.getJSONObject(j).getJSONArray("images_array");
              for(int k=0;k<hotelImagesJsonArray.length();k++){
                  hotelImages.add(hotelImagesJsonArray.getString(k));
              }
              hotelMap.put("images_array", hotelImages);
              hotels.add(hotelMap);
           }
           destiMap.put("hotels",hotels);
           list.add(destiMap);
      }

      for (HashMap<String,Object> desti : list){
           System.out.print("Desti id : " + desti.get("id"));
           System.out.print("Desti name : " + desti.get("name"));
           System.out.print("Desti program : "+desti.get("program"));
           System.out.print("Desti program_link : " + desti.get("program_link"));
           System.out.print("Desti images_array size : "+((ArrayList<String>)desti.get("images_array")).size());
           ArrayList<HashMap<String,Object>> hotels = (ArrayList<HashMap<String,Object>>) desti.get("hotels");
           for (HashMap<String,Object> hotel : hotels){
                System.out.print("hotel id : " + hotel.get("id"));
                System.out.print("hotel city_id : " + hotel.get("city_id"));
                System.out.print("hotel name : "+hotel.get("name"));
                System.out.print("hotel images_array size : "+((ArrayList<String>)hotel.get("images_array")).size());
           }
      }
} catch (JSONException e) {
      e.printStackTrace();
}


public class DestinationAdapter extends BaseAdapter {
    public ArrayList<HashMap<String, Object>> detArray;
    private Context mContext;
    private DisplayImageOptions options;
    public static ImageLoader imageLoader;

    @SuppressWarnings("deprecation")
    public DestinationAdapter(Context paramContext,ArrayList<HashMap<String, Object>> list) {
        this.mContext = paramContext;
        this.detArray = list;
        imageLoader = ImageLoader.getInstance();
        imageLoader.init(ImageLoaderConfiguration.createDefault(paramContext));
        options = new DisplayImageOptions.Builder().cacheOnDisc(true)
                .showStubImage(R.drawable.noimage)
                .showImageOnFail(R.drawable.noimage).build();
    }

    public int getCount() {
        return detArray.size();
    }

    public Object getItem(int pos) {
        return detArray.get(pos);
    }

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

    public View getView(int position, View view, ViewGroup paramViewGroup) {
        Viewholder holder;
        if (view == null) {
            holder = new Viewholder();
            view = LayoutInflater.from(mContext).inflate(R.layout.raw_dest, paramViewGroup, false);
            holder.destImg = (ImageView) view.findViewById(R.id.iv_dest);
            holder.destName = (TextView) view.findViewById(R.id.tv_city);
            view.setTag(holder);
        } else {
            holder = (Viewholder) view.getTag();
        }
        holder.destName.setText((String)detArray.get(position).get("name"));
        holder.destName.setText((String)detArray.get(position).get("name"));
        ArrayList<String> images = (ArrayList<String>)detArray.get(position).get("images_array");
        if(images!=null && images.size()>0){
            imageLoader.displayImage(images.get(0),holder.destImg, options);
        }
        return view;
    }

    class Viewholder {
        ImageView destImg;
        TextView destName;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM