1

In my android app, I get a json value and iterate through them by doing this

    if (response != null) {
        try {
            JSONObject object = new JSONObject(response);
            Iterator enu = object.keys();
            ArrayList<String> locationList = new ArrayList<String>();
            while(enu.hasNext()) {
                locationList.add(object.getString((String) enu.next()));
            }
            callerContext.DisplayLocations(locationList);
        } catch (JSONException e) {
            Toast.makeText(callerContext, callerContext.getResources().getString(R.string.error_message), Toast.LENGTH_LONG).show();
        }
    }

The problem is the ArrayList if I then iterate through that, the values are in a different order then when I insert then in the php code...

How do I loop through the json object in the same order as when they were inserted?

Thanks.

EDIT:

PHP

            $data = array();
            for ($i = 0; $i < $num_records; $i++) {

                array_push($data, 
                    array("id{$i}" => mysql_result($recordset, $i, 'id')), 
                    array("location{$i}" => mysql_result($recordset, $i, 'location')), 
                    array("date{$i}" => mysql_result($recordset, $i, 'date added'))
                );
            }
sneaky
  • 2,141
  • 9
  • 31
  • 38
  • There *is* no order. You have a JSON object with fields, not an array. – Brian Roach Jul 27 '13 at 19:57
  • What are the values that you are trying to add to the ArrayList? Are you only trying to add just the `location`, or are you trying to add the `id`, `location`, and `data` for each record? – btse Jul 27 '13 at 22:15

3 Answers3

2

JSON Objects do not have or guarantee an order, use a JSON Array instead if this is needed.

Suau
  • 4,628
  • 22
  • 28
  • When I change it to JSON Array, i get an error saying that string cannot be converted to a JSON array... – sneaky Jul 27 '13 at 19:53
  • no, i mean your php should generate a json Array in the first place if you need a specific order – Suau Jul 27 '13 at 19:56
  • how do you create the array in php? – sneaky Jul 27 '13 at 20:55
  • first you should be clear about what you want to do then figure out how your data should be structured and then start writing code. could you tell us more about what you want to achieve ? – Suau Jul 28 '13 at 08:18
0

Your Php code seems fine. U need to change ur Java end. Try this:

BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()))
StringBuilder content = new StringBuilder();

String line;
while (null != (line = br.readLine()) {
   content.append(line);
}
Object obj=JSONValue.parse(content.toString());
JSONArray jArray=(JSONArray)obj;

//test the order
System.out.println(jArray);

// u may iterate it like this:
for (int i = 0; i < jArray.length(); i++) {
    JSONObject row = jArray.getJSONObject(i);
    // do stuff with all rows now for example:
    String location = row.getString("location");
}

Refer to these two Stackoverflow posts: JSON Array iteration in Android/Java and Parsing a JSON Array from HTTP Response in Java

Community
  • 1
  • 1
Jazib
  • 1,200
  • 1
  • 16
  • 39
0

I was unsure of which values you were attempting to add to add to LocationList. Looking at your code, it seems like you are adding the values for id, location, and date to the LocationList, and you want to achieve this in the same order that you add them in your php. If this is not correct, please let me know and I will update my answer accordingly. Anyways, this should add everything in order:

PHP code:

$data = array();
for ($i = 0; $i < $num_records; $i++) {

    array_push($data, 
        array("id{$i}" => mysql_result($recordset, $i, 'id')), 
        array("location{$i}" => mysql_result($recordset, $i, 'location')), 
        array("date{$i}" => mysql_result($recordset, $i, 'date added'))
    );
}

// This is what I added. Creates a JSON array.
$jsonArray = json_encode($data);

// Then do whatever you want with $jsonArray, perhaps echo it?

Java Code:

if (response != null) {
    try {
        ArrayList<String> locationList = new ArrayList<String>();
        JSONArray dataArray = new JSONArray(response);
        int length = dataArray.length();

        for (int i = 0; i < length; i++) {
            JSONObject json = dataArray.get(i);
            Iterator enu = json.keys();

            // No need for a loop since JSONObject should only have one key => value pair
            locationList.add(json.getString((String) enu.next()));
        }

        callerContext.DisplayLocations(locationList);
    } catch (JSONException e) {
        Toast.makeText(callerContext, callerContext.getResources().getString(R.string.error_message), Toast.LENGTH_LONG).show();
    }
}
btse
  • 7,811
  • 3
  • 25
  • 30