Marker is not adding properly while add through fo

2019-09-01 09:27发布

问题:

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

            }

回答1:

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
  }
 }