0

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 Answer 1

1

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

}

Sign up to request clarification or add additional context in comments.

1 Comment

Cheers mate, It was solved by convert array into a JSON string. thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.