1

I 'm implementing a basic registration system in an android app which is connected to SQL DATABASE via wampserver and PHP API ... each time I execute a registration process the user gets saved in the database but when I try to get the JSON response of the process which carries the registered user information to store in a SQLite database associated to my app ... I get the the error which stated : string cannot be converted to a json object.

This is the android end where I call the PHP code to execute the registration and receive the json response.

private void registerUser(final String name, final String email,
        final String password, final String latitude,
        final String longitude, final String userType) {
    // Tag used to cancel the request
    String tag_string_req = "req_register";

    pDialog.setMessage("Registering ...");
    showDialog();

    StringRequest strReq = new StringRequest(Method.POST,
            AppConfig.URL_REGISTER, new Response.Listener<String>() {

                @Override
                public void onResponse(String response) {
                    hideDialog();

                    try {
                        Log.i("tagconvertstr", "[" + response.toString()
                                + "]");


                        JSONObject jObj = new JSONObject(response);
                        boolean error = jObj.getBoolean("error");
                        if (!error) {
                            // User successfully stored in MySQL
                            // Now store the user in sqlite
                            String uid = jObj.getString("uid");

                            JSONObject user = jObj.getJSONObject("user");
                            String name = user.getString("name");
                            String email = user.getString("email");
                            String latitude = user.getString("latitude");
                            String longitude = user.getString("longitude");
                            String userType = user.getString("userType");
                            String service = user.getString("service");
                            String rate = user.getString("rate");
                            String rated_clients = user
                                    .getString("rated_clients");
                            String servicesTag = user
                                    .getString("servicesTag");
                            String created_at = user
                                    .getString("created_at");

                            // Inserting row in users table
                            db.addUser(name, email, latitude, longitude,
                                    userType, service, rate, rated_clients,
                                    servicesTag, uid, created_at);

                            Toast.makeText(
                                    getApplicationContext(),
                                    "User successfully registered. Try login now!",
                                    Toast.LENGTH_LONG).show();

                            // Launch login activity
                            checkLogin(email, password);

                        } else {
                            Log.d("heeeeeeeeeeeeeeeey", "error here");

                            // Error occurred in registration. Get the error
                            // message
                            String errorMsg = jObj.getString("error_msg");
                            toast.makeDialog("Error in registering "
                                    + errorMsg + "kk",
                                    getApplicationContext());
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
            }, new Response.ErrorListener() {

                @Override
                public void onErrorResponse(VolleyError error) {
                    loginLayout.setVisibility(View.GONE);
                    registerLayout.setVisibility(View.GONE);
                    noConnectionLayout.setVisibility(View.VISIBLE);
                    tag = "register";
                    hideDialog();
                }
            }) {

        @Override
        protected Map<String, String> getParams() {
            // Posting params to register url
            Map<String, String> params = new HashMap<String, String>();
            params.put("name", name);
            params.put("email", email);
            params.put("password", password);
            params.put("latitude", latitude);
            params.put("longitude", longitude);
            params.put("userType", userType);

            return params;
        }

    };
    strReq.setRetryPolicy(new DefaultRetryPolicy(0,
            DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

    // Adding request to request queue
    AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}

I get the error at the line : JSONObject jObj = new JSONObject(response);

this is the PHP code for the registration process :

<?php

ini_set ( 'display_errors', 'On' );

require_once 'include/DB_Functions.php';

$db = new DB_Functions ();

// json response array

$response = array (
"error" => FALSE 

`);

if (isset ( $_POST ['name'] ) && isset ( $_POST ['email'] ) && isset ( $_POST ['password'] ) && isset ( $_POST ['latitude'] ) && isset ( $_POST ['longitude'] ) && isset ( $_POST ['userType'] )) {



// receiving the post params
$name = $_POST ['name'];
$email = $_POST ['email'];
$password = $_POST ['password'];
$latitude = $_POST ['latitude'];
$longitude = $_POST ['longitude'];
$userType = $_POST ['userType'];

// check if user is already existed with the same email
if ($db->isUserExisted ( $email )) {
    // user already existed
    $response ["error"] = TRUE;
    $response ["error_msg"] = "User already existed with " . $email;
    echo json_encode ( $response );
} else {
    // create a new user
    $user = $db->storeUser ( $name, $email, $password, $latitude, $longitude, $userType );

    if ($user) {
        // user stored successfully
        $response ["error"] = FALSE;
        $response ["uid"] = $user ["unique_id"];
        $response ["user"] ["name"] = $user ["name"];
        $response ["user"] ["email"] = $user ["email"];
        $response ["user"] ["latitude"] = $user ["latitude"];
        $response ["user"] ["longitude"] = $user ["longitude"];
        $response ["user"] ["userType"] = $user ["userType"];
        $response ["user"] ["service"] = $user ["service"];
        $response ["user"] ["rate"] = $user ["rate"];
        $response ["user"] ["rated_clients"] = $user ["rated_clients"];
        $response ["user"] ["servicesTag"] = $user ["servicesTag"];
        $response ["user"] ["created_at"] = $user ["created_at"];
        $response ["user"] ["updated_at"] = $user ["updated_at"];
        echo json_encode ( $response );
    } else {

        // user failed to store
        $response ["error"] = TRUE;
        $response ["error_msg"] = "Unknown error occurred in registration!";
        echo json_encode ( $response );
    }
}
} else {
$response ["error"] = TRUE;
$response ["error_msg"] = "Required parameters (name, email or password) is missing!";
echo json_encode ( $response );
}
?>

This is both isUserExicted and storeUser functions :

public function isUserExisted($email) {
    $stmt = $this->conn->prepare ( "SELECT email from users WHERE email = ?" );

    $stmt->bind_param ( "s", $email );

    $stmt->execute ();

    $stmt->store_result ();

    if ($stmt->num_rows > 0) {
        // user existed
        $stmt->close ();
        return true;
    } else {
        // user not existed
        $stmt->close ();
        return false;
    }
}


public function storeUser($name, $email, $password, $latitude, $longitude, $userType) {
    $uuid = uniqid ( '', true );
    $hash = $this->hashSSHA ( $password );
    $encrypted_password = $hash ["encrypted"]; // encrypted password
    $salt = $hash ["salt"]; // salt

    $service = "none";
    $rate = "none";
    $rated_clients = "none";
    $servicesTag = "none";

    $stmt = $this->conn->prepare ( "INSERT INTO users(unique_id, name, email, encrypted_password, latitude, longitude, userType, salt, service, rate, rated_clients, servicesTag, created_at) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())" );
    $stmt->bind_param ( "ssssssssssss", $uuid, $name, $email, $encrypted_password, $latitude, $longitude, $userType, $salt, $service, $rate, $rated_clients, $servicesTag );
    $result = $stmt->execute ();
    $stmt->close ();
    var_dump ( $result );
    // check for successful store
    if ($result) {

        $stmt = $this->conn->prepare ( "SELECT * FROM users WHERE email = ?" );

        $stmt->bind_param ( "s", $email );

        $stmt->execute ();
        $user = $stmt->get_result ()->fetch_assoc ();
        $stmt->close ();
        var_dump ( $user );
        echo '</pre>';

        return $user;
    } else {

        return null;
    }
}

this is the response value :

enter image description here

Note : the columns binded to the query in storeUser method is guaranteed to be created in the database.

Ahmed Samy
  • 896
  • 2
  • 7
  • 20

1 Answers1

0

Your json you get from server is not valid one, you can check json validity by runing it on sites like:

http://www.jsoneditoronline.org/

the problem is probably caused by some server errors, or you echo some other output before the resulting json, those are html tags at the begging. I would suggest to turn off errors, see here for more: Turn Off Display Error PHP.ini

you can do it using .htaccess file, ex:

Options -Indexes

# suppress PHP errors from displaying in the browser
php_flag display_startup_errors off
php_flag display_errors off
php_flag html_errors off

# log PHP errors to a file
php_flag log_errors on
php_value error_reporting 32767
php_value error_log "./error_log.txt"

Your php should generally be in the following simplified form:

<?php
header('Content-type: application/json');
$json = file_get_contents('php://input'); // input json
// ...
$js_result = json_encode(array("error" => "unknown_action")); // result
echo $js_result;
Community
  • 1
  • 1
marcinj
  • 44,446
  • 9
  • 70
  • 91