bufferking bufferking - 7 days ago 7
Android Question

i am getting double jsonarray in android to extract and not getting result back

My result image of android app

this is the image of the output i am getting i need to get the value of name. The code i am trying is

JSONArray jsonArray = new JSONArray(result);

JSONObject jsonObject = new JSONObject(jsonArray);

String name = jsonObject.getString("name");


But it isn't working. Can anyone help me regarding this
Thanks alot

This is the backend php code on which i am working on

$aircraftId = filter_input(INPUT_POST, 'aircraftId');
$arr = array();
$stmt = $db->prepare("SELECT * FROM temp WHERE aircraft_id = :aid");
$stmt->execute(array(':aid' => $aircraftId));
$data = $stmt->fetchAll(PDO::FETCH_OBJ);
$x = 0;
foreach ($data as $in)
{
$arr[$x][] = array(
'id' => $data->id,
'name' => $data->name,
'label' => $data->label,
'description' => $data->description,
'type' => $data->type,
'value' => $data->value,
'deliminator' => $data->deliminator,
'deliminator2' => $data->deliminator2,
'title' => $data->title,
'part_number' => $data->part_number,
'serial_number' => $data->serial_number,
'mm' =>$data->mm,
'cost' =>$data->cost,
'category' =>$data->category,
'timeInstall' => $data->timeInstall,
'customType' => $data->customType,
'engineNumber' => $data->engineNumber,
'activateMargin' => $data->activateMargin,
'margin0' => $data->margin0,
'margin1' => $data->margin1,
'margin2' => $data->margin2,
'margin3' => $data->margin3,
'displayField' => $data->displayField,
'tso1' => $data->tso1,
'tso2' => $data->tso2,
'tso3' => $data->tso3,
'tso4' => $data->tso4,
'interval1' => $data->interval1,
'interval2' => $data->interval2,
'interval3' => $data->interval3,
'interval4' => $data->interval4,
'rmg1' => $data->rgm1,
'rmg2' => $data->rmg2,
'rmg3' => $data->rmg3,
'rmg4' => $data->rmg4,
'lcw1' => $data->lcw1,
'lcw2' => $data->lcw2,
'lcw3' => $data->lcw3,
'lcw4' => $data->lcw4
);
$x = $x+1;
}

echo json_encode($arr);

Answer

You are not parsing the response right. Remember "[" shows JSONArray started and in the response you have two [ which means you need to get two JSONArrays before you get JSONObject and eventualy data inside that JSONObject.

Try this

try {
        JSONArray responseArray = new JSONArray(result);
        JSONArray innerArray = responseArray.getJSONArray(0);
        for (int i = 0; i < innerArray.length(); i++) {
            JSONObject jsonObject = innerArray.getJSONObject(i);
            String id = jsonObject.getString("id");
            String name = jsonObject.getString("name");
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

@Tabish's code is even better if you are getting multiple arrays within the first array.