0
  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);

            }
2
  • Are you sure you have different LatLng values for your markers? Maybe they are just overlapping Commented Apr 27, 2014 at 12:13
  • @SteveBenett no i have different values only Commented Apr 28, 2014 at 1:07

1 Answer 1

3

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
  }
 }
Sign up to request clarification or add additional context in comments.

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.