简体   繁体   中英

Null display when parsing json from php to android

here is my php code

$titikPetaInti = array();
while($row = mysql_fetch_assoc($hasil2))
{
     $titikPetaInti[] = $row['koordinat'];
}

$data = "{titikPeta:".json_encode($titikPetaInti)."}";
echo $data;
?>

then here is my android code xResultTitikPeta is result request to php

jObject = new JSONObject(xResultTitikPeta);
        JSONArray myArray1 = (JSONArray) jObject.getJSONArray("titikPeta");
        String[]titikPeta = new String[myArray1.length()];

        for(int a = 0; a < myArray1.length(); a++)
        {
            titikPeta[a] = myArray1.getJSONObject(a).toString();
        }
        teks1 = (TextView) findViewById(R.id.textView1);
        teks1.setText(Arrays.toString(titikPeta));

it displaying null at emulator like no value

--EDIT--

i think there something mistake in parsing code, cus when i display the xResultTitikPeta in android, it give me string result

here is result of xResultTitikPeta

{titikPeta:["-8.705378,115.225189","-8.56056700000000,115.42395100000","-8.57659700000000,115.40065300000","-8.55596300000000,115.41085700000","-8.51855200000000,115.491908000000","-8.54743200000000,115.41036800000","-8.56551100000000,115.45173900000","-8.44321000000000,115.616019000000"]}

this is malformed JSON! no double quotes on key.

$data = "{titikPeta:".json_encode($titikPetaInti)."}";

instead do:

$data = '{"titikPeta":'.json_encode($titikPetaInti).'}';

EDITED:

Ok, remove that hand made approach:

$data = json_encode(array("titikPeta"=>$titikPetaInti));

尝试

$data = "{\"titikPeta\":".json_encode($titikPetaInti)."}";

OK, I've found your bug! As well as fixing the $data = json_encode(array("titikPeta" => $titikPetaInti)); issue, the problem is here:

titikPeta[a] = myArray1.getJSONObject(a).toString();

The elements of myArray1 are actually of type string and cause an exception to be thrown, so you need instead:

titikPeta[a] = myArray1.getString(a);

This produces the output of:

[-8.705378,115.225189, -8.56056700000000,115.42395100000, -8.57659700000000,115.40065300000, -8.55596300000000,115.41085700000, -8.51855200000000,115.491908000000, -8.54743200000000,115.41036800000, -8.56551100000000,115.45173900000, -8.44321000000000,115.616019000000]

As each element in your array is of the form "-8.705378,115.225189" , the JSON parser assumes they are strings. If you change the elements to "-8.705378","115.225189" you can also use:

titikPeta[a] = Double.toString(myArray1.getDouble(a));

However, the first version will work too.

Note: my personal preference is that I would declare each array element as:

{"x":-8.705378,"y":115.225189}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM