登录系统:$ _POST ['username']和$ _POST ['password']始终为空

时间:2015-03-25 15:47:39

标签: php android mysql json http

首先我要说的是,我已经无休止地在Google上寻求帮助,并且在过去的x小时内花了很多时间来调试相同的错误,但我无法理解。

我正在关注如何为我的Android应用创建登录系统this tutorial。当我在Genymotion上运行我的应用程序时,我能够输入我的登录凭据,但是一旦我点击登录按钮,我的应用程序崩溃了。我在调试模式下再次运行我的应用程序,原因是由于以下异常:

  

引起:java.lang.NullPointerException:尝试在空对象引用上调用虚方法'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));
}

1 个答案:

答案 0 :(得分:2)

我想你忘记设置JSON标头了。 如果要返回JSON,则需要更改此代码

$data = $response;
header('Content-Type: application/json');
echo json_encode($data);
相关问题