Alberkko619
Alberkko619

Reputation: 39

Getting json data from node js API

I have created an API with nodejs and mongodb, where i can get and set data, however my json array doesn't have a name. I wanted to get that data to my android application and I found this solution online, but it gets the data from an json array called "hits", is there a way I can adjust the code to fit format of database, or can I add a name to my json array so I can use the same solution?

the solution i found

        String url = "https://api.myjson.com/bins/12qqdf";

    JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    try {
                        JSONArray jsonArray = response.getJSONArray("hits");

                        for (int i = 0; i < jsonArray.length(); i++) {
                            JSONObject hit = jsonArray.getJSONObject(i);

                            String address = hit.getString("address");
                            String longi = hit.getString("longitude");
                            String lat = hit.getString("latitude");

                            mExampleList.add(new ExampleItem(address, longi, lat));
                        }

                        mExampleAdapter = new ExampleAdapter(MainActivity.this, mExampleList);
                        mRecyclerView.setAdapter(mExampleAdapter);

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            error.printStackTrace();
        }
    });

    mRequestQueue.add(request);
}

my database format

[  
{  
  "_id":"5d66c8e2b957510ea064ccfa",
  "address":"Rruga - fdff",
  "latitude":34.343232,
  "longitude":12.322736,
  "__v":0
},
{  
  "_id":"5d66c8ebb957510ea064ccfb",
  "address":"Rruga - 111",
  "latitude":34.343232,
  "longitude":12.322736,
  "__v":0
},
{  
  "_id":"5d66c8f8b957510ea064ccfc",
  "address":"Rruga - 222",
  "latitude":32.343232,
  "longitude":22.322736,
  "__v":0
},
{  
  "_id":"5d66cb98c6e86132d46c2fed",
  "address":"Rruga - zzz",
  "latitude":34.343232,
  "longitude":12.322736,
  "__v":0
}
]

Upvotes: 0

Views: 51

Answers (1)

Bali
Bali

Reputation: 759

Based on your JSON change onResponse(JSONObject response) to onResponse(JSONArray jsonArray)

Finally remove below line. It should work

JSONArray jsonArray = response.getJSONArray("hits");

Upvotes: 2

Related Questions