我不知道我在做什么错。我已经制作了一个注册表单,其中包含一个唯一的代码,该代码保存在sql数据库中,因此当用户输入错误的代码时,我希望显示错误消息或吐司。
现在,我面临的是org.json JSONException:没有成功的价值。 如何将错误消息设置为mainActivity中定义的代码textview?
或如何使吐司面包出现。 是否有比我目前正在使用的方法更好的方法来限制用户注册(手动将唯一代码保存在数据库中)? register.php 其余代码可以完美运行,下面的方法属于AsyncTask类 BackgroundTask.java 答案 0 :(得分:0) 问题是您多次使用echo,还应仅对json编码的数据使用echo。. 要解决此问题,只需尝试使用邮递员获取不同情况下的API响应,您将了解该问题。 答案 1 :(得分:0) JSONObject.getString()方法不会返回 null ,并且会抛出JSONException。 使用optString():<?php
if ($_SERVER["REQUEST_METHOD"] =="POST"){
require_once 'connect.php';
$name = $_POST["name"];
$email = $_POST["email"];
$password = $_POST["password"];
$code=$_POST["code"];
//for checking if the email address already exists
$mysql_select="SELECT email FROM register_table where email ='$email' ";
$res=mysqli_query($conn,$mysql_select);
if (mysqli_num_rows($res) > 0 ) {
$row = mysqli_fetch_assoc($res);
if($email==$row['email']){
echo "Email already exists";
}
}else {
$code_query="SELECT code FROM code_table where code='$code' ";
$code_result=mysqli_query($conn,$code_query);
$roww = mysqli_fetch_assoc($code_result);
$sql="INSERT INTO register_table (name, email,password) VALUES ('$name', '$email', '$password')";
if($code!=$roww['code']){
$resultt["codes"] = "0";
echo json_encode($resultt);
$result["success"] = "0";
echo json_encode($result);
mysqli_close($conn);
}else if (mysqli_query($conn, $sql) && $code==$roww['code'] ){
$resultt["codes"] = "1";
echo json_encode($resultt);
$result["success"] = "1";
echo json_encode($result);
mysqli_close($conn);
}else {
$result["success"] = "0";
$result["message"] = "error";
echo json_encode($result);
echo "registration not successful";
mysqli_close($conn);
}
}
}else{
echo "register method is not post";
}
?>
protected void onPostExecute(String res) {
try {
JSONObject jsonobject = new JSONObject(res);
String success = jsonobject.getString("success");
String code_result=jsonobject.getString("codes");
if(code_result.equals("0") && success.equals("0")){
Toast.makeText(context,"Please enter the correct code",Toast.LENGTH_SHORT).show();
}else if (success.equals("1") && code_result.equals("1")) {
Toast.makeText(context, "Register Successfully!", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(context, "Register Error!" + e.toString(), Toast.LENGTH_SHORT).show();
}
}
2 个答案:
String success = jsonobject.optString("success");
String code_result = jsonobject.optString("codes");
if (success != null && code_result != null) {
// ...
}