让我首先说,我在谷歌上无休止地搜索帮助,在过去的x个小时里,我确实花了x个小时调试同一个错误,但我就是搞不清楚。
我正在学习如何为我的Android应用程序创建登录系统的教程。当我在Genymotion上运行我的应用程序时,我可以输入我的登录凭据,但我一按下登录按钮,我的应用就会崩溃。我在调试模式下再次运行了我的应用程序,原因是以下异常:
由以下原因引起:java.lang.NullPointerException:试图在null对象引用上调用虚拟方法"java.lang.String org.json.JSONObject.toString()"
如果我错了,请纠正我,但我认为发生的事情是我的JSONParser试图解析一个空对象。这可能是因为我的PHP文件总是返回空的,我不知道为什么会这样
if(isset($_POST['username'])) {
$password=$_POST["username"];
}
if(isset($_POST['password'])) {
$password=$_POST["password"];
}
if (!empty($_POST))
{
if (empty($_POST['username']) || empty($_POST['password']))
{
// Create some data that will be the JSON response
$response["success"] = 0;
$response["message"] = "One or both of the fields are empty .";
//die is used to kill the page, will not let the code below to be executed. It will also
//display the parameter, that is the json data which our android application will parse to be
//shown to the users
die(json_encode($response));
}
$query = " SELECT * FROM login WHERE username = '$username'and password='$password'";
$sql1=mysql_query($query);
$row = mysql_fetch_array($sql1);
if (!empty($row))
{
$response["success"] = 1;
$response["message"] = "You have been sucessfully login";
die(json_encode($response));
}
else
{
$response["success"] = 0;
$response["message"] = "invalid username or password ";
die(json_encode($response));
}
}
else
{
$response["success"] = 0;
$response["message"] = " One or both of the fields are empty ";
die(json_encode($response));
}
我想您忘记设置JSON头了。如果您正在返回JSON,则需要像以下一样更改代码
$data = $response;
header('Content-Type: application/json');
echo json_encode($data);