0

I want to fetch json data from json object. My json data is:{"avg":2.5} and my android code is

public class AsyncTaskParseJson extends AsyncTask < String, String, String > {

        final String TAG = "AsyncTaskParseJson.java";

        // set your json string url here
        String yourJsonStringUrl = "http://www.bsservicess.com/photoUpload/star_avg.php?bookName=" + book_name;

        // contacts JSONArray

        @Override
        protected void onPreExecute() {}

        @Override
        protected String doInBackground(String...arg0) {

            try {
                JSONParser jParser = new JSONParser();

                // get json string from url
                JSONObject json = jParser.getJSONFromUrl(yourJsonStringUrl);

                // get the array of users
                JSONObject dataJsonArr = json.getJSONObject(str);

                String c = dataJsonArr.getString("avg");
                na = c;
                starts = Float.parseFloat(c);


            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(String strFromDoInBg) {
            super.onPostExecute(strFromDoInBg);

            netRate.setRating(starts);
            Toast.makeText(mybookview.this, Float.toString(starts), Toast.LENGTH_SHORT).show();
        }

But somehow its not working.I have trie every tutorial and evrything but nothing works.plz help me

michoprogrammer
  • 1,159
  • 2
  • 18
  • 45
Nicky Manali
  • 386
  • 3
  • 22
  • Could you please explain which part doesn' work? Did you tried to enter in debug mode and see what happen in every step? Opening the link you can see a warning in your back end Warning: `Division by zero in /home/mohanmanali9/public_html/photoUpload/star_avg.php on line 30` – michoprogrammer Jul 14 '16 at 07:12
  • actually i dont konw how to fetch data fron json object.I just want to know the method to fetch the data fron json object – Nicky Manali Jul 14 '16 at 07:14
  • First of all you need a model class for mapping your json, then the procedure that you follow is almost correct. [here](http://stackoverflow.com/a/38337023/1222099) you can find a good explanation. – michoprogrammer Jul 14 '16 at 07:19
  • 1
    use Volley library its very simple – karanatwal.github.io Jul 14 '16 at 07:29
  • 1) [Get your string from the server](https://developer.android.com/training/volley/simple.html) 2) [Parse the JSON](http://stackoverflow.com/questions/2591098/how-to-parse-json-in-java) assuming that you are actually getting JSON from the URL – OneCricketeer Jul 14 '16 at 07:31
  • try using retrofit2, you will never bother to think about asynchronous or json parsing anymore :) – Faruk Jul 14 '16 at 07:43

3 Answers3

0

this is for simple get data from url example:

Parse JSON from HttpURLConnection object

and if you want use library then try Volley: tutorial link:

http://www.androidhive.info/2014/05/android-working-with-volley-library-1/

Community
  • 1
  • 1
Jaydeep Devda
  • 727
  • 4
  • 18
0

your getting the json data in response is as {"avg":2.5} simple remove the below code

 JSONObject dataJsonArr = json.getJSONObject(str);

 String c = dataJsonArr.getString("avg");

with below line

String c = json.getString("avg");
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • srry but it giving me an error: Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.getString(java.lang.String)' on a null object reference – Nicky Manali Jul 14 '16 at 07:40
0

A very simple solution to your problem

String str = "{ \"avg\" :0 }";
JsonParser parser = new JsonParser();
JsonObject object = (JsonObject) parser.parse(str);
String value = object.get("avg").getAsString();

But first of all you have to correct the warning in your backend.

EDIT the complete solution

public class AsyncTaskParseJson extends AsyncTask < String, String, String > {

    HttpURLConnection urlConnection;

    @Override
    protected String doInBackground(String...args) {

        StringBuilder result = new StringBuilder();

        try {
            URL url = new URL("http://www.bsservicess.com/photoUpload/star_avg.php?bookName=" + book_name);
            urlConnection = (HttpURLConnection) url.openConnection();
            InputStream in = new BufferedInputStream(urlConnection.getInputStream());

            BufferedReader reader = new BufferedReader(new InputStreamReader( in ));

            String line;
            while ((line = reader.readLine()) != null) {
                result.append(line);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            urlConnection.disconnect();
        }

        return result.toString();
    }

    @Override
    protected void onPostExecute(String result) {
        JsonParser parser = new JsonParser();
        JsonObject object = (JsonObject) parser.parse(result);
        String value = object.get("avg").getAsString();
    }

}

But first of all remove the warning from the web response!

michoprogrammer
  • 1,159
  • 2
  • 18
  • 45
  • That's not getting the json from a web request – OneCricketeer Jul 14 '16 at 07:27
  • @cricket_007 the problem of Nicky is not about getting the data from a web request, because the logic of the asynctask is correct, the problem is in parsing the data. So this solution fits perfect in his needs. – michoprogrammer Jul 14 '16 at 07:28
  • How do you know the logic is correct without seeing the response or the implementation of `jParser.getJSONFromUrl(yourJsonStringUrl);`? – OneCricketeer Jul 14 '16 at 07:32
  • The logic of the asynctask is correct, the parsing phase is wrong. How do you know this? Because I tried to open the url by myself with the same code and I fixed it before posting the solution. And I decided to post only the json part because the rest it works properly. Of course Nicky has to change the "str" that I have hard coded for the sake of simplicity. – michoprogrammer Jul 14 '16 at 07:36
  • but in this way im not using url so how did i get json object – Nicky Manali Jul 14 '16 at 07:43
  • JSONObject object = (JSONObject ) parser.parse(result); cannot resolve the method parser.parse(result) what should i do now – Nicky Manali Jul 14 '16 at 07:58
  • Did you import the gson library? Because I test the code that I wrote for you and it works properly. – michoprogrammer Jul 14 '16 at 08:12
  • Use: JSONObject response = new JSONObject(result); String m = response.optString("avg"); Inside your onPostExecute method instead of JsonParser – Ravi Rawal Jul 14 '16 at 08:39