Does not display incoming data with response

3445 views android
1

I am writing an application for android and using the volley library. I need to write the received data into TextResult. How to do it?

private void jsonParse() {
        String url = "https://api.apixu.com/v1/current.json?key=...&q=Paris";
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            JSONArray jsonArray = response.getJSONArray("location");
                            for (int i = 0; i < jsonArray.length(); i++) {
                                JSONObject location = jsonArray.getJSONObject(i);
                                String name = location.getString("name");
                                String region = location.getString("region");
                                String country = location.getString("country");
                                TextResult.append(name + ", " + region + ", " + country + "\n\n");
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
            }
        });
        mQueue.add(request);
    }

Json response example

{"location":{"name":"Paris","region":"Ile-de-France","country":"France"}}

answered question

what error are you getting?

2 Answers

4

{"location":{"name":"Paris","region":"Ile-de-France","country":"France"}}

Its not a JSONArray its a JSONObject.

First get the location from JSONObject.

String location_value=response.get("location");

JSONObject location=new JSONObject(location_value);

String name = location.getString("name");
String region = location.getString("region");
String country = location.getString("country");

TextResult.append(name + ", " + region + ", " + country + "\n\n");

posted this
2

Use this piece of code.

@Override
    public void onResponse(JSONObject response) {
        try {
            JSONObject jsonObject = response.getJSONObject("location");

            for (int i = 0; i < jsonArray.length(); i++) {
                JSONArray location = jsonObject.getJSONArray(i);
                String name = location.getString("name");
                String region = location.getString("region");
                String country = location.getString("country");
                TextResult.append(name + ", " + region + ", " + country + "\n\n");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

posted this

Have an answer?

JD

Please login first before posting an answer.