我正在尝试使用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