title: registration on android and saving on database using PHP, MySQL and SQLite
body: <p>many may have ask about this question but i want to ask it anyway..im doing a tutorial <a href="http://www.androidhive.info/2012/01/android-login-and-registration-with-php-mysql-and-sqlite/" rel="nofollow noreferrer">here</a> and i kind of remade the whole thing i made the user register name email password and confirm password...but i get this error here <strong>05-08 01:13:42.638: W/System.err(3295): org.json.JSONException: No value for cpassword</strong> after changing the code i then get this error <img src="https://i.stack.imgur.com/uFfqe.png" alt="error"></p>
  
  <p><strong><em>any ideas are welcome i also want to know <code>how to get the original password back</code></em></strong> </p>
  
  <p>java code </p>
  
  <p>database handler</p>
  
  <pre><code>public class DatabaseHandler extends SQLiteOpenHelper {
  
      // All Static variables
      // Database Version
      private static final int DATABASE_VERSION = 5;
  
      // Database Name
      private static final String DATABASE_NAME = "user_api";
  
      // Login table name
      private static final String USER = "user";
  
      // Login Table Columns names
      private static String USER_ID = "id";
      private static String USER_UID = "uid";
      private static String USER_NAME = "name";
      private static String USER_EMAIL = "email";
      private static String USER_PASSWORD = "cpassword";
  
      public DatabaseHandler(Context context) {
          super(context, DATABASE_NAME, null, DATABASE_VERSION);
      }
  
      // Creating Tables
      @Override
      public void onCreate(SQLiteDatabase db) {
          String CREATE_LOGIN_TABLE = "CREATE TABLE " + USER + "("
                  + USER_ID + " INTEGER PRIMARY KEY," 
                  + USER_NAME + " TEXT,"
                  + USER_EMAIL + " TEXT UNIQUE,"
                  + USER_UID + " TEXT,"
                  + USER_PASSWORD + " TEXT" + ")";
          db.execSQL(CREATE_LOGIN_TABLE);
      }
  
      // Upgrading database
      @Override
      public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
          // Drop older table if existed
          db.execSQL("DROP TABLE IF EXISTS " + USER);
  
          // Create tables again
          onCreate(db);
      }
  
      /**
       * Storing user details in database
       * */
      public void addUser(String name, String email, String uid, String cpassword) {
          SQLiteDatabase db = this.getWritableDatabase();
  
          ContentValues values = new ContentValues();
          values.put(USER_NAME, name); // Name
          values.put(USER_EMAIL, email); // Email
          values.put(USER_UID, uid); // Email
          values.put(USER_PASSWORD,cpassword); // Password
  
          // Inserting Row
          db.insert(USER, null, values);
          db.close(); // Closing database connection
      }
  
      /**
       * Getting user data from database
       * */
      public HashMap&lt;String, String&gt; getUserDetails(){
          HashMap&lt;String,String&gt; user = new HashMap&lt;String,String&gt;();
          String selectQuery = "SELECT  * FROM " + USER;
  
          SQLiteDatabase db = this.getReadableDatabase();
          Cursor cursor = db.rawQuery(selectQuery, null);
          // Move to first row
          cursor.moveToFirst();
          if(cursor.getCount() &gt; 0){
              user.put("name", cursor.getString(1));
              user.put("email", cursor.getString(2));
              user.put("uid", cursor.getString(3));
              user.put("password", cursor.getString(4));
              Log.e(cursor.getString(1)+cursor.getString(2), cursor.getString(3)+cursor.getString(4));
          }
          cursor.close();
          db.close();
          // return user
          return user;
      }
  
      /**
       * Getting user login status
       * return true if rows are there in table
       * */
      public int getRowCount() {
          String countQuery = "SELECT  * FROM " + USER;
          SQLiteDatabase db = this.getReadableDatabase();
          Cursor cursor = db.rawQuery(countQuery, null);
          int rowCount = cursor.getCount();
          db.close();
          cursor.close();
  
          // return row count
          return rowCount;
      }
  
      /**
       * Re crate database
       * Delete all tables and create them again
       * */
      public void resetTables(){
          SQLiteDatabase db = this.getWritableDatabase();
          // Delete All Rows
          db.delete(USER, null, null);
          db.close();
      }
  
  }
  </code></pre>
  
  <p>register</p>
  
  <pre><code>public class RegisterActivity extends Activity {
  
      Button Submit;
      EditText Name,Email,Password,ConfirmPassword;
  
      private static String USER_SUCCESS = "success";
      private static String USER_ERROR = "error";
      private static String USER_ERROR_MSG = "error_msg";
      // JSON Response node names
          private static String USER_ID = "id";
          private static String USER_UID = "uid";
          private static String USER_NAME = "name";
          private static String USER_EMAIL = "email";
          private static String USER_PASSWORD = "cpassword";
      @Override
      protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_register);
  
          Name = (EditText) findViewById(R.id.Name);
          Email = (EditText) findViewById(R.id.Email);
          Password = (EditText) findViewById(R.id.Password);
          ConfirmPassword = (EditText) findViewById(R.id.ConfirmPassword);
          Submit = (Button) findViewById(R.id.Submit);
  
          Submit.setOnClickListener(new OnClickListener() {
  
              @Override
              public void onClick(View v) {
                  // TODO Auto-generated method stub
  
                  Toast toast = Toast.makeText(RegisterActivity.this, "Submit", Toast.LENGTH_SHORT);
                  toast.setGravity(Gravity.CENTER|Gravity.CENTER, 0, 0);
                  toast.show();
                  String name = Name.getText().toString();
                  String email = Email.getText().toString();
                  String password = Password.getText().toString();
                  String cpassword = ConfirmPassword.getText().toString();
                   String EMAIL_REGEX = "^[\\w-_\\.+]*[\\w-_\\.]\\@([\\w]+\\.)+[\\w]+[\\w]$";
                  if (email.matches(EMAIL_REGEX)){
                      if(password.matches(cpassword)){
                          new MyAsyncTask().execute(name, email,cpassword);
                      }else{
                          Toast ief = Toast.makeText(RegisterActivity.this, "Password Does Not Match", Toast.LENGTH_SHORT);
                          ief.setGravity(Gravity.CENTER|Gravity.CENTER, 0, 0);
                          ief.show();
                      }
  
                  }else{
                      Toast ief = Toast.makeText(RegisterActivity.this, "Incorrect Email format", Toast.LENGTH_SHORT);
                      ief.setGravity(Gravity.CENTER|Gravity.CENTER, 0, 0);
                      ief.show();
                  }
  
              }
          });
      }
      private class MyAsyncTask extends AsyncTask&lt;String, Void ,JSONObject&gt; {
  
          protected JSONObject doInBackground(String... params) {
  
          UserFunctions userFunction = new UserFunctions();
          if (params.length != 3)
          return null;
  
          JSONObject json = userFunction.registerUser(params[0], params[1], params[2]);
          return json;
          }
  
          protected void onPostExecute(JSONObject json) {
              try {
                  if (json != null &amp;&amp; json.getString(USER_SUCCESS) != null) {
                      String res = json.getString(USER_SUCCESS); 
                      if(Integer.parseInt(res) == 1){
                          // user successfully registred
                          // Store user details in SQLite Database
  
                          DatabaseHandler db = new DatabaseHandler(getApplicationContext());
                          JSONObject json_user = json.getJSONObject("user");
                          Log.e(json_user.toString(), "Password no value");
                          // Clear all previous data in database
                          UserFunctions userFunction = new UserFunctions();
                          userFunction.logoutUser(getApplicationContext());
                          db.addUser(json_user.getString(USER_NAME), json_user.getString(USER_EMAIL),json.getString(USER_UID), json.getString(USER_PASSWORD));                        
  
  
                          // Launch Dashboard Screen
                          Intent dashboard = new Intent(getApplicationContext(), HomeActivity.class);
                          // Close all views before launching Dashboard
                          //dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                          startActivity(dashboard);
                          // Close Registration Screen
                          finish();
                      }else{
                          // Error in registration
                          Toast ief = Toast.makeText(RegisterActivity.this, "User Email is Already in Use", Toast.LENGTH_SHORT);
                          ief.setGravity(Gravity.CENTER|Gravity.CENTER, 0, 0);
                          ief.show();
                      }
                  }
              } catch (JSONException e) {
                  e.printStackTrace();
              }
          }
          }
  }
  </code></pre>
  
  <p>php </p>
  
  <p>index.php</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["user_uid"];
              $response["user"]["name"] = $user["user_name"];
              $response["user"]["email"] = $user["user_email"];
              $response["user"]["password"] = $user["user_password"];
              echo json_encode($response);
          } else {
              // user not found
              // echo json with error = 1
              $response["error"] = 1;
              $response["error_msg"] = "Incorrect 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-&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);
              if ($user) {
                  // user stored successfully
                  $response["success"] = 1;
                  $response["uid"] = $user["user_uid"];
                  $response["user"]["name"] = $user["user_name"];
                  $response["user"]["email"] = $user["user_email"];
                  $response["user"]["password"] = $user["user_password"];
                  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>DB_Functions.php</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) {
          $uid = uniqid('', true);
          $hash = $this-&gt;hashSSHA($password);
          $encrypted_password = $hash["encrypted"]; // encrypted password
          $salt = $hash["salt"]; // salt
          $result = mysql_query("INSERT INTO user_tbl(user_uid, user_name, user_email, user_password, user_salt) VALUES('$uid', '$name', '$email', '$encrypted_password', '$salt')");
          // check for successful store
          if ($result) {
              // get user details 
              $id = mysql_insert_id(); // last inserted id
              $result = mysql_query("SELECT * FROM user_tbl WHERE user_id = $id");
              // 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 user_tbl WHERE user_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['user_salt'];
              $encrypted_password = $result['user_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 user_email from user_tbl WHERE user_email = '$email'");
          $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>