我正在嘗試使用android和php json,我嘗試獲取像這樣的東西,它是如何在示例中顯示的。示例json respone是:{「android」:[{「ver」:「1.5」,「name」:「Cupcake」,「api」:「API level 3」},{「ver」:「 1.6「,」name「:」Donut「,」api「:」API level 4「}]}getJSONObject與數組
and my json respone is: [{」post_id「:」3「,」user_id「:」1 「 」post_inhalt「: 」羅立「, 」喜歡「: 」1「},{ 」POST_ID「: 」4「, 」USER_ID「: 」1「, 」post_inhalt「: 」拉拉「, 」喜歡「:」 2 「}]
ther是我的問題,我想要一個數組的對象;
我的php代碼看起來像這樣。
<?php
$con=mysqli_connect("localhost","root","","my_db");
//echo "Welcome, I am connecting Android to PHP, MySQL";
if (mysqli_connect_errno($con))
{
//echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$user_id = "1";
//Für die Überprüfung
$result = mysqli_query($con, "SELECT * FROM post where user_id='$user_id'");
$response = array();
// fetch data in array format
while ($row = mysqli_fetch_array($result, MYSQL_ASSOC)) {
//$response["code"] = 1;
// Fetch data of Fname Column and store in array of row_array
/*
$row_array["post"]['post_id'] = $row['post_id'];
$row_array["post"]['user_id'] = $row['user_id'];
$row_array["post"]['post_inhalt'] = $row['post_inhalt'];
$row_array["post"]['likes'] = $row['likes'];
*/
$row_array['post_id'] = $row['post_id'];
$row_array['user_id'] = $row['user_id'];
$row_array['post_inhalt'] = $row['post_inhalt'];
$row_array['likes'] = $row['likes'];
//push the values in the array
array_push($response,$row_array);
}
print json_encode($response);
mysqli_close($con);
?>
我希望把這個在我的Android列表視圖,但每次我跑我的應用程序,錯誤: 「org.json.JSONArray org.json.JSONObject.getJSONArray(java.lang.String中)」在空對象參考
因爲我認爲數據不能從我的android找到。我不是最好的機器人,所以也許有人可以幫助我。
這裏是我的我的PHP代碼更新:
//while ($row = mysqli_fetch_array($result, MYSQL_ASSOC)) {
if(mysqli_num_rows($result) > 0) {
$row = mysqli_fetch_array($result);
//$response["code"] = 1;
// Fetch data of Fname Column and store in array of row_array
/*
$row_array["post"]['post_id'] = $row['post_id'];
$row_array["post"]['user_id'] = $row['user_id'];
$row_array["post"]['post_inhalt'] = $row['post_inhalt'];
$row_array["post"]['likes'] = $row['likes'];
*/
//$row_array = array();
$row_array['post_id'] = $row['post_id'];
$row_array['user_id'] = $row['user_id'];
$row_array['post_inhalt'] = $row['post_inhalt'];
$row_array['likes'] = $row['likes'];
//Funktioniert auch, gib aber nur ein array zurück
//$response[] = $row;
$response["post"] = array();
//push the values in the array
array_push($response["post"],$row_array);
}
print json_encode($response);
很難說......它在代碼中獲得jsonarray ...你可以使用optSJSONArray而不是getJSONArray ...總是使用opt ...而不是get ...你試過getJSONArray( 「機器人」); – challenger