douji9184 2017-02-19 21:37
浏览 473
已采纳

JSONException String无法转换为JSONArray

I have been trying to make a login system for my app in android studio and I keep getting this error

org.json.JSONException: Value Connection of type java.lang.String cannot be converted to JSONArray

and could not fix it in any way, I hope you can spot it and help me out. Here is a part of the login activity where I believe the problem is (I can provide more code if needed)

    {StringRequest stringRequest = new StringRequest(Request.Method.POST, login_url,
        new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try
                {
                    JSONArray jsonArray = new JSONArray(response);
                    JSONObject jsonObject = jsonArray.getJSONObject(0);
                    String code = jsonObject.getString("code");
                    if(code.equals("login_failed"))
                    {
                        builder.setTitle("Login Error...");
                        displayAlert(jsonObject.getString("message"));
                    }
                    else
                    {
                        Intent intent = new Intent(LoginActivity.this,TestActivity.class);
                        Bundle bundle = new Bundle();
                        bundle.putString("email",jsonObject.getString(("email")));
                        intent.putExtras(bundle);
                        startActivity(intent);
                    }
                }
                catch (JSONException e)
                {
                    e.printStackTrace();
                }

            }
        }, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error)
    {
        Toast.makeText(LoginActivity.this,"Error",Toast.LENGTH_LONG).show();
        error.printStackTrace();
    }
})
{
    @Override
    protected Map<String, String> getParams() throws AuthFailureError
    {
        Map<String,String> params = new HashMap<String, String>();
        params.put("email",email);
        params.put("password",password);
        return params;
    }
};
    MySingleton.getmInstance(LoginActivity.this).addToRequestQue(stringRequest);

}

here is the php code:

<?php
require "connection.php";
$email = $_POST["email"];
$password = $_POST["password"];

$sql = "select email,password from user_info where email like '".$email."' and password like '".$password."';";
$result = mysqli_query($connection,$sql);
$response = array();
if(mysqli_num_rows($result)>0)
{
    $row = mysqli_fetch_row($result);
    $email = $row[0];
    $password = $row[1];
    $code = "login_success";
    array_push($response,array("code"=>$code,"email"=>$email,"password"=>$password));
    echo json_encode($response);
}
else
{
    $code = "login_failed";
    $message = "User not found...";
    array_push($response,array("code"=>$code,"message"=>$message));
    echo json_encode($response);    
}
mysqli_close($connection);
?>
  • 写回答

1条回答 默认 最新

  • douyingzhan5905 2017-02-19 21:44
    关注

    You can't create a JSONArray from a String unless that string is a proper stringified JSON file.

    You have to, in your PHP, convert your array into a JSON string instead. (or vice versa if I understood the relationship incorrectly, I didn't read your code too accurately).

    Another solution is for you to use jquery and an ajax function to call the PHP script (I dont' know what you're creating, could be a Cordova plugin in which case you have Javascript, otherwise you'll have to do something similar in Java, google is your friend).

    Here's a function taken straight from one of my own apps I'm making. Read through it, it might not be 100% copy pastable. The important parts are that it converts a javascript object into a proper JSON string before sending it to your PHP function.

    function login(successCallback, errorCallback, args) {
    var loginData = {
        "username": args[0].username,
        "password": args[0].password
    };
    var dataString = JSON.stringify(loginData);
    $.ajax({
        url: 'login.php',
        method: 'post',
        data: {loginData: dataString},
        dataType: 'json',
        complete: function (data) {
            console.log(data.responseText);
        },
        error: function (xhr, status, errorThrown) {
            console.log("Error: " + errorThrown);
            console.log("Status: " + status);
            errorCallback('Error logging in!');
        },
        success: function (data) {
            if (data.status == "success") {
                console.log(data.responseText);
                successCallback('Success logging in!');
            } else if (data.status = "noConnection") {
                console.log(data.responseText);
                errorCallback('Could not connect to database.');
            } else {
                console.log(data.responseText);
                errorCallback('Error logging in (but database was connected to)!');
            }
        }
    });
    

    }

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵