Question

  1. Marker not properly adding through for loop
  2. When i give i=2 then it's loading 2nd marker otherwise it's just loading single marker
  3. Can you please tell me what could be the reason
JSONObject jsonObject = new JSONObject(result);

            for (int i = 1; i <= jsonObject.length(); i++) {
                jsonObject = jsonObject.getJSONObject(Integer.toString(i));

                Double lat = jsonObject.getDouble("latitude");

                Double lon = jsonObject.getDouble("longitude");

                int sno = jsonObject.getInt("sno");

                Toast.makeText(getBaseContext(), "" + lat + lon + sno,
                        Toast.LENGTH_SHORT).show();

                MarkerOptions marker = new MarkerOptions()
                        .position(new LatLng(lat, lon)).title("New")
                        .snippet("are here");

                googleMap.addMarker(marker);

            }
Was it helpful?

Solution

Problem is your using the same JSONObject variable when trying to get the inner JSONObject. So after the first for loop , the second will try to get the JSONObject from inner JSONObject not from the parent JSONObject.

Declare a new variable for inner JSONObject like this

JSONObject jsonObject = new JSONObject(result);
for (int i = 1; i <= jsonObject.length(); i++) {
   JSONObject jsonInnerObject = jsonObject.getJSONObject(Integer.toString(i));
   Double lat = jsonInnerObject.getDouble("latitude");
   Double lon = jsonInnerObject.getDouble("longitude");
   // Add your other stuff here
}

Another best approach is to Iterate using keys. This doesn't required the index. You can have any value in place of index.

JSONObject jsonObject = new JSONObject(json);
Iterator<Object> iterator = jsonObject.keys();

while (iterator.hasNext()){
 Object obj = iterator.next();
 JSONObject innerJsonObject = jsonObject.getJSONObject(obj.toString());
 if(innerJsonObject != null) {
 Double lat = innerJsonObject.getDouble("latitude");
 Double lon = innerJsonObject.getDouble("longitude");
   // do your other stuff here to add to marker
  }
 }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top