Retrieving Json Array

4

I am trying to retrieve the values from the following url: http://rentopoly.com/ajax.php?query=Bo. I want to get the values of all the suggestions to be displayed in a list view one by one. This is how i want to do...

public class AlertsAdd {
 public ArrayList <JSONObject> retrieveJSONArray(String urlString) {
  String result = queryRESTurl(urlString);
  ArrayList <JSONObject> ALERTS = new ArrayList <JSONObject> ();
  if (result != null) {

   try {
    JSONObject json = new JSONObject(result);
    JSONArray alertsArray = json.getJSONArray("suggestions");
    for (int a = 0; a < alertsArray.length(); a++) {
     JSONObject alertitem = alertsArray.getJSONObject(a);
     ALERTS.add(alertitem);
    }
    return ALERTS;
   } catch (JSONException e) {
    Log.e("JSON", "There was an error parsing the JSON", e);
   }
  }
  JSONObject myObject = new JSONObject();
  try {
   myObject.put("suggestions", myObject.getJSONArray("suggestions"));
   ALERTS.add(myObject);
  } catch (JSONException e1) {
   Log.e("JSON", "There was an error creating the JSONObject", e1);
  }
  return ALERTS;
 }
 private String queryRESTurl(String url) {
  // URLConnection connection;
  HttpClient httpclient = new DefaultHttpClient();
  HttpGet httpget = new HttpGet(url);
  HttpResponse response;
  try {
   response = httpclient.execute(httpget);
   HttpEntity entity = response.getEntity();
   if (entity != null) {
    InputStream instream = entity.getContent();
    String result = convertStreamToString(instream);
    instream.close();
    return result;
   }
  } catch (ClientProtocolException e) {
   Log.e("REST", "There was a protocol based error", e);
  } catch (IOException e) {
   Log.e("REST", "There was an IO Stream related error", e);
  }
  return null;
 }

 /**
  * To convert the InputStream to String we use the
  * BufferedReader.readLine() method. We iterate until the BufferedReader
  * return null which means there's no more data to read. Each line will
  * appended to a StringBuilder and returned as String.
  */
 private String convertStreamToString(InputStream is) {
  BufferedReader reader = new BufferedReader(new InputStreamReader(is));
  StringBuilder sb = new StringBuilder();

  String line = null;
  try {
   while ((line = reader.readLine()) != null) {
    sb.append(line + "\n");
   }
  } catch (IOException e) {
   e.printStackTrace();
  } finally {
   try {
    is.close();
   } catch (IOException e) {
    e.printStackTrace();
   }
  }
  return sb.toString();
 }
}

Here's the adapter code...

public class AlertsAdapter extends ArrayAdapter <JSONObject> {
 public AlertsAdapter(Activity activity, List <JSONObject> alerts) {
  super(activity, 0, alerts);
 }
 @Override
 public View getView(int position, View convertView, ViewGroup parent) {
  Activity activity = (Activity) getContext();
  LayoutInflater inflater = activity.getLayoutInflater();
  View rowView = inflater.inflate(R.layout.list_text, null);
  JSONObject imageAndText = getItem(position);
  TextView textView = (TextView) rowView.findViewById(R.id.last_build_stat);
  try {
   textView.setText((String) imageAndText.get("suggestions"));
  } catch (JSONException e) {
   textView.setText("JSON Exception");
  }
  return rowView;
 }
}

Here's the logcat...

    04-30 13:09:46.656: INFO/ActivityManager(584): Starting activity: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10000000 cmp=com.WorldToyota/.Alerts }
04-30 13:09:50.417: ERROR/JSON(924): There was an error parsing the JSON
04-30 13:09:50.417: ERROR/JSON(924): org.json.JSONException: JSONArray[0] is not a JSONObject.
04-30 13:09:50.417: ERROR/JSON(924):     at org.json.JSONArray.getJSONObject(JSONArray.java:268)
04-30 13:09:50.417: ERROR/JSON(924):     at com.WorldToyota.AlertsAdd.retrieveJSONArray(AlertsAdd.java:30)
04-30 13:09:50.417: ERROR/JSON(924):     at com.WorldToyota.Alerts.onCreate(Alerts.java:20)
04-30 13:09:50.417: ERROR/JSON(924):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1123)
04-30 13:09:50.417: ERROR/JSON(924):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2364)
04-30 13:09:50.417: ERROR/JSON(924):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2417)
04-30 13:09:50.417: ERROR/JSON(924):     at android.app.ActivityThread.access$2100(ActivityThread.java:116)
04-30 13:09:50.417: ERROR/JSON(924):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1794)
04-30 13:09:50.417: ERROR/JSON(924):     at android.os.Handler.dispatchMessage(Handler.java:99)
04-30 13:09:50.417: ERROR/JSON(924):     at android.os.Looper.loop(Looper.java:123)
04-30 13:09:50.417: ERROR/JSON(924):     at android.app.ActivityThread.main(ActivityThread.java:4203)
04-30 13:09:50.417: ERROR/JSON(924):     at java.lang.reflect.Method.invokeNative(Native Method)
04-30 13:09:50.417: ERROR/JSON(924):     at java.lang.reflect.Method.invoke(Method.java:521)
04-30 13:09:50.417: ERROR/JSON(924):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791)
04-30 13:09:50.417: ERROR/JSON(924):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:549)
04-30 13:09:50.417: ERROR/JSON(924):     at dalvik.system.NativeStart.main(Native Method)
04-30 13:09:50.688: ERROR/JSON(924): There was an error creating the JSONObject
04-30 13:09:50.688: ERROR/JSON(924): org.json.JSONException: JSONObject["suggestions"] not found.
04-30 13:09:50.688: ERROR/JSON(924):     at org.json.JSONObject.get(JSONObject.java:287)
04-30 13:09:50.688: ERROR/JSON(924):     at org.json.JSONObject.getJSONArray(JSONObject.java:362)
04-30 13:09:50.688: ERROR/JSON(924):     at com.WorldToyota.AlertsAdd.retrieveJSONArray(AlertsAdd.java:41)
04-30 13:09:50.688: ERROR/JSON(924):     at com.WorldToyota.Alerts.onCreate(Alerts.java:20)
04-30 13:09:50.688: ERROR/JSON(924):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1123)
04-30 13:09:50.688: ERROR/JSON(924):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2364)
04-30 13:09:50.688: ERROR/JSON(924):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2417)
04-30 13:09:50.688: ERROR/JSON(924):     at android.app.ActivityThread.access$2100(ActivityThread.java:116)
04-30 13:09:50.688: ERROR/JSON(924):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1794)
04-30 13:09:50.688: ERROR/JSON(924):     at android.os.Handler.dispatchMessage(Handler.java:99)
04-30 13:09:50.688: ERROR/JSON(924):     at android.os.Looper.loop(Looper.java:123)
04-30 13:09:50.688: ERROR/JSON(924):     at android.app.ActivityThread.main(ActivityThread.java:4203)
04-30 13:09:50.688: ERROR/JSON(924):     at java.lang.reflect.Method.invokeNative(Native Method)
04-30 13:09:50.688: ERROR/JSON(924):     at java.lang.reflect.Method.invoke(Method.java:521)
04-30 13:09:50.688: ERROR/JSON(924):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791)
04-30 13:09:50.688: ERROR/JSON(924):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:549)
04-30 13:09:50.688: ERROR/JSON(924):     at dalvik.system.NativeStart.main(Native Method)

Plz help me parsing this script and displaying the values in list format....

android
json
asked on Stack Overflow Apr 30, 2010 by Rahul Varma • edited Jan 6, 2020 by Mickael Lherminez

4 Answers

4

check out this example - uses the same service you are trying to access and is also based on Android.

http://damonsk.com/2010/01/jsonarray-httpclient-android/

answered on Stack Overflow May 10, 2010 by Damon Skelhorn
1

You need to get the JSONArray first from the string that you got. And then access the particular object. Here is the code that you can use to get the suggestions array :

String result = queryRESTurl(urlString);
JSONArray array =  new JSONArray( result );

JSONObject object = array.getJSONObject( 0 ); JSONArray alertsArray = object.getJSONArray( "suggestions" );

answered on Stack Overflow Apr 30, 2010 by Karan
0

Looking at the JSON object:

{
"query": "Bo",
"suggestions": ["Bognor Regis", "Bolton",  ... ]
}

It looks to me that suggestions[0] isn't a JSONObject ("an unordered collection of name/value pairs"), hence the error. It is a plain String. Try:

String alertitem = alertsArray.getString(a);
answered on Stack Overflow Apr 30, 2010 by seanhodges
0
        public static ArrayList<Sport_Teamdetail_dto> getSport_TeamDetail(String id) {

            ArrayList<Sport_Teamdetail_dto> fetchSport_TeamDetail = new ArrayList<Sport_Teamdetail_dto>();
            String result = "";
            InputStream is = null;

            ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("id", id));


            try {
                // http post
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(url + "fetch_allsportdata.php?");
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                is = entity.getContent();

               // http Get
                HttpClient httpclient = new DefaultHttpClient();
                HttpResponse httpResponse = httpclient.execute(new HttpGet(url));
                is = httpResponse.getEntity().getContent();


            } catch (Exception e) {
                Log.e("log_tag", "Error in http connection " + e.toString());
            }
            // convert response to string
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(
                        is, "iso-8859-1"), 8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
                is.close();
                result = sb.toString();
            } catch (Exception e) {
                Log.e("log_tag", "Error converting result " + e.toString());
            }

            // parse json data
            try {
                JSONObject json_obj = new JSONObject(result);
                JSONArray j_Arr_sco_id = json_obj.getJSONArray("scid");
                JSONArray j_Arr_tn = json_obj.getJSONArray("Teamname");
                JSONArray j_Arr_vn = json_obj.getJSONArray("Venuename");
                JSONArray j_Arr_cenr = json_obj.getJSONArray("Centerreference");
                JSONArray j_Arr_ref1 = json_obj.getJSONArray("Referee1");
                JSONArray j_Arr_ref2 = json_obj.getJSONArray("Referee2");

                for (int i = 0; i < j_Arr_tn.length(); i++) {
                    Sport_Teamdetail_dto sportteamdto = new Sport_Teamdetail_dto();
                    sportteamdto.sport_scocer_id = j_Arr_sco_id.getString(i);
                    sportteamdto.sports_team_teamname = j_Arr_tn.getString(i);
                    sportteamdto.sports_venue_name_all = j_Arr_vn.getString(i);
                    sportteamdto.sports_centerreff_name_teamnm = j_Arr_cenr
                            .getDouble(i);
                    sportteamdto.sports_ref1_name_team_nm = j_Arr_ref1.getDouble(i);
                    sportteamdto.sports_ref2_name_teamnm = j_Arr_ref2.getDouble(i);

                    fetchSport_TeamDetail.add(sportteamdto);

                }

            } catch (JSONException e) {
                Log.e("log_tag", "Error parsing data " + e.toString());
            }
            return fetchSport_TeamDetail;

        }


   public class ItemListAdapterFindStore extends ArrayAdapter<ComanWord> {
        Context context1;
        private HashMap<Integer, Boolean> mSelection = new HashMap<Integer, Boolean>();

        /**
         * Constructor from a list of items
         */
        public ItemListAdapterFindStore(Context context, ArrayList<ComanWord> items) {
            super(context, 0, items);
            li = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            context1 = context;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            // The item we want to get the view for
            // --
            final ComanWord item = getItem(position);

            // Re-use the view if possible
            // --
            final ViewHolder holder;
            if (convertView == null) {
                convertView = li.inflate(R.layout.list_item_card, null);
                holder = new ViewHolder(convertView);
                convertView.setTag(R.id.holder, holder);
            } else {
                holder = (ViewHolder) convertView.getTag(R.id.holder);
            }

            holder.m_text1.setText(item.getEnglish());
            holder.m_text2.setText(item.getHindi());

            if (item.getGujarati() != null && item.getGujarati() != "") {
                holder.m_text3.setText(item.getGujarati());
            }


            if(item.getFavflag() ==0){
                holder.img_audio1.setImageResource(R.drawable.apptheme_rate_star_small_off_holo_light);
            }else{
                holder.img_audio1.setImageResource(R.drawable.apptheme_rate_star_small_on_holo_light);
            }

            RelativeLayout rel = (RelativeLayout) convertView
                    .findViewById(R.id.rel_box);
            // rel.setBackgroundColor(v.getResources().getColor(R.color.bacground));
            if (mSelection.get(position) != null) {

                rel.setBackgroundColor(convertView.getResources().getColor(
                        R.color.actionbarcolor1));// this is a selected position so
                                                    // make it red
            } else {
                rel.setBackgroundColor(convertView.getResources().getColor(
                        R.color.white));
            }

            holder.img.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    Log.i("fb", "AMIT::" + item.getEnglish().toString());
                    PlanetFragment.speakOut(item.getEnglish().toString());
                }
            });

            holder.img_audio1.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {

                    if(item.getFavflag() ==0){
                        holder.img_audio1.setImageResource(R.drawable.apptheme_rate_star_small_on_holo_light);
                    }else{
                        holder.img_audio1.setImageResource(R.drawable.apptheme_rate_star_small_off_holo_light);
                    }
                    PlanetFragment.test(position);



                }
            });

            return convertView;
        }

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

        @Override
        public boolean hasStableIds() {
            return true;
        }

        private LayoutInflater li;

        private static class ViewHolder {
            public ViewHolder(View m_rootView) {
                m_text1 = (TextView) m_rootView.findViewById(R.id.text1);
                m_text2 = (TextView) m_rootView.findViewById(R.id.text2);
                m_text3 = (TextView) m_rootView.findViewById(R.id.text3);
                img = (ImageView) m_rootView.findViewById(R.id.img_audio);

                img_audio1 = (ImageView) m_rootView.findViewById(R.id.img_audio1);
                m_text2.setTypeface(MainActivity.fonth);
                m_text3.setTypeface(MainActivity.fontg);
            }

            private TextView m_text1;
            private TextView m_text2;
            private TextView m_text3;
            private ImageView img, img_audio1;

        }

        public void setNewSelection(int position, boolean value) {
            mSelection.put(position, value);
            notifyDataSetChanged();
        }

        public boolean isPositionChecked(int position) {
            Boolean result = mSelection.get(position);
            return result == null ? false : result;
        }

        public Set<Integer> getCurrentCheckedPosition() {
            return mSelection.keySet();
        }

        public void removeSelection(int position) {
            CommonWordApp.words = "";
            mSelection.remove(position);
            notifyDataSetChanged();
        }

        public void clearSelection() {
            CommonWordApp.words = "";
            mSelection = new HashMap<Integer, Boolean>();
            notifyDataSetChanged();
        }
    }
answered on Stack Overflow Dec 3, 2012 by Amit Prajapati • edited Feb 25, 2016 by Amit Prajapati

User contributions licensed under CC BY-SA 3.0