Question

I try to put JSONObject values on a JSONArray on a "for" instruction and with the first value group it works correctly, but when I add the second value group I see that the first values are override too. I put the code and an examepl to explain it better.

JSONArray jsPoints = new JSONArray();
JSONObject js = new JSONObject();
for(int i = 0; i < points.length; i++)
{                               
    try 
    {
       js.put("id",points[i]._id);
       js.put("calification",points[i]._calification);
       js.put("comment",points[i]._comment);
       js.put("gps",points[i]._coords);
       js.put("X",points[i]._X);
       js.put("Y",points[i]._Y);
    } 
    catch (JSONException e) 
    {                               
       e.printStackTrace();
    }
    jsPoints.put(js);
}

I have, for example, this value gruops:

On i = 0:

id: 1 - calification: 0 - comment: "hi" - gps: 0 - X: 220 - Y: 110

On i = 1;

id: 2 - calification: 2 - comment: "hello" - gps: 40.324 - X: 10 - Y: 52

When I put the first values (i = 0), I added on jsPoints correctly, but when I put the second values (i = 1) the first values are override by the second one, how can I solve this problem? Thanks!

Was it helpful?

Solution

JSONArray jsPoints = new JSONArray();

for(int i = 0; i < points.length; i++)
{       
 JSONObject js = null;

try 
{
   js = new JSONObject();  
   js.put("id",points[i]._id);
   js.put("calification",points[i]._calification);
   js.put("comment",points[i]._comment);
   js.put("gps",points[i]._coords);
   js.put("X",points[i]._X);
   js.put("Y",points[i]._Y);
} 
catch (JSONException e) 
{                               
   e.printStackTrace();
}
  if(js!=null)
    jsPoints.put(js);

}

OTHER TIPS

 try 
{
 JSONObject js = new JSONObject();

JSONArray jsPoints = new JSONArray();

for(int i = 0; i < jsPoints.length; i++)
 {                               

   js.put("id",points[i]._id);
   js.put("calification",points[i]._calification);
   js.put("comment",points[i]._comment);
   js.put("gps",points[i]._coords);
   js.put("X",points[i]._X);
   js.put("Y",points[i]._Y);
} 
catch (JSONException e) 
{                               
   e.printStackTrace();
}
jsPoints.put(js);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top