Just Simple Info

Pages

Android Simple Login with Php and Mysql



Android Simple Login with Php and Mysql
Must android application required connection in cloud server. So I wrote this simple code to share an idea on how to create simple login in android application connected to server using PHP and Mysql database and OkHttp library.


Below are the java code for android.

1. RegisterActivity.java


package blogspot.justsimpleinfo.com.simpleloginwithphpandmysql;

import android.content.Intent;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class RegisterActivity extends AppCompatActivity implements View.OnClickListener {

    Button mRegisterBtn;
    Button mLoginBtn;

    EditText mNameEditText;
    EditText mUserEditText;
    EditText mPasswordEditText;
    EditText mPasswordEditTextValidation;

    String mName;
    String mUsername;
    String mPassword;
    String mPasswordValidation;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mRegisterBtn = this.findViewById(R.id.register_button);
        mLoginBtn = this.findViewById(R.id.login_button);

        mNameEditText = this.findViewById(R.id.input_name);
        mUserEditText = this.findViewById(R.id.input_username);
        mPasswordEditText = this.findViewById(R.id.input_password);
        mPasswordEditTextValidation = this.findViewById(R.id.input_password_validation);


        mRegisterBtn.setOnClickListener(this);
        mLoginBtn.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        
        mName = mNameEditText.getText().toString().trim();
        mUsername = mUserEditText.getText().toString().trim();
        mPassword = mPasswordEditText.getText().toString().trim();
        mPasswordValidation = mPasswordEditTextValidation.getText().toString();

        switch (v.getId()){
            case R.id.register_button:


                if(mName.length() <=0){

                    Toast.makeText(this, "Name is require "+mName, Toast.LENGTH_SHORT).show();
                    return;

                }

                if(mUsername.length() <=0){

                    Toast.makeText(this, "Username is require", Toast.LENGTH_SHORT).show();
                    return;
                }

                if(mPassword.length() <=0){
                    Toast.makeText(this, "Password is require", Toast.LENGTH_SHORT).show();
                    return;
                }

                if(!mPassword.equals(mPasswordValidation)){
                    Toast.makeText(this, "Password not match.", Toast.LENGTH_SHORT).show();
                    return;
                }

                new ServerConnectionUtils(this,ServerConnectionUtils.REGISTER_ACTION,mName,mUsername,mPassword).execute();
                break;
            case R.id.login_button:
                Intent loginIntent = new Intent(this.getApplicationContext(),LoginActivity.class);
                startActivity(loginIntent);
                this.finish();
                break;
            default:
        }

    }
}


2. LoginActivity.java


package blogspot.justsimpleinfo.com.simpleloginwithphpandmysql;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class LoginActivity extends AppCompatActivity implements View.OnClickListener, DialogInterface.OnClickListener {
    Button mLoginBtn;
    Button mGoToRegisterBtn;
    EditText mLoginUserNameInput;
    EditText mLoginPasswordInput;
    android.app.AlertDialog mAlertDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        this.checkIfAlreadyLogin();

        setContentView(R.layout.activity_login);

        mLoginBtn = findViewById(R.id.login_button);
        mGoToRegisterBtn = findViewById(R.id.go_to_register_button);
        mLoginUserNameInput = findViewById(R.id.login_username_input);
        mLoginPasswordInput = findViewById(R.id.login_password_input);

        mLoginBtn.setOnClickListener(this);
        mGoToRegisterBtn.setOnClickListener(this);

    }

    private void checkIfAlreadyLogin(){
        SharedPreferences sharedPreferences  =this.getSharedPreferences(Constant.SHARED_PREFERENCE_NAME,MODE_PRIVATE);
        boolean isLogin = sharedPreferences.getBoolean(Constant.IS_LOGIN,false);

        if(isLogin){

            Intent homeIntent = new Intent(this,HomeActivity.class);
            startActivity(homeIntent);
            finish();

        }

    }
    @Override
    public void onClick(View view) {

        switch (view.getId()){

            case R.id.go_to_register_button:

                Intent intent = new Intent(this,RegisterActivity.class);
                startActivity(intent);

                break;
            case R.id.login_button:
                this.login();
                break;
            default:

        };



    }

    @Override
    public void onClick(DialogInterface dialog, int which) {

        mAlertDialog.dismiss();

    }

    private void login(){
        String username = mLoginUserNameInput.getText().toString().trim();
        String password = mLoginPasswordInput.getText().toString().trim();

        if(username.length() <=0){

            mAlertDialog = new MessageAlertDialog(this,"Username require",false,this).show();

            return;
        }

        if(password.length() <=0){

            mAlertDialog = new MessageAlertDialog(this,"Password require",false,this).show();

            return;
        }

        new ServerConnectionUtils(this,ServerConnectionUtils.LOGIN_ACIONT,username,password).execute();
    }
}

3. HomeActivity.java



package blogspot.justsimpleinfo.com.simpleloginwithphpandmysql;

import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class HomeActivity extends AppCompatActivity implements View.OnClickListener {

    TextView mUserNameTextView;
    Button mLogoutButton;
    SharedPreferences mSharedPreferences;
    String mName = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mSharedPreferences = this.getSharedPreferences(Constant.SHARED_PREFERENCE_NAME,MODE_PRIVATE);
        mName = mSharedPreferences.getString(Constant.NAME,null);

        setContentView(R.layout.activity_home);

        mUserNameTextView = this.findViewById(R.id.username_textview);

        mLogoutButton = this.findViewById(R.id.logout_button);
        mLogoutButton.setOnClickListener(this);

        if(mName !=null){

            mUserNameTextView.setText(mName);
        }
    }

    @Override
    public void onClick(View view) {

        /**
         * logout
         */
        SharedPreferences.Editor editor = mSharedPreferences.edit();
        editor.putBoolean(Constant.IS_LOGIN, false);
        editor.putString(Constant.NAME,"");
        editor.commit();


        Intent loginIntent = new Intent(this,LoginActivity.class);
        startActivity(loginIntent);
        this.finish();


    }
}

3. ServerConnectionUtils.java



package blogspot.justsimpleinfo.com.simpleloginwithphpandmysql;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.util.Log;
import android.view.LayoutInflater;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by Lau-PC on 6/24/2018.
 */

public class ServerConnectionUtils extends AsyncTask<String,String,Boolean> implements DialogInterface.OnClickListener {


    final static int REGISTER_ACTION = 1;
    final static int LOGIN_ACIONT = 2;

    Context mContext;


    int mAction;
    String mName;
    String mUsername;
    String mPassword;

    String mServerErrorMessage = "";
    String mServerMessage = "";
    boolean mIsSuccess = false;

    AlertDialog mMessageAlertDialog;
    LoadingDialog mLoadingDialog;
    SharedPreferences mSharedPreferences;


    ServerConnectionUtils(Context context,int action,String name,String username,String password){

        mContext = context;
        mAction = action;
        mName = name;
        mUsername = username;
        mPassword = password;

        mSharedPreferences = context.getSharedPreferences(Constant.SHARED_PREFERENCE_NAME,Context.MODE_PRIVATE);
        mLoadingDialog = new LoadingDialog(context,"Registering... Please wait...");
    }

    ServerConnectionUtils(Context context,int action,String username,String password){
        mContext = context;
        mAction = action;
        mUsername = username;
        mPassword = password;
        mSharedPreferences = context.getSharedPreferences(Constant.SHARED_PREFERENCE_NAME,Context.MODE_PRIVATE);
        mLoadingDialog = new LoadingDialog(context,"Checking... Please wait...");
    }


    @Override
    protected void onPreExecute() {

        mLoadingDialog.show();

    }

    @Override
    protected Boolean doInBackground(String... strings) {

        if(mAction == REGISTER_ACTION){

            return register();

        }else{

            return login();

        }

    }

    @Override
    protected void onPostExecute(Boolean success) {

        mLoadingDialog.mAlertDialog.dismiss();

        if(success){
            mMessageAlertDialog = new MessageAlertDialog(mContext,mServerMessage,true,this).show();

        }else{

            mMessageAlertDialog =  new MessageAlertDialog(mContext,mServerErrorMessage,false,this).show();
        }

    }

    /**
     * registering function
     * @return
     */
    private boolean register(){

        OkHttpClient client = new OkHttpClient();


        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("name", mName)
                .addFormDataPart("username", mUsername)
                .addFormDataPart("password", mPassword)
                .build();

        Request request = new Request.Builder()
                .url(Constant.BASE_URL + Constant.REGISTER_URL)
                .post(requestBody)
                .build();

        try {

            Response response = client.newCall(request).execute();

            /**
             * get response body
             */
            String serverResponse = response.body().string();

            /**
             * convert response string to json object
             */
            JSONObject serverResponseJSON = new JSONObject(serverResponse);

            boolean isSuccessful = serverResponseJSON.getBoolean("success");

            if(isSuccessful){

                mIsSuccess = true;
                mServerMessage = serverResponseJSON.getString("message");

                /**
                 * save to shared pref
                 */
                SharedPreferences.Editor editor = mSharedPreferences.edit();
                editor.commit();

            }else{

                mIsSuccess = false;
                mServerErrorMessage = serverResponseJSON.getString("error_message");
            }


        } catch (IOException e) {
            e.printStackTrace();
            mServerErrorMessage = e.getMessage();
            mIsSuccess = false;
            return  mIsSuccess;

        } catch (JSONException e) {
            e.printStackTrace();
            mServerErrorMessage = e.getMessage();
            mIsSuccess = false;
            return  mIsSuccess;
        }


        return  mIsSuccess;
    }

    /**
     * login function
     * @return
     */
    private boolean login(){

        OkHttpClient client = new OkHttpClient();


        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("username", mUsername)
                .addFormDataPart("password", mPassword)
                .build();

        Request request = new Request.Builder()
                .url(Constant.BASE_URL + Constant.LOGIN_URL)
                .post(requestBody)
                .build();

        try {

            Response response = client.newCall(request).execute();
            String serverResponse = response.body().string();
           JSONObject serverResponseJSON = new JSONObject(serverResponse);



            boolean isSuccessful = serverResponseJSON.getBoolean("success");

            if(isSuccessful){

                mIsSuccess = true;
                mServerMessage = serverResponseJSON.getString("message");
                /**
                 * add to shared preference
                 */
                SharedPreferences.Editor editor = mSharedPreferences.edit();
                editor.putBoolean(Constant.IS_LOGIN, true);
                editor.putString(Constant.NAME,serverResponseJSON.getJSONObject(Constant.USER_INFO).getString(Constant.NAME));

                editor.commit();

            }else{

                mIsSuccess = false;
                mServerErrorMessage = serverResponseJSON.getString("error_message");
            }


        } catch (IOException e) {
            e.printStackTrace();
            mServerErrorMessage = e.getMessage();
            mIsSuccess = false;
            return  mIsSuccess;

        } catch (JSONException e) {
            e.printStackTrace();
            mServerErrorMessage = e.getMessage();
            mIsSuccess = false;
            return  mIsSuccess;
        }


        return  mIsSuccess;
    }

    @Override
    public void onClick(DialogInterface dialog, int which) {

        mMessageAlertDialog.dismiss();

        if(mIsSuccess && mAction == REGISTER_ACTION){


            RegisterActivity registerActivity = (RegisterActivity) mContext;

            Intent intent = new Intent(mContext,LoginActivity.class);
            registerActivity.startActivity(intent);

            registerActivity.finish();

        }else if(mIsSuccess && mAction == LOGIN_ACIONT){

            LoginActivity mainActivity = (LoginActivity) mContext;

            Intent intent = new Intent(mContext,HomeActivity.class);
            mainActivity.startActivity(intent);

            mainActivity.finish();
        }


    }


    /**
     * Loading dialog
     */
    class LoadingDialog extends AlertDialog.Builder{

        ProgressBar mProgressBar;
        Context mContext;
        AlertDialog mAlertDialog;

        LinearLayout mLoadingLayout;

        LoadingDialog(Context context,String message) {
            super(context);

            mContext = context;
            this.setCancelable(false);


            mLoadingLayout = (LinearLayout) LayoutInflater.from(context).inflate(R.layout.progress_layout,null,false);
            init(message);

        }

        private void init(String message){

            TextView loadingTextView = mLoadingLayout.findViewById(R.id.loading_textview);
            loadingTextView.setText(message);
            this.setView(mLoadingLayout);
        }

        @Override
        public AlertDialog show() {
            mAlertDialog = super.show();

            return mAlertDialog;
        }
    }
}


4. AndroidManifiest.xml


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="blogspot.justsimpleinfo.com.simpleloginwithphpandmysql">

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".LoginActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".RegisterActivity" />
        <activity android:name=".HomeActivity"></activity>
    </application>

</manifest>

Add okHttp in gradle dependencies


compile 'com.squareup.okhttp3:okhttp:3.10.0'

Below are PHP codes.

1.DatabaseConnection.php


<?php

class DatabaseConnection{
    
    private $servername = 'localhost';
    private $username = 'root';
    private $password = '';
    private $database_name = 'sample';
    
    function __construct() {
        
        date_default_timezone_set('Asia/Manila');
        
    }
    
    function connect(){
        
        try {
            
            $connection = new PDO("mysql:host=$this->servername;dbname=$this->database_name", $this->username, $this->password);
            $connection->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_OBJ);
           
            
            return $connection;
            
        } catch (PDOException $e){
            
             die("Error: " . $e->getMessage());
            
        }
      
        
    }
    
}

?>


2.DatabaseUtil.php


<?php

class DatabaseUtil{
    
    function __construct() {
        
    }
    
 
    
    function registerNewUser($name,$username,$password,$connection){
        
        $response = array('success'=>false,'error_message'=>'','message'=>'');
        
        
        if($this->checkIfUserExists($username, $connection)){
            
            $response['success'] = false;
            $response['error_message'] = 'User not available. Please select another user';
            
            return $response;
            
        }
        
        
       $sql = 'INSERT INTO users (name,username,password,created,modified) VALUES (?,?,?,?,?)';
       $stmt = $connection->prepare($sql);
       
       if($stmt->execute([$name,$username,md5($password),date('Y-m-d H:i:s'),date('Y-m-d H:i:s')])){
           
           $response['success'] = true;
           $response['message'] = 'Successfully registered';
           return $response;
           
       }else{
           
           $response['success'] = false;
           $response['message'] = 'Failed to register. Please try again.';
           
           return $response;
           
       }
        
         
    
         
        
    }
    
    function checkIfUserExists($username,$connection){
        
        
        $sql = 'SELECT * FROM users WHERE username = ? LIMIT 1';
        $stmt = $connection->prepare($sql);
        
        $stmt->execute([$username]);
        
        if($stmt->rowCount() > 0){
            
            return true;
            
        }else{
            
            return false;
            
        }
        
         
        
        
    }
    
    function selectUser($username,$password, $connection){
        
        $response = array('valid_user'=>false,'User'=>array('username'=>'','name'=>''));
        
        $sql = 'SELECT * FROM users WHERE username = ? AND password = ? LIMIT 1';
        $stmt = $connection->prepare($sql);
        
        $stmt->execute([$username,md5($password)]);
        
       
        while ($row = $stmt->fetch()) {
            // do something with $row
            $response['valid_user'] = true;
            $response['User']['username'] = $row->username;
            $response['User']['name'] = $row->name;
            
        }

         
        
        return $response;
    }
    
   

    
}
?>


3. Register.php


<?php
require_once './DatabaseConnection.php';
require_once './DatabaseUtil.php';


$response = array(
    'success'=>false,
    'error_message'=>'',
    'message'=>''
);
if(!$_POST['name']){
    
    $response['success'] = true;
    $response['error_message'] = 'Name is require.';
    echo json_encode($response);
    return;
}
if(!$_POST['username']){
    
    $response['success'] = false;
    $response['error_message'] = 'Username is require.';
    echo json_encode($response);
    
    return;
}

if(!$_POST['password']){
    
    $response['success'] = false;
    $response['error_message'] = 'Password is require.';
    
    echo json_encode($response);
    
    return;
}


$DatabaseConnection = new DatabaseConnection();
$DatabaseUtil = new DatabaseUtil();
$registration_response = $DatabaseUtil->registerNewUser($_POST['name'], $_POST['username'], $_POST['password'], $DatabaseConnection->connect());

if($registration_response['success']){
    
    $response['success'] = true;
    $response['message'] = 'Successfully registered';
    
}else{
    
    $response['success'] = false;
    $response['error_message'] = $registration_response['error_message'];
    
}

echo json_encode($response);


?>


4. Login.php


<?php
require_once './DatabaseConnection.php';
require_once './DatabaseUtil.php';

$DatabaseConnection = new DatabaseConnection();
$DatabaseUtil = new DatabaseUtil();

$response = array(
    'success'=>false,
    'error_message'=>'',
    'message'=>'',
    'valid_user'=>false
);

if(!$_POST['username']){
    
    $response['success'] = false;
    $response['error_message'] = 'Username is require.';
    echo json_encode($response);
    
    return;
}

if(!$_POST['password']){
    
    $response['success'] = false;
    $response['error_message'] = 'Password is require.';
    
    echo json_encode($response);
    
    return;
    
}


$login_response = $DatabaseUtil->selectUser($_POST['username'],$_POST['password'], $DatabaseConnection->connect());


if($login_response['valid_user']){
    $response['success'] = true;
    $response['valid_user'] = true;
    $response['message'] = 'Successfully login';
    $response['UserInfo'] = $login_response['User'];

    
}else{
    
    $response['success'] = false;
    $response['valid_user'] = false;
    $response['error_message'] = 'Invalid username or password';
    
}

 echo json_encode($response);
    
    return;
?>

Here is the database table structure for users table


CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL,
  `name` varchar(50) NOT NULL,
  `username` varchar(50) NOT NULL,
  `password` varchar(50) NOT NULL,
  `created` datetime NOT NULL,
  `modified` datetime NOT NULL
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

Download source code here.

You can view some of my simple code snippet of:
  1. Android Scrolling Table with Fixed Header Column, Fixed Row , Header Spans and Pagination.
  2. Search Auto Suggest In Android (AutoCompleteTextView).
  3. Android Upload File To Server With Data.
  4. Save AES encypted object as file in android storage.
  5. Android TableLayout Example

No comments:

Post a Comment