【问题标题】:How to fix this Problem org.json.JSONException: Value Database of type java.lang.String cannot be converted to JSONObject如何解决这个问题 org.json.JSONException: Value Database of type java.lang.String cannot be convert to JSONObject
【发布时间】:2019-04-18 08:52:48
【问题描述】:

我正在使用 Volley 库 php mysql 来构建登录系统,我正面临这个问题

注册错误= 156 org.json.JSONException: java.lang.String 类型的值数据库无法转换为 JSONObject

当我检查我的 数据库用户详细信息插入成功时

这些方法我已经试过了

<?php
 $result = array();
 $allValues = array();
 $values = array();

 if (mysqli_query($connection, $sql)) {


         $values['status'] = 'true';
         $values['message'] = 'successful';
    } else {


         $values['status'] = 'false';
         $values['message'] = 'failed';
    }

$allValues[] = $values; 

 $result['result'] = $allValues;

 echo json_encode($result);



?>

更改我的 java 代码

JSONArray jsonArray =response.getJSONArray("result");

 for(int i = 0 ; i<jsonArray.length(); i++){
       JSONObject jsonObject = jsonArray.getJSONObject(i);
      Log.i("jsonsingleImage",jsonObject.toString());

     String status =   jsonObject.getString("status");
     String message =    jsonObject.getString("message");



 JSONObject jo = new JSONObject(success.substring(1, success.length()-1));

 new JSONObject(success.substring(success.indexOf("{"), success.lastIndexOf("}") + 1));


我的 Registration.php 代码
<?php 

if ($_SERVER['REQUEST_METHOD'] == "POST") {

    require_once("connection.php");

    $first_name = $_POST['firstName'];

    $first_name = strip_tags($first_name);
    $first_name = ucfirst(strtolower($first_name)); // uppercase first letter
    $first_name = str_replace(' ', '', $first_name); // remove spaces


    $last_name = $_POST['lastName'];
    $last_name = strip_tags($last_name);
    $last_name = ucfirst(strtolower($last_name)); // uppercase first letter
        $last_name = str_replace(' ', '', $last_name); // remove spaces


    $email = $_POST['email'];

    $email = strip_tags($email);
    $email = str_replace(' ', '', $email); // remove spaces
    $password = $_POST['password'];
    $password = mysqli_real_escape_string($password);
    $password = strip_tags($password);

    $password = str_replace(' ', '', $password); // remove spaces
    $password = password_hash($_POST['password'], PASSWORD_BCRYPT);


    $sql = "INSERT INTO users (firstName, lastName, email, password) VALUES ('$first_name', '$last_name', '$email', '$password')";

    if (mysqli_query($connection, $sql)) {


        $result['success']  = "True";
        $result['message']  = "Successfully";

        echo json_encode($result);
        mysqli_close($connection);

    } else {



          $result['success']  = "False";
        $result['message']  = "Failed";

        echo json_encode($result);
        mysqli_close($connection);
    }




}

?>

SignActivity.java 代码

        StringRequest stringRequest = new StringRequest(Request.Method.POST, URLS.SIGNUP_API, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String success = jsonObject.getString("success");

                    if (success.equals("True")) {

                        Toast.makeText(SignupActivity.this, "Registration successfully", Toast.LENGTH_LONG).show();
                        Log.i("Registration ======= ", "Registration successfully");

                    }

                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                    Toast.makeText(SignupActivity.this, "Registration Error= 156 " + e.toString(), Toast.LENGTH_LONG).show();

                    Log.i("Catch error 156  ======", e.toString());

                }
            }
        },
'''

【问题讨论】:

    标签: java php android


    【解决方案1】:

    参考以下代码

    这里是连接 php 文件

    <?php
    $conn = mysqli_connect("localhost", "root", "", "rfid") or die('connection error');
    ?>
    

    这里是登录php文件

    <?php
    if ($_SERVER['REQUEST_METHOD']=='POST') {
    $parent_user = $_POST['username'];
    $parent_pass = $_POST['password'];
    
    include('connect.php');
    
    $sql = "SELECT * FROM parent WHERE parent_user='$parent_user' AND 
    parent_pass='$parent_pass' ";
    $response = mysqli_query($conn, $sql);
    if (mysqli_num_rows($response)==1) {
      while($row=mysqli_fetch_assoc($response)){
        $result["id"] = $row['parent_id'];
      }
    $result["success"] = "1";
    $result["message"] = "success";
      echo json_encode($result);
      mysqli_close($conn);
    }
    else{
      $result["success"] = "0";
      $result["message"] = "error";
    
      echo json_encode($result);
      mysqli_close($conn);
    }
    }
    ?>
    

    这里是登录类

     private void LogMeIn() {
        final String Username = Utxt.getText().toString().trim();
        final String Password = Ptxt.getText().toString().trim();
        StringRequest SR = new StringRequest(Request.Method.POST, url, new 
        Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    JSONObject jsonObject=new JSONObject(response);
                    Log.d("test", "onResponse: "+jsonObject.toString(4));
                    String success=jsonObject.getString("success");
                    Log.d("test", "onResponse: "+success);
                    if (success.equals("1")){
                        String Id =jsonObject.getString("id");
    
                        session.createLoginSession(""+Id);
                        Intent intent=new Intent(LoginActivity.this,MainActivity.class);
                        intent.putExtra("Id",Id);
                        startActivity(intent);
                        Toast.makeText(LoginActivity.this, "******Welcome*******", 
                     Toast.LENGTH_SHORT).show();
                    }
                    else {
                        Toast.makeText(LoginActivity.this, "Invalid Username OR 
                        Password", Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    Toast.makeText(LoginActivity.this, "Register 
                unsuccessful"+e.toString(), Toast.LENGTH_SHORT).show();
    
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(getApplicationContext(), " "+error.toString(), 
          Toast.LENGTH_SHORT).show();
            }
        })
        {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<>();
                params.put("username", Username);
                params.put("password", Password);
                return params;
            }
    
        };
        RequestQueue RQ = Volley.newRequestQueue(LoginActivity.this);
        RQ.add(SR);
    
    }
    

    【讨论】:

    • 先生仍然面临同样的问题,请告诉我如何解决这个问题
    • 请分享日志
    猜你喜欢
    • 1970-01-01
    • 2013-09-11
    • 1970-01-01
    • 2016-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多