Wednesday, 2 March 2022

Create/develop simple login application in android using wamp server and MySQL  databases.

In this tutorial we will create a simple login application using wamp server and MySQL databases.
We will use Retrofit library for server communication. 

So lets start

1. Run wamp server and open phpMyAdmin home page






2. Create a databases and name it "simple_login_app_db"


 
3. Execute following query to create 'users' table
    CREATE TABLE IF NOT EXISTS `users` (
     id` int(11) NOT NULL AUTO_INCREMENT,
	`username` varchar(200) NOT NULL,
	`password` text NOT NULL,
	 PRIMARY KEY (`id`)
     ) 
4. Insert a record

5. Now go to 'C:\wamp64\www', create a project/folder and give name 'simple_login_app'

Create two .php files, connect.php & login.php

   i. Copy below code in connect.php file 


	ini_set('display_errors',0);
    date_default_timezone_set('Asia/Karachi');
    $servername = "localhost";
    $username = "root";
    $password = "";
    try {
        $conn = new PDO("mysql:host=$servername;dbname=simple_login_app_db", $username, $password);
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    }catch(PDOException $e){
        echo "Connection failed: " . $e->getMessage();
    }
    ii. Copy below code in login.php
php 
header('Content-type: application/json');
include_once('connect.php');
$response=array();

if ( isset($_REQUEST['username']) & isset($_REQUEST['password']) ){

  $username = $_REQUEST['username'];
  $password = md5( $_REQUEST['password'] ); 
    
  $stmt = $conn->prepare("SELECT * FROM `users`  WHERE username='$username' AND  password = '$password'  ");  
  
      $stmt->execute();
      $stmt->setFetchMode(PDO::FETCH_OBJ); 
      $row = $stmt->fetch();

      if($row->id != ""){

        $response['id']= $row->id;
        $response['username']= $row->username;
    
        $response["success"] = 1;
        $response["message"] = "Logged in successfully";
        
      }else{
        $response["success"] = 0;
        $response["message"] = "Invalid username or password"; 
      }
  
}else{    
    $response["success"] = 0;
    $response["message"] = "Required field(s) is missing";
}
echo json_encode($response);
6. Create a project in android studio and give name "SimpleLoginApp".

7. Rename MainActivity to LoginActivity (Optional) and past below code.

import android.os.Bundle
import android.util.Log
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.AppCompatButton
import com.google.android.material.textfield.TextInputLayout
import com.google.gson.JsonObject
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class LoginActivity : AppCompatActivity() {

    private lateinit var userNameField: TextInputLayout
    private lateinit var passwordField: TextInputLayout
    private lateinit var loginBtn: AppCompatButton

    private lateinit var messageFromServerTextView: TextView
    private var messageFromServer = ""

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.login_activity)

        messageFromServerTextView = findViewById(R.id.message_from_server)

        userNameField = findViewById(R.id.username)
        passwordField = findViewById(R.id.password)
        loginBtn = findViewById(R.id.login_btn)

        loginBtn!!.setOnClickListener {
            loginFunc(userNameField.editText!!.text.toString(),   passwordField.editText!!.text.toString())
        }
    }

    private fun loginFunc(username: String, password: String) {

        val userServiceInterface = RetrofitClient.getRetrofitInstance().create(UserServiceInterface::class.java)
        val  call = userServiceInterface.login(username, password)

        call?.enqueue(object : Callback {
            override fun onResponse(call: Call, response: Response) {
               if (response.isSuccessful) {
                   val jsonObject =  response.body()!!.asJsonObject
                   messageFromServer = jsonObject.get("message").toString()
                    //if (jsonObject.get("message").toString().contains("Logged in successfully")){ }
               }else {
                   messageFromServer = response.message().toString()
               }
               messageFromServerTextView.text = messageFromServer
               Toast.makeText(this@LoginActivity, messageFromServer, Toast.LENGTH_LONG).show()
               Log.i("server response", messageFromServer)
            }
            override fun onFailure(call: Call, t: Throwable) {
               messageFromServer = t.message.toString()
               messageFromServerTextView.text = messageFromServer
               Toast.makeText(this@LoginActivity, messageFromServer, Toast.LENGTH_LONG).show()
               Log.i("server response", messageFromServer)
            }
        })

    }
}
8. Create a class "RetrofitClient" and copy below code

import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class RetrofitClient {
    public static final String URL_LOGIN = "http://192.168.00.00/simple_login_app/";
    private static Retrofit retrofit = null;
    public static Retrofit getRetrofitInstance(){
        if(retrofit == null){
            retrofit = new Retrofit.Builder()
            .baseUrl(URL_LOGIN)
            .addConverterFactory(GsonConverterFactory.create())
            .build();
        }
        return retrofit;
    }
}
9. Create an interface "UserServiceInterface" and copy below code.
import com.google.gson.JsonObject;
import retrofit2.Call;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.POST;

public interface UserServiceInterface {
   @FormUrlEncoded
   @POST("login.php")
   Call login(
     @Field("username") String username,
     @Field("password") String password
   );
}
10. Open 'manifest' file and add following permission.
 uses-permission android:name="android.permission.INTERNET" 
11. Open 'build.gradle' file and add following dependencies.

implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
implementation 'com.google.code.gson:gson:2.8.6'
12. Go to layout folder and copy below code in the login_activity.xml.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".LoginActivity"
    >
        <TextView
            android:layout_gravity="center_horizontal"
            android:layout_marginTop="50dp"
            android:textStyle="bold"
            android:textSize="32sp"
            android:text="Simple Login App"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>

        <LinearLayout
            android:layout_marginTop="20dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:padding="30dp">

            <com.google.android.material.textfield.TextInputLayout
                android:id="@+id/username"
                style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="Username">

                <com.google.android.material.textfield.TextInputEditText
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:inputType="text" />
            </com.google.android.material.textfield.TextInputLayout>

            <com.google.android.material.textfield.TextInputLayout
                android:id="@+id/password"
                android:layout_marginTop="10dp"
                style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="Password">

                <com.google.android.material.textfield.TextInputEditText
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:inputType="textPassword" />

            </com.google.android.material.textfield.TextInputLayout>

            <androidx.appcompat.widget.AppCompatButton
                android:id="@+id/login_btn"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="20dp"
                android:background="@color/purple_500"
                android:textColor="@color/white"
                android:text="Login" />

    </LinearLayout>

    <TextView
       android:layout_margin="10dp"
        android:id="@+id/message_from_server"
        android:layout_gravity="center_horizontal"
        android:textSize="24dp"
        android:layout_marginTop="30dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

</LinearLayout>

Now your code is ready. Run it. Following UI should be shown.

Note: Replace IP address in RetrofitClient class with your machine address.

Watch the video for practical implementation


That's it. Thank you