0

Here is a sample of my json_encode in PHP:

print(json_encode($row));

leads to {"AverageRating":"4.3"} which is good.

But in Java, I can not seem to grab this 4.3 value. Here it is (for an Android project) I have edited non-relevant data.

 public class Rate extends ListActivity {

   JSONArray jArray;
   String result = null;
   InputStream is = null;
   StringBuilder sb = null;
   String Item, Ratings, Review, starAvg;
   RatingBar ratingsBar;
   ArrayList<NameValuePair> param;

  public void onCreate(Bundle savedInstanceState) {

      starAvg = "0"; // Sets to 0 in case there are no ratings yet.
      new starRatingTask().execute();
      ratingsBar = (RatingBar) findViewById(R.id.theRatingBar);


  class starRatingTask extends AsyncTask<String, String, Void> {

    InputStream is = null;
    String result = "";


    @Override
    protected Void doInBackground(String... params) {
        String url_select = "http://www.---.com/---/average_stars.php";

        ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
        param.add(new BasicNameValuePair("item", Item));


        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url_select);


        try {
            httpPost.setEntity(new UrlEncodedFormEntity(param));
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();

            // read content
            is = httpEntity.getContent();

        } catch (Exception e) {

            Log.e("log_tag", "Error in http connection " + e.toString());
        }
        try {
            BufferedReader br = new BufferedReader(
                    new InputStreamReader(is));
            StringBuilder sb = new StringBuilder();
            String line = "";
            while ((line = br.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            result = sb.toString();

        } catch (Exception e) {

            Log.e("log_tag", "Error converting result " + e.toString());
        }

        return null;

    }

    protected void onPostExecute(Void v) {

        String starAvgTwo = null;
        try {
            jArray = new JSONArray(result);
            JSONObject json_data = null;
            for (int i = 0; i < jArray.length(); i++) {
                json_data = jArray.getJSONObject(i);
                starAvg = json_data.getString("AverageRating");

                   starAvgTwo = starAvg;

            }
        } catch (JSONException e1) {
            Toast.makeText(getBaseContext(), "No Star Ratings!",
                    Toast.LENGTH_LONG).show();
        } catch (ParseException e1) {
            e1.printStackTrace();
        }


                Toast.makeText(getBaseContext(), starAvgTwo,
                        Toast.LENGTH_LONG).show();

        ratingsBar.setRating(Float.valueOf(starAvg));



    }
}

That second toast produces a blank (I assume a "" - empty string?). If I change the toast variable back to starAvg, then it toasts "0".

How can I retrieve the value of 4.3.

6
  • What is inside "result" after you get it from sb.toString()? Commented Jun 22, 2012 at 21:04
  • I toasted result; it is actually shows {"AverageRating":"4.3"} That is very interesting... so it goes back to the JSON parsing section I imagine? Commented Jun 22, 2012 at 21:14
  • 1
    That json describes a JSONObject, not a JSONArray. If it were [{"AverageRating":"4.3"},{"AverageRating":"2.3"},{"AverageRating":"5.0"}] then you'd be working with an array. Commented Jun 22, 2012 at 21:25
  • So does that mean the problem is on the PHP end in how it is encoding? Commented Jun 22, 2012 at 21:29
  • 2
    Well, you should be able to parse it as a JSONObject if you will always be getting it this way, or if you will be getting a list of star ratings, then the PHP side needs to json_encode an array of rows instead of just one. Commented Jun 22, 2012 at 21:37

2 Answers 2

1

As we discussed in the comments on the original question, the PHP is sending down as single JSONObject rather than an array. Parsing as a JSONObject is required in it's present state; however, if you begin sending down an array of your value objects, then you'd use JSONArray to parse it.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, marked you correct since you got to the bottom of it first!
1

I think your JSON doesn't contain array. so just do this:

JSONObject jsonObject = new JSONObject(result); //to convert string to be a JSON object
String averageRating = jsonObject.getString("AverageRating"); //get the value of AverageRating variable

and try toast the averageRating.

and how to get the array from JSON object?

if you have JSON:

{"employees": [
    { "firstName":"John" , "lastName":"Doe" }, 
    { "firstName":"Anna" , "lastName":"Smith" }, 
    { "firstName":"Peter" , "lastName":"Jones" }]
}

then use this code

JSONArray jsonArray = new JSONArray(result);
for (int i = 0; i < jsonArray.length(); i++) {
    JSONObject jsonObject = jsonArray.getJSONObject(i);
    Log.i(Rate.class.getName(), jsonObject.getString("firstName"));
}

that code will produce

John Anna Peter

in your LogCat

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.