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

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)!');
            }
        }
    });
    

    }

    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题