4

i am trying to process json response sent by php and i am receiving through Volley response in this android code but after some debugging i figured out that the portion of code processing the json object in not executing strating from the line JSONObject jObj = new JSONObject(response); i printed a Log before it and it's printing , so if you please help me identify the problem i would be greatful. android code:

          private void checkLogin(final String email, final String password) {
    // Tag used to cancel the request
    String tag_string_req = "req_login";

    pDialog.setMessage("Logging in ...");
    showDialog();
    StringRequest strReq = new StringRequest(Method.POST,
            AppConfig.URL_REGISTER, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            Log.d(TAG, "Login Response: " + response.toString());
            hideDialog();
            try {
                Log.d("Login","You're in the try portion of the code");
                JSONObject jObj = new JSONObject(response);
                boolean error = jObj.getBoolean("error");

                // Check for error node in json
                if (!error) {
                    // user successfully logged in
                    // Create login session
                    Log.d("Login", "user successfully logged in");
                    session.setLogin(true);
                    // Launch main activity
                    Intent intent = new Intent(LoginActivity.this,
                            MainActivity.class);
                    startActivity(intent);
                    finish();
                } else {
                    // Error in login. Get the error message
                    String errorMsg = jObj.getString("error_msg");
                    Toast.makeText(getApplicationContext(),
                            errorMsg, Toast.LENGTH_LONG).show();
                }
            } catch (JSONException e) {
                // JSON error
                e.printStackTrace();
            }

        }
    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e(TAG, "Login Error: " + error.getMessage());
            Toast.makeText(getApplicationContext(),
                    error.getMessage(), Toast.LENGTH_LONG).show();
            hideDialog();
        }
    }) {

        @Override
        protected Map<String, String> getParams() {
            // Posting parameters to login url
            Map<String, String> params = new HashMap<String, String>();
            params.put("tag", "login");
            params.put("email", email);
            params.put("password", password);

            return params;
        }

    };

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

php code:

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

/**
* File to handle all API requests
* Accepts GET and POST
* 
* Each request will be identified by TAG
* Response will be JSON data

/**
* check for POST request 
*/
if (isset($_POST['tag']) && $_POST['tag'] != '') {
// get tag
$tag = $_POST['tag'];


// include db handler
require_once 'include/DB_Functions.php';
$db = new DB_Functions();

// response Array
$response = array("tag" => $tag, "error" => FALSE);

// check for tag type
if ($tag == 'login') {

    // Request type is check Login
    $email = $_POST['email'];
    $password = $_POST['password'];

    // check for user
    $user = $db->getUserByEmailAndPassword($email, $password);
    if ($user != false) {
        // user found
        $response["error"] = FALSE;
        $response["uid"] = $user["unique_id"];
        $response["user"]["name"] = $user["name"];
        $response["user"]["email"] = $user["email"];
        $response["user"]["created_at"] = $user["created_at"];
        $response["user"]["updated_at"] = $user["updated_at"];
        echo json_encode($response);
    } else {
        // user not found
        // echo json with error = 1
        $response["error"] = TRUE;
        $response["error_msg"] = "Incorrect email or password!";
        echo json_encode($response);
    }
} else if ($tag == 'register') {
    // Request type is Register new user
    $name = $_POST['name'];
    $email = $_POST['email'];
    $password = $_POST['password'];

    // check if user is already existed
    if ($db->isUserExisted($email)) {
        // user is already existed - error response
        $response["error"] = TRUE;
        $response["error_msg"] = "User already existed";
        echo json_encode($response);
    } else {
        // store user
        $user = $db->storeUser($name, $email, $password);
        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"]["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"] = "Error occured in Registartion";
            echo json_encode($response);
        }
    }
} else {
    // user failed to store
    $response["error"] = TRUE;
    $response["error_msg"] = "Unknow 'tag' value. It should be either 'login' or 'register'";
    echo json_encode($response);
}
} else {
$response["error"] = TRUE;
$response["error_msg"] = "Required parameter 'tag' is missing!";
echo json_encode($response);
}
?>

response in the logcat:

09-16 02:14:11.785: D/LoginActivity(4314): <tr><td bgcolor='#eeeeec' align='center'>1</td><td bgcolor='#eeeeec' align='center'>0.0029</td><td bgcolor='#eeeeec' align='right'>143512</td><td bgcolor='#eeeeec'>{main}(  )</td><td title='D:\wamp\www\android_login_api\index.php' bgcolor='#eeeeec'>..\index.php<b>:</b>0</td></tr>
09-16 02:14:11.785: D/LoginActivity(4314): <tr><td bgcolor='#eeeeec' align='center'>2</td><td bgcolor='#eeeeec' align='center'>0.0045</td><td bgcolor='#eeeeec' align='right'>158264</td><td bgcolor='#eeeeec'>DB_Functions->__construct(  )</td><td title='D:\wamp\www\android_login_api\index.php' bgcolor='#eeeeec'>..\index.php<b>:</b>20</td></tr>
09-16 02:14:11.785: D/LoginActivity(4314): <tr><td bgcolor='#eeeeec' align='center'>3</td><td bgcolor='#eeeeec' align='center'>0.0060</td><td bgcolor='#eeeeec' align='right'>162616</td><td bgcolor='#eeeeec'>DB_Connect->connect(  )</td><td title='D:\wamp\www\android_login_api\include\DB_Functions.php' bgcolor='#eeeeec'>..\DB_Functions.php<b>:</b>13</td></tr>
09-16 02:14:11.785: D/LoginActivity(4314): <tr><td bgcolor='#eeeeec' align='center'>4</td><td bgcolor='#eeeeec' align='center'>0.0072</td><td bgcolor='#eeeeec' align='right'>163184</td><td bgcolor='#eeeeec'><a href='http://www.php.net/function.mysql-connect' target='_new'>mysql_connect</a>
09-16 02:14:11.785: D/LoginActivity(4314): (  )</td><td title='D:\wamp\www\android_login_api\include\DB_Connect.php' bgcolor='#eeeeec'>..\DB_Connect.php<b>:</b>18</td></tr>
09-16 02:14:11.785: D/LoginActivity(4314): </table></font>
09-16 02:14:11.785: D/LoginActivity(4314): {"tag":"login","error":false,"uid":"55ef78acac6190.14514751","user":{"name":"Taha Souri 5","email":"[email protected]","created_at":"2015-09-09 02:09:16","updated_at":null}}

09-17 01:03:17.081: W/System.err(24259): org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
09-17 01:03:17.081: W/System.err(24259):    at org.json.JSON.typeMismatch(JSON.java:111)
09-17 01:03:17.081: W/System.err(24259):    at org.json.JSONObject.<init>(JSONObject.java:159)
09-17 01:03:17.081: W/System.err(24259):    at org.json.JSONObject.<init>(JSONObject.java:172)
09-17 01:03:17.081: W/System.err(24259):    at info.androidhive.loginandregistration.LoginActivity$3.onResponse(LoginActivity.java:104)
09-17 01:03:17.081: W/System.err(24259):    at info.androidhive.loginandregistration.LoginActivity$3.onResponse(LoginActivity.java:97)
09-17 01:03:17.081: W/System.err(24259):    at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60)
09-17 01:03:17.081: W/System.err(24259):    at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
09-17 01:03:17.081: W/System.err(24259):    at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
09-17 01:03:17.082: W/System.err(24259):    at android.os.Handler.handleCallback(Handler.java:808)
09-17 01:03:17.082: W/System.err(24259):    at android.os.Handler.dispatchMessage(Handler.java:103)
09-17 01:03:17.082: W/System.err(24259):    at android.os.Looper.loop(Looper.java:193)
09-17 01:03:17.082: W/System.err(24259):    at android.app.ActivityThread.main(ActivityThread.java:5322)
09-17 01:03:17.082: W/System.err(24259):    at java.lang.reflect.Method.invokeNative(Native Method)
09-17 01:03:17.082: W/System.err(24259):    at java.lang.reflect.Method.invoke(Method.java:515)
09-17 01:03:17.082: W/System.err(24259):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:829)
09-17 01:03:17.082: W/System.err(24259):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:645)
09-17 01:03:17.082: W/System.err(24259):    at dalvik.system.NativeStart.main(Native Method)

the other php codes:

<?php 


class DB_Functions {

private $db;

//put your code here
// constructor
function __construct() {
    require_once 'DB_Connect.php';
    // connecting to database
    $this->db = new DB_Connect();
    $this->db->connect();
}

// destructor
function __destruct() {

}

/**
 * Storing new user
 * returns user details
 */
public function storeUser($name, $email, $password) {
    $uuid = uniqid('', true);
    $hash = $this->hashSSHA($password);
    $encrypted_password = $hash["encrypted"]; // encrypted password
    $salt = $hash["salt"]; // salt
    $result = mysql_query("INSERT INTO users(unique_id, name, email, encrypted_password, salt, created_at) VALUES('$uuid', '$name', '$email', '$encrypted_password', '$salt', NOW())");
    // check for successful store
    if ($result) {
        // get user details 
        $uid = mysql_insert_id(); // last inserted id
        $result = mysql_query("SELECT * FROM users WHERE uid = $uid");
        // return user details
        return mysql_fetch_array($result);
    } else {
        return false;
    }
}

/**
 * Get user by email and password
 */
public function getUserByEmailAndPassword($email, $password) {
    $result = mysql_query("SELECT * FROM users WHERE email = '$email'") or die(mysql_error());
    // check for result 
    $no_of_rows = mysql_num_rows($result);
    if ($no_of_rows > 0) {
        $result = mysql_fetch_array($result);
        $salt = $result['salt'];
        $encrypted_password = $result['encrypted_password'];
        $hash = $this->checkhashSSHA($salt, $password);
        // check for password equality
        if ($encrypted_password == $hash) {
            // user authentication details are correct
            return $result;
        }
    } else {
        // user not found
        return false;
    }
}

/**
 * Check user is existed or not
 */
public function isUserExisted($email) {
    $result = mysql_query("SELECT email from users WHERE email = '$email'");
    $no_of_rows = mysql_num_rows($result);
    if ($no_of_rows > 0) {
        // user existed 
        return true;
    } else {
        // user not existed
        return false;
    }
}

/**
 * Encrypting password
 * @param password
 * returns salt and encrypted password
 */
public function hashSSHA($password) {

    $salt = sha1(rand());
    $salt = substr($salt, 0, 10);
    $encrypted = base64_encode(sha1($password . $salt, true) . $salt);
    $hash = array("salt" => $salt, "encrypted" => $encrypted);
    return $hash;
}

/**
 * Decrypting password
 * @param salt, password
 * returns hash string
 */
public function checkhashSSHA($salt, $password) {

    $hash = base64_encode(sha1($password . $salt, true) . $salt);

    return $hash;
}

}

?>

<?php  
class DB_Connect {

// constructor
function __construct() {

}

// destructor
function __destruct() {
    // $this->close();
}

// Connecting to database
public function connect() {
    require_once 'include/Config.php';
    // connecting to mysql
    $con = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or die(mysql_error());
    // selecting database
    mysql_select_db(DB_DATABASE) or die(mysql_error());

    // return database handler
    return $con;
}

// Closing database connection
public function close() {
    mysql_close();
}

}

?>
13
  • 2
    if processing json code doesn't start, the program may be terminated by other exception before processing json... Commented Sep 15, 2015 at 1:48
  • 2
    Hope, PHP Output have set Header Content-Type: application/json so that it can be readable by any JSON parser Commented Sep 15, 2015 at 2:24
  • 2
    <?php header('Content-Type: application/json'); //here your code for output ?> this will work to parse Commented Sep 15, 2015 at 2:25
  • 2
    Please post the entire crash report from the logcat you might be getting some sort of exception. Commented Sep 15, 2015 at 5:45
  • 1
    Ok, @MarmikBhatt thank you i'm missling this line in header , i will try again and report. Commented Sep 16, 2015 at 0:17

1 Answer 1

2

It should be like this...

 $user = $db->getUserByEmailAndPassword($email, $password);
 header('Content-Type:application:json;');
if ($user != false) {
    // user found
    $response["error"] = FALSE;
    $response["uid"] = $user["unique_id"];
    $response["user"]["name"] = $user["name"];
    $response["user"]["email"] = $user["email"];
    $response["user"]["created_at"] = $user["created_at"];
    $response["user"]["updated_at"] = $user["updated_at"];

} else {
    // user not found
    // echo json with error = 1
    $response["error"] = TRUE;
    $response["error_msg"] = "Incorrect email or password!";
    $response["user"] = null;
}
 echo json_encode($response);
Sign up to request clarification or add additional context in comments.

Comments

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.