获取“java.lang.String无法转换为JSONObject”错误如何纠正它

时间:2017-06-28 15:54:22

标签: java php android sql json

在我的应用中收到此错误

  

W / System.err:org.json.JSONException:java.lang.String类型的值br无法转换为JSONObject

这是我的RegisterActivity.java

public class RegisterActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_register);

    final EditText etName=(EditText) findViewById(R.id.etname);
    final EditText etUsername=(EditText) findViewById(R.id.etusername);
    final EditText etPassword=(EditText) findViewById(R.id.etpassword);
    final EditText etCPassword=(EditText) findViewById(R.id.etcpassword);
    final EditText etEmail=(EditText) findViewById(R.id.etemail);
    final EditText etContact=(EditText) findViewById(R.id.etcontact);
    final EditText etAge=(EditText) findViewById(R.id.etage);
    final Button btnRegister=(Button) findViewById(R.id.btnregister);

    btnRegister.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final String name=etName.getText().toString();
            final String username=etUsername.getText().toString();
            final String password=etPassword.getText().toString();
            final String email=etEmail.getText().toString();
            final int age=Integer.parseInt(etAge.getText().toString());
            final int contact=Integer.parseInt(etContact.getText().toString());

            Response.Listener<String> responseListener = new Response.Listener<String>(){

                @Override
                public void onResponse(String response) {
                    try {
                        JSONObject jsonResponse= new JSONObject(response);
                        boolean success = jsonResponse.getBoolean("success");

                        if(success){
                            Intent intent = new Intent(RegisterActivity.this,LoginActivity.class);
                            RegisterActivity.this.startActivity(intent);
                        }else{
                            AlertDialog.Builder builder= new AlertDialog.Builder(RegisterActivity.this);
                            builder.setMessage("Register Failed")
                                    .setNegativeButton("Retry",null)
                                    .create()
                                    .show();
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();

                        AlertDialog.Builder build= new AlertDialog.Builder(RegisterActivity.this);
                        build.setMessage("JSON Failed")
                                .setNegativeButton("Retry",null)
                                .create()
                                .show();
                    }
                }
            };

            RegisterRequest registerRequest = new RegisterRequest(name,username,password,email,contact,age,responseListener);
            RequestQueue queue = Volley.newRequestQueue(RegisterActivity.this);
            queue.add(registerRequest);
        }
    });
}
}

这是RegistryRequest.java

public class RegisterRequest extends StringRequest{

private static final String REGISTER_REQUEST_URL="https://smplycode.000webhostapp.com/Registerft.php";
private Map<String, String> params;


public RegisterRequest(String name,String username,String password,String email,int contact, int age, Response.Listener<String> listener) {
    super(Method.POST, REGISTER_REQUEST_URL, listener, null);
    params = new HashMap<>();
    params.put("name",name);
    params.put("username",username);
    params.put("password",password);
    params.put("email",email);
    params.put("contact",contact+"");
    params.put("age",age+"");
    }

@Override
public Map<String, String> getParams() {return params;}
    }

这是我的registerft.php文件

<?php
    $con = mysqli_connect("localhost", "id20401_mydbname", "mydbpaord", "id2041_mydme");

    $name = $_POST["name"];
    $username = $_POST["username"];
    $password = $_POST["password"];
    $email = $_POST["email"];
    $contact = $_POST["contact"];
    $age = $_POST["age"];

    $statement = mysqli_prepare($con, "INSERT INTO usersft (name, username, password, email, contact, age) VALUES (?, ?, ?, ?, ?, ?)");
    mysqli_stmt_bind_param($statement, "ssssii", $name, $username,$password,$email,$contact, $age);
    mysqli_stmt_execute($statement);

    $response = array();
    $response["success"] = true;  

    echo json_encode($response);
?>

我在youtube上观看了this教程,这段代码正在编写该教程。

Getting this when printing response string as an alert

如果有人想要帮助请给我你的电子邮件ID我正在做的项目我想为c ++学习新的应用程序:)

2 个答案:

答案 0 :(得分:0)

首先在JSONObject jsonResponse= new JSONObject(response);之前打印出字符串,这样你才能真正知道它是否是正确的格式。 Br是换行符的html标记,因此我认为您的响应是HTML而不是JSON

答案 1 :(得分:0)

我首先尝试收集不同的答案和评论

如果您在应用程序之外的RegistryRequest.java进行POST呼叫(例如使用curl -i -X POST --data "name=name&username=username&password=password&email=email&contact=123456789&age=21" https://smplycode.000webhostapp.com/Registerft.php),则会出现 HTML页面,其中包含错误消息(由其他):

<br />
<b>Warning</b>:  mysqli_stmt_bind_param() expects parameter 1 to be mysqli_stmt, boolean given in <b>/storage/ssd1/901/2049901/public_html/Registerft.php</b> on line <b>12</b><br />
<br />
<b>Warning</b>:  mysqli_stmt_execute() expects parameter 1 to be mysqli_stmt, boolean given in <b>/storage/ssd1/901/2049901/public_html/Registerft.php</b> on line <b>13</b><br />

在第一个HTML标记(<br />)上解释,因为JSON失败 - 这就是错误消息的内容。

现在让我们尝试分析 php错误消息,即查找根本原因:

创建数据库连接或构建语句失败并返回一个布尔false 而非预备语句 - 因此mysqli_stmt_bind_param()上的错误。有关详细信息,请参阅mysqli_fetch_array()/mysqli_fetch_assoc()/mysqli_fetch_row() expects parameter 1 to be resource or mysqli_result, boolean given

请确保您的数据库查询正常,并且您的php页面会返回有效的JSON