简体   繁体   中英

String cannot be converted to JSONObject - Android

Ok, guys. I developed a Login-Registration System using MySQL and PHP. At the beginning, it worked perfectly, being able to register new accounts, and, obviously, to LogIn. But, for 2 days, I'm receiving some weird errors(?!) in my Android.

This is my PHP code:

<?php
$con = mysqli_connect("***", "***", "***", "***");

$email = $_POST["email"];
$password = $_POST["password"];
$name = $_POST["name"];
$age = $_POST["age"];
$location = $_POST["location"];


$statement = mysqli_prepare($con, "INSERT INTO useraccounts (email, password, name, age, location) VALUES (?, ?, ?, ?, ?)");
mysqli_stmt_bind_param($statement, "sssis", $email, $password, $name, $age, $location);
mysqli_stmt_execute($statement);

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

echo json_encode($response);

This is my RegisterRequest class:

public class RegisterRequest extends StringRequest {

private static final String REGISTER_REQUESTURL = "http://docscanner.ezyro.com/Register.php";
private Map<String, String> params;

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

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

And, finally, this is my method:

    try {
        final EditText etEmail = (EditText) findViewById(R.id.emailTxt);
        final EditText etPassword = (EditText) findViewById(R.id.passwordTxt);
        final EditText etName = (EditText) findViewById(R.id.nameTxt);
        final EditText etAge = (EditText) findViewById(R.id.ageTxt);
        final EditText etLocation = (EditText) findViewById(R.id.locationTxt);

        final String email = etEmail.getText().toString();
        final String password = etPassword.getText().toString();
        String name = etName.getText().toString();
        int age = Integer.parseInt(etAge.getText().toString());
        String location = etLocation.getText().toString();

        if (!etEmail.equals("") && !etPassword.equals("") && !etName.equals("") && !etAge.equals("") && !etLocation.equals("")) {
            if (isValidEmailAddress(email)) {

                Response.Listener<String> listener = new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            boolean success = jsonObject.getBoolean("success");
                            if (success) {
                                Intent loginIntent = new Intent(getApplicationContext(), LoginActivity.class);
                                loginIntent.putExtra("emailExtra", email);
                                loginIntent.putExtra("passwordExtra", password);
                                startActivity(loginIntent);
                            } else {
                                AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this);
                                builder.setMessage("Register failed")
                                        .setNegativeButton("Retry", null)
                                        .create()
                                        .show();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                };

                RegisterRequest registerRequest = new RegisterRequest(email, password, name, age, location, listener);
                RequestQueue queue = Volley.newRequestQueue(RegisterActivity.this);
                queue.add(registerRequest);
            } else {
                Toast.makeText(getApplicationContext(),
                        "Email format is not valid",
                        Toast.LENGTH_LONG)
                        .show();
            }
        } else {
            Toast.makeText(getApplicationContext(),
                    "All fields must be completed",
                    Toast.LENGTH_LONG)
                    .show();
        }
    }catch(NumberFormatException nEx){
        Toast.makeText(getApplicationContext(),
                "Please complete all fields in order to submit the document",
                Toast.LENGTH_LONG)
                .show();
    }
}

My error:

W/System.err: org.json.JSONException: Value

There is problem with your php code as far as i can see. Add this to your php file (in the start)

header('Content-Type: application/json');

and another problem I saw was that when making a simple post request (FROM POSTMAN) it returns the following data :-

<html>
    <body>
        <script type="text/javascript" src="/aes.js" ></script>
        <script>function toNumbers(d){var e=[];d.replace(/(..)/g,function(d){e.push(parseInt(d,16))});return e}function toHex(){for(var d=[],d=1==arguments.length&&arguments[0].constructor==Array?arguments[0]:arguments,e="",f=0;f
            <d.length;f++)e+=(16>d[f]?"0":"")+d[f].toString(16);return e.toLowerCase()}var a=toNumbers("f655ba9d09a112d4968c63579db590b4"),b=toNumbers("98344c2eee86c3994890592585b49f80"),c=toNumbers("3c1ab4cc426e0aacb5f07f248a1799fe");document.cookie="__test="+toHex(slowAES.decrypt(c,2,a,b))+"; expires=Thu, 31-Dec-37 23:55:55 GMT; path=/"; location.href="http://docscanner.ezyro.com/Register.php?i=2";
            </script>
            <noscript>This site requires Javascript to work, please enable Javascript in your browser or use a browser with Javascript support</noscript>
        </body>
    </html>

The following is obviously not a string containing JSON data. try adding the header part of the code specified and if possible you should think about moving to Firebase auth or some other auth service becuase you are sending the non- encrypted password over an HTTP connection. You are also sending an non-hashed password to your db which is another problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM