title: Android JSON null pointer parsing
body: <p>I am trying to modify a bit of code from the working state to add more functionality to understand how the code is working. So basically I am trying to add additional functionality by giving the user an option to create a new bet. Before I modified it was working fine, by fine I mean the user was able to login and register with out anyproblem. Even the layout are also being displayed with out any problem.</p>
  
  <p>For comparison purpose I am going to add the same php files before and after version.</p>
  
  <p><strong>index.php</strong> <em>Before</em></p>
  
  <pre><code>&lt;?php
  
  /**
   * 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']) &amp;&amp; $_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" =&gt; $tag, "success" =&gt; 0, "error" =&gt; 0);
  
      // check for tag type
      if ($tag == 'login')
      {
          // Request type is check Login
          $email = $_POST['email'];
          $password = $_POST['password'];
  
          // check for user
          $user = $db-&gt;getUserByEmailAndPassword($email, $password);
          if ($user != false) 
          {
              // user found
              // echo json with success = 1
              $response["success"] = 1;
              $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"] = 1;
              $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'];
          $prefered_username = $_POST['preffered'];
  
          // check if user is already existed
          if ($db-&gt;isUserExisted($email)) {
              // user is already existed - error response
              $response["error"] = 2;
              $response["error_msg"] = "User already existed";
              echo json_encode($response);
          } 
          else 
          {
              // store user
              $user = $db-&gt;storeUser($name, $email, $password, $prefered_username);
              if ($user) 
              {
                  // user stored successfully
                  $response["success"] = 1;
                  $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"] = 1;
                  $response["error_msg"] = "Error occured in Registartion";
                  echo json_encode($response);
              }
          }
      }
       else
        {
          echo "Invalid Request";
      }
  } 
  else
   {
      echo "Access Denied";
  }
  
  
  ?&gt;
  </code></pre>
  
  <p><strong>index.php</strong> <em>After</em></p>
  
  <pre><code>  &lt;?php
  
  /**
   * 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']) &amp;&amp; $_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" =&gt; $tag, "success" =&gt; 0, "error" =&gt; 0);
  
      // check for tag type
      if ($tag == 'login')
      {
          // Request type is check Login
          $email = $_POST['email'];
          $password = $_POST['password'];
  
          // check for user
          $user = $db-&gt;getUserByEmailAndPassword($email, $password);
          if ($user != false) 
          {
              // user found
              // echo json with success = 1
              $response["success"] = 1;
              $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"] = 1;
              $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'];
          $prefered_username = $_POST['preffered'];
  
          // check if user is already existed
          if ($db-&gt;isUserExisted($email)) {
              // user is already existed - error response
              $response["error"] = 2;
              $response["error_msg"] = "User already existed";
              echo json_encode($response);
          } 
          else 
          {
              // store user
              $user = $db-&gt;storeUser($name, $email, $password, $prefered_username);
              if ($user) 
              {
                  // user stored successfully
                  $response["success"] = 1;
                  $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"] = 1;
                  $response["error_msg"] = "Error occured in Registartion";
                  echo json_encode($response);
              }
          }
      }
      /********************************************************************************************************************************************************/
       else if ($tag == 'betregister') 
       {
       /*
          // Request type is New Bet Register
          $bet_uid = $_POST['uid'];
          $bet_id = $_POST['betid'];        
          $bet_starttime = $_POST['start_time'];
          $bet_updated = $_POST['updated'];
          $bet_status = $_POST['bet_status'];
          $bet_users = $_POST['bet_users'];
          */
  
  
          $bet_name = $_POST['bet_name'];
          $bet_brief = $_POST['bet_brief'];
          $bet_description = $_POST['bet_description'];
          $bet_value = $_POST['bet_value'];
          $bet_endtime = $_POST['end_time'];
  
          // check if bet already exists
          if ($db-&gt;betExists($bet_name)) 
          {
              // bet already existed - error response
              $response["error"] = 2;
              $response["error_msg"] = "bet already existed";
              echo json_encode($response);
          } 
          else 
          {
              // create bet
              $bet = $db-&gt;createNewBet($bet_name, $bet_brief, $bet_description, $bet_value,$bet_endtime);
              if ($bet) 
              {
                  // bet created successfully
                  $response["success"] = 1;
                  $response["uid"] = $bet["uid"];
                  $response["betid"] = $bet["betid"];
                  $response["bet"]["bet_name"] = $bet["bet_name"];
                  $response["bet"]["bet_brief"] = $bet["bet_brief"];
                  $response["bet"]["bet_description"] = $bet["bet_description"];
                  echo json_encode($response);
              } 
              else
               {
                  // bet failed to store
                  $response["error"] = 1;
                  $response["error_msg"] = "Error occured in creating new bet";
                  echo json_encode($response);
              }
          }
      }
       else
        {
          echo "Invalid Request";
      }
  } 
  else
   {
      echo "Access Denied";
  }
  
  
  ?&gt;
  </code></pre>
  
  <p><strong>DBFunctions</strong> <em>Before</em></p>
  
  <pre><code>&lt;?php
  
  class DB_Functions {
  
      private $db;
  
      //put your code here
      // constructor
      function __construct() {
          require_once 'DB_Connect.php';
          // connecting to database
          $this-&gt;db = new DB_Connect();
          $this-&gt;db-&gt;connect();
      }
  
      // destructor
      function __destruct() {
  
      }
  
      /**
       * Storing new user
       * returns user details
       */
      public function storeUser($name, $email, $password, $preferred_name) {
          $uuid = uniqid('', true);
          $hash = $this-&gt;hashSSHA($password);
          $encrypted_password = $hash["encrypted"]; // encrypted password
          $salt = $hash["salt"]; // salt
          $result = mysql_query("INSERT INTO users(unique_id, name, email, encrypted_password, preffered_usrname, salt, created_at) VALUES('$uuid', '$name', '$email', '$encrypted_password', '$preferred_name', '$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 {
          echo mysql_error();
              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 &gt; 0) {
              $result = mysql_fetch_array($result);
              $salt = $result['salt'];
              $encrypted_password = $result['encrypted_password'];
              $hash = $this-&gt;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'");
          if(!$result){
              return false;
          }
  
          $no_of_rows = mysql_num_rows($result);
          if ($no_of_rows &gt; 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" =&gt; $salt, "encrypted" =&gt; $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;
      }
  
  }
  
  ?&gt;
  </code></pre>
  
  <p><strong>DBFunctions</strong> <em>After</em></p>
  
  <pre><code>    &lt;?php
  
  class DB_Functions {
  
      private $db;
  
      //put your code here
      // constructor
      function __construct() {
          require_once 'DB_Connect.php';
          // connecting to database
          $this-&gt;db = new DB_Connect();
          $this-&gt;db-&gt;connect();
      }
  
      // destructor
      function __destruct() {
  
      }
  
      /**
       * Storing new user
       * returns user details
       */
      public function storeUser($name, $email, $password, $preferred_name) 
      {
          $uuid = uniqid('', true);
          $hash = $this-&gt;hashSSHA($password);
          $encrypted_password = $hash["encrypted"]; // encrypted password
          $salt = $hash["salt"]; // salt
          $result = mysql_query("INSERT INTO users(unique_id, name, email, encrypted_password, preffered_usrname, salt, created_at) VALUES('$uuid', '$name', '$email', '$encrypted_password', '$preferred_name', '$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 {
          echo mysql_error();
              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 &gt; 0) {
              $result = mysql_fetch_array($result);
              $salt = $result['salt'];
              $encrypted_password = $result['encrypted_password'];
              $hash = $this-&gt;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'");
          if(!$result){
              return false;
          }
  
          $no_of_rows = mysql_num_rows($result);
          if ($no_of_rows &gt; 0) {
              // user existed 
              return true;
          } else {
              // user not existed
              return false;
          }
      }
  
       /**
       * Check user is betExists or not
       */
      public function isbetExists($betName) {
          $result = mysql_query("SELECT bet_name from bets WHERE bet_name = '$betName'");
          if(!$result){
              return false;
          }
  
          $no_of_rows = mysql_num_rows($result);
          if ($no_of_rows &gt; 0) {
              // bet exists 
              return true;
          } else {
              // bet doesnot exist
              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" =&gt; $salt, "encrypted" =&gt; $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;
      }
  
      /**
       * Adding new bet (my new code)
       */
       public function createNewBet($betname, $betbrief, $betdescription, $betvalue)
       {
          $uid = uniqid('',true);
          $bet_id = betid('',true);
          $result = mysql_query("INSERT INTO bets(bet_name,bet_brief,bet_description) VALUES('$betname','$betbrief','$betdescription')");
  
  
       }
       /*
           public function storeUser($name, $email, $password, $preferred_name) 
      {
          $uuid = uniqid('', true);
          $hash = $this-&gt;hashSSHA($password);
          $encrypted_password = $hash["encrypted"]; // encrypted password
          $salt = $hash["salt"]; // salt
          $result = mysql_query("INSERT INTO users(unique_id, name, email, encrypted_password, preffered_usrname, salt, created_at) VALUES('$uuid', '$name', '$email', '$encrypted_password', '$preferred_name', '$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 {
          echo mysql_error();
              return false;
          }
      }*/
  
  
  
  }
  
  ?&gt;
  </code></pre>
  
  <p>And finally this is the java class that my android app that is going to be utilizing the code.</p>
  
  <pre><code>package com.techiequickie.james.boadraf;
  
  import android.content.Intent;
  import android.os.AsyncTask;
  import android.os.Bundle;
  import android.support.v7.app.ActionBarActivity;
  import android.view.Gravity;
  import android.view.View;
  import android.widget.Button;
  import android.widget.EditText;
  import android.widget.SeekBar;
  import android.widget.Toast;
  
  import org.json.JSONException;
  import org.json.JSONObject;
  
  import databasehandler.DatabaseHandler;
  import databasehandler.UserFunctions;
  
  /**
   * Created by YP on 17-Nov-14.
   */
  public class newBet_activity extends ActionBarActivity
  {
      EditText inputBetname, inputBetbrief, inputBetdescription;
      SeekBar valueSeekbar; //= null;
      Button btn_newbet;
  
  
      // JSON Response node names
      private static String KEY_SUCCESS = "success";
      @SuppressWarnings("unused")
      private static String KEY_ERROR = "error";
      @SuppressWarnings("unused")
      private static String KEY_ERROR_MSG = "error_msg";
      //private static String KEY_UID = "uid";
      private static String KEY_BETNAME = "bet_name";
      private static String KEY_BETBRIEF = "bet_brief";
      private static String KEY_BETDESCRIPTION = "bet_description";
      private static String KEY_BETVALUE = "bet_value";
     // private static String KEY_CREATED_AT = "created_at";
  
  
      @Override
      protected void onCreate(Bundle savedInstanceState)
      {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.newbet);
          // Importing all assets like buttons, text fields
          inputBetname = (EditText) findViewById(R.id.betName_et);
          inputBetbrief = (EditText) findViewById(R.id.betBriefDescription_et);
          inputBetdescription = (EditText) findViewById(R.id.betDescription_et);
          btn_newbet = (Button) findViewById(R.id.bet_btn);
  
          //valueSeekbar = (SeekBar) findViewById(R.id.betValue_bar);
  
          /*
          valueSeekbar.setOnSeekBarChangeListener
         (
  
           new SeekBar.OnSeekBarChangeListener()
          {
              int progressChanged = 0;
  
              public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                  progressChanged = progress;
              }
  
              public void onStartTrackingTouch(SeekBar seekBar) {
                  // TODO Auto-generated method stub
              }
  
              public void onStopTrackingTouch(SeekBar seekBar) {
                  Toast.makeText(newBet_activity.this, "seek bar progress:" + progressChanged, Toast.LENGTH_SHORT).show();
              }
          }
         );*/
  
  
          btn_newbet.setOnClickListener(new View.OnClickListener()
           {
  
  
              public void onClick(View view)
              {
                  String betname = inputBetname.getText().toString();
                  String betBrief = inputBetbrief.getText().toString();
                  String betDescription = inputBetdescription.getText().toString();
                  //StringBuilder betValue = ((toString()) valueSeekbar.getProgress());
  
                  new BetRegisterTask().execute(betname,betBrief,betDescription);
              }
           }
          );
  
  
      }
  
  
          class BetRegisterTask extends AsyncTask&lt;String, Void, String&gt;
          {
  
              @Override
              protected String doInBackground(String... params)
              {
  
                  UserFunctions userFunction = new UserFunctions();
                  JSONObject json = userFunction.createBet(params[0], params[1], params[2]);
  
                  // check for login response
                  try
                  {
                      if (json.getString(KEY_SUCCESS) != null)
                      {
  
                          String res = json.getString(KEY_SUCCESS);
                          if (Integer.parseInt(res) == 1)
                          {
                              // user successfully registred
                              // Store user details in SQLite Database
                              DatabaseHandler db = new DatabaseHandler(getApplicationContext());
                              JSONObject json_user;
                              json_user = json.optJSONObject("user");
  
                              // Clear all previous data in database
                              userFunction.logoutUser(getApplicationContext());
                              db.newBet(json_user.getString(KEY_BETNAME), json_user.getString(KEY_BETBRIEF), json.getString(KEY_BETDESCRIPTION));
                              return "1";
  
                          }
  
                      }
                  } catch (JSONException e)
                  {
                      e.printStackTrace();
                  }
  
                  return "0";
              }
  
              @Override
              protected void onPostExecute(String s)
              {
                  super.onPostExecute(s);
                  if (s.equals("1"))
                  {
  
                      // Launch Dashboard Screen
                      Intent dashboard = new Intent(getApplicationContext(), Loginactivity.class);
                      // Close all views before launching Dashboard
                      dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                      startActivity(dashboard);
                      // Close Registration Screen
                      finish();
                      showToastforSucessfulBetCreation();
  
                  }
                  else
                  {
                      // Error in registration
                      //registerErrorMsg.setText("Error occurred in registration");
                      showToastforUnsucessfulBetCreation();
                  }
              }
          }
  
      public void showToastforSucessfulBetCreation() {
          Toast toast = Toast.makeText(this, "Registration Sucessfull", Toast.LENGTH_LONG);
          toast.setGravity(Gravity.BOTTOM, 0, 30);
          toast.show();
  
      }
  
  
      public void showToastforUnsucessfulBetCreation() {
          Toast toast = Toast.makeText(this, "Registration UnSucessfull", Toast.LENGTH_LONG);
          toast.setGravity(Gravity.BOTTOM, 0, 30);
          toast.show();
  
      }
  
  }
  </code></pre>
  
  <p>But for now I am NOT able to login to the app itself, which I was able to before.</p>
  
  <p>EDIT
  adding a dropbox link as exceeding the character limit
  <a href="https://www.dropbox.com/s/iszqh2mjw23kyvq/register_java_class.txt?dl=0" rel="nofollow">https://www.dropbox.com/s/iszqh2mjw23kyvq/register_java_class.txt?dl=0</a></p>