0

I have a registration form and Im doing validation on the fly. After the user switches focus off the email field, I want to check whether there is such email registered in the database and toast about it. No matter what I do, though, I always get a null pointer exception on line 585 which is the following line:

Log.d("Checking wether this email exists in database", json.toString());

Here is the whole thing:

class CheckWetherAUserWithSuchEmailExists extends AsyncTask<String, String, String> {

        int success;

        @Override
        protected String doInBackground(String... args) {

            int success;
            try {
                // Building Parameters
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                Log.d("Kylie", userEmail);
                params.add(new BasicNameValuePair("user_email", userEmail));

                Log.d("request!", "starting");

                // Posting user data to script
                JSONObject json = jsonParser.makeHttpRequest(CHECK_EMAIL_EXISTS_URL, "POST", params);

                // full json response
                Log.d("Checking wether this email exists in database", json.toString());

                // json success element
                success = json.getInt(TAG_SUCCESS);
                if (success == 1) {
                    Log.d("Email exists", json.toString());
                    finish(); //fire up an alarm
                    userWithTheSameEmail = true;
                    return json.getString(TAG_MESSAGE);
                } else if(success == 2) {
                    Log.d("Email doesnt exist", json.getString(TAG_MESSAGE));
                    userWithTheSameEmail = false;
                    return json.getString(TAG_MESSAGE);
                } else {
                    Log.d("Something happened", json.getString(TAG_MESSAGE));
                    userWithTheSameEmail = false;
                    return json.getString(TAG_MESSAGE);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;

        }

Here is the php script that accepts the json:

<?php

//load and connect to MySQL database stuff
require("config.inc.php");



if (!empty($_POST)) {
    //gets user's info based off of a username.

    $user_email = mysql_real_escape_string($_POST['user_email'];
    #$user_email_to_query = "\"". $user_email . "\"";
    $query = " 
            SELECT 
                user_email 
            FROM users 
            WHERE 
                user_email = '$user_email'
        ";

    if (mysql_num_rows($row) > 0) {
        $response["success"] = 1;
        $response["message"] = "User with such email exists";
    } else {
        $response["success"] = 2;
        $response["message"] = "User with such email doesnt exist. You can continue registering";   
    }
} else {
    die("Another brick in the wall");
}

Here is the config:

<?php 

    $username = "asd_asd"; 
    $password = "123123"; 
    $host = "localhost"; 
    $dbname = "asd_asd"; 


    $options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'); 


    try 
    { 

        $db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options); 
    } 
    catch(PDOException $ex) 
    { 

        die("Failed to connect to the database: " . $ex->getMessage()); 
    } 

    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 

    $db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); 


    if(function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc()) 
    { 
        function undo_magic_quotes_gpc(&$array) 
        { 
            foreach($array as &$value) 
            { 
                if(is_array($value)) 
                { 
                    undo_magic_quotes_gpc($value); 
                } 
                else 
                { 
                    $value = stripslashes($value); 
                } 
            } 
        } 

        undo_magic_quotes_gpc($_POST); 
        undo_magic_quotes_gpc($_GET); 
        undo_magic_quotes_gpc($_COOKIE); 
    } 


    header('Content-Type: text/html; charset=utf-8'); 
    session_start();

This is the table:

CREATE TABLE IF NOT EXISTS `users` (
  `user_id` int(11) NOT NULL AUTO_INCREMENT,
  `user_name` varchar(30) NOT NULL,
  `user_email` varchar(50) NOT NULL,
  `user_password` varchar(100) NOT NULL,
  `user_sex` varchar(10) NOT NULL,
  `user_avatar` varchar(100) DEFAULT NULL,
  `user_date_registered` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `user_last_seen` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  `user_points` int(11) NOT NULL,
  PRIMARY KEY (`user_id`),
  UNIQUE KEY `user_name` (`user_name`,`user_email`),
  KEY `user_id` (`user_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=3 ;

This is the error stack trace:

 D/Kylie(4458): [email protected]
 D/request!(4458): starting
Error parsing data org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
 threadid=9: thread exiting with uncaught exception (group=0x4001e578)
FATAL EXCEPTION: AsyncTask #1
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:200)
at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:274)
at java.util.concurrent.FutureTask.setException(FutureTask.java:125)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:308)
at java.util.concurrent.FutureTask.run(FutureTask.java:138)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
at java.lang.Thread.run(Thread.java:1019)
 Caused by: java.lang.NullPointerException
 net.asdasd.activities.Signup$CheckWetherAUserWithSuchEmailExists.doInBackground(Signup.java:585)
at net.asdasd.activities.Signup$CheckWetherAUserWithSuchEmailExists.doInBackground(Signup.java:1)
at android.os.AsyncTask$2.call(AsyncTask.java:185)
java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
... 4 more

If there is any more info that I am supposed to provide, Id be delighted to do so.

1 Answer 1

2

As far as I can see, nowhere in your PHP code do you actually do json OUTPUT. You generate an array, but don't do anything with it.

There should be a

if (!empty($_POST)) {
   ... blah blah blah...
   echo json_encode($response);   // <<---this is missing, apparently
} else {
   echo json_encode('Something blew up');
}

Also note how I've changed the else clause to also output JSON. If you're expecting JSON on the remote end, then everything you output should be JSON. Otherwise you'll try to decode something that ISN'T json and end up with an exception or at least undefined behavior.

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

1 Comment

Yes you are right :)) I never really learned php and now Im struggling. 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.