I am having problems parsing a JSONObject send betweend my Server and the Android Device.
It looks like this:
{ "items":[{"value":"100","longitude":"11.584565599030755","latitude":"48.25420604757366","type":"timer"},{"value":"50","longitude":"11.695457342867675","latitude":"48.34626913462275","type":"rare"},{"value":"1","longitude":"11.6782003186674","latitude":"48.33575480986649","type":"normal"},{"value":"1","longitude":"11.707280558203376","latitude":"48.19109880886268","type":"normal"}], "locations":[{"username":"babine","gender":"female","longitude":"11.670796394348145","latitude":"48.26356506347656"}] }
This is what my device is actually recieving from the server. Now split this up like this:
JSONArray locations= json.getJSONArray("locations");
List<JSONObject> list = new ArrayList<JSONObject>();
for (int i= 0; i < locations.length(); i++) {
list.add(locations.getJSONObject(i));
}
LocationEvent.players = list;
JSONArray items = json.getJSONArray("items");
list.clear();
for (int i= 0; i < items.length(); i++){
list.add(items.getJSONObject(i));
}
Item.items = list;
Where Item.items and LocationEvent.players are from type:
List<\JSONObject>
Later i am creating Overlays for each of those List items like this:
players.clear();
for(JSONObject player: LocationEvent.getAllPlayers()){
UserOverlay user = new UserOverlay(game, player.getString("username"), player.getString("gender"), Double.valueOf(player.getString("latitude")), Double.valueOf(player.getString("longitude")));
players.add(user);
}
items.clear();
for(JSONObject item : Item.getAllItems()){
ItemOverlay itemOv = new ItemOverlay(game, type, Double.valueOf(item.getString("longitude")), Double.valueOf(item.getString("latitude")));
items.add(itemOv);
}
And here is where the JSONException occurs:
org.json.JSONException: No value for username
I am not quite sure what i am doing wrong here...maybe you guys can help me out. If you need more information just let me know. Thanks
The problem is that you're reusing the same list to store the items:
List<JSONObject> list = new ArrayList<JSONObject>();
for (int i= 0; i < locations.length(); i++) {
list.add(locations.getJSONObject(i));
}
LocationEvent.players = list;
Here, Location.players
contains the locations
JSONArray items = json.getJSONArray("items");
list.clear();
But now it doesn't contain anything anymore: you've just cleared it.
for (int i= 0; i < items.length(); i++){
list.add(items.getJSONObject(i));
}
Item.items = list;
And now Location.players
contains the items, just as Item.items
, since both variables reference the same list.