0

Android Volley User Login System using PHP MySQL Tutorial

How to create user Login application with Volley library and open profile activity after successfully login.

In our previous tutorial we have discussed about User registration using Volley library on server.  Now this is the 2nd part of tutorial. In this tutorial we would going to learn about How to login after successfully registration. By using both tutorials you can easily develop your own Volley User Login and registration system.

Before getting started please also read my previous tutorial about User registration using Volley library . By reading this tutorial you can actually know how we are registering user information like name, email and password on our hosting server using PHP MySQL script . We are using same MySQL table for both login and registration. So when user successfully complete the registration process he can login.

What we are doing in this project Volley User Login :

There are two activities in this project. First is MainActivity, second is ProfileActivity. The MainActivity contain functionality of user login and the ProfileActivity opens when user successfully login.

Activities in this project :

  • MainActivity.java
  • ProfileActivity.java

Layout files in this project :

  • activity_main.xml
  • activity_profile.xml

Follow the below steps for Android Volley User Login System :-

1. Read my User Registration using Volley Tutorial. This will explain how user registration would complete.

2. Create a database in PhpMyAdmin.

3. Create a new table in database name as User_Details_Table with four columns id, User_Email, User_Password, User_Full_Name. Set id as primary key.

 

4. Upload the below PHP script with your database configuration. In DatabaseConfig.php file you have to set your server PhpMyAdmin HostName, Host Password, Host User, Database Name.

Code for DatabaseConfig.php file.

<?php

//Define your host here.
$HostName = "localhost";

//Define your database username here.
$HostUser = "id302300_android_examples_data_user";

//Define your database password here.
$HostPass = "1234567890";

//Define your database name here.
$DatabaseName = "id302300_android_examples";

?>

Code for user_login.php file.

<?php

if($_SERVER['REQUEST_METHOD']=='POST'){

include 'DatabaseConfig.php';

$con = mysqli_connect($HostName,$HostUser,$HostPass,$DatabaseName);

$email = $_POST['User_Email'];
$password = $_POST['User_Password'];

$Sql_Query = "select * from User_Details_Table where User_Email = '$email' and User_Password = '$password' ";

$check = mysqli_fetch_array(mysqli_query($con,$Sql_Query));

if(isset($check)){

echo "Data Matched";
}
else{
echo "Invalid Username or Password Please Try Again !";
}

}else{
echo "Check Again";
}
mysqli_close($con);

?>

 

5. Start a new android application development project.

6. Add internet permission in AndroidManifest.xml file.

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

 

7. Add compile ‘com.android.volley:volley:1.0.0’ library file in build.gradle(Module:app) file. So open it.

build-gradle

 

8. Add compile ‘com.android.volley:volley:1.0.0’ inside dependencies block.

 

9. Create two EditText and one Button in activity_main.xml layout file

<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/textView"
    android:textSize="20dp"
    android:textStyle="bold"
    android:text="Volley User Login System"
    android:gravity="center"
    android:layout_marginTop="20dp"/>

<EditText
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:hint="Enter Your Email"
    android:gravity="center"
    android:id="@+id/editText_Email"
    android:layout_below="@+id/textView"
    android:layout_marginTop="20dp"/>

<EditText
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:hint="Enter Your Email"
    android:gravity="center"
    android:id="@+id/editText_Password"
    android:inputType="textPassword"
    android:layout_below="@+id/editText_Email"
    android:layout_marginTop="20dp"/>

<Button
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="CLICK HERE TO LOGIN"
    android:id="@+id/button_login"
    android:layout_below="@id/editText_Password"
    android:layout_marginTop="20dp"/>

10. Create EditText, Button, RequestQueue, String, ProgressDialog, Boolean objects in MainActivity.java file.

// Creating EditText.
EditText Email, Password;

// Creating button;
Button LoginButton;

// Creating Volley RequestQueue.
RequestQueue requestQueue;

// Create string variable to hold the EditText Value.
String EmailHolder, PasswordHolder;

// Creating Progress dialog.
ProgressDialog progressDialog;

// Storing server url into String variable.
String HttpUrl = "https://android-examples.000webhostapp.com/user_login.php";

Boolean CheckEditText;

 

11. Assign ID’s to all of them.

// Assigning ID's to EditText.
Email = (EditText) findViewById(R.id.editText_Email);

Password = (EditText) findViewById(R.id.editText_Password);

// Assigning ID's to Button.
LoginButton = (Button) findViewById(R.id.button_login);

// Creating Volley newRequestQueue .
requestQueue = Volley.newRequestQueue(MainActivity.this);

// Assigning Activity this to progress dialog.
progressDialog = new ProgressDialog(MainActivity.this);

 

12. Create function to check EditText is empty or not.

public void CheckEditTextIsEmptyOrNot() {

    // Getting values from EditText.
    EmailHolder = Email.getText().toString().trim();
    PasswordHolder = Password.getText().toString().trim();

    // Checking whether EditText value is empty or not.
    if (TextUtils.isEmpty(EmailHolder) || TextUtils.isEmpty(PasswordHolder)) {

        // If any of EditText is empty then set variable value as False.
        CheckEditText = false;

    } else {

        // If any of EditText is filled then set variable value as True.
        CheckEditText = true;
    }
}

13. Adding click listener to Login button.

// Adding click listener to button.
LoginButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {

      
    }
});

14. Creating UserLogin function.

// Creating user login function.
public void UserLogin() {

    // Showing progress dialog at user registration time.
    progressDialog.setMessage("Please Wait");
    progressDialog.show();

    // Creating string request with post method.
    StringRequest stringRequest = new StringRequest(Request.Method.POST, HttpUrl,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String ServerResponse) {

                    // Hiding the progress dialog after all task complete.
                    progressDialog.dismiss();

                    // Matching server responce message to our text.
                    if(ServerResponse.equalsIgnoreCase("Data Matched")) {

                        // If response matched then show the toast.
                        Toast.makeText(MainActivity.this, "Logged In Successfully", Toast.LENGTH_LONG).show();

                        // Finish the current Login activity.
                        finish();

                        // Opening the user profile activity using intent.
                        Intent intent = new Intent(MainActivity.this, ProfileActivity.class);

                        // Sending User Email to another activity using intent.
                        intent.putExtra("UserEmailTAG", EmailHolder);

                        startActivity(intent);
                    }
                    else {

                        // Showing Echo Response Message Coming From Server.
                        Toast.makeText(MainActivity.this, ServerResponse, Toast.LENGTH_LONG).show();

                    }


                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {

                    // Hiding the progress dialog after all task complete.
                    progressDialog.dismiss();

                    // Showing error message if something goes wrong.
                    Toast.makeText(MainActivity.this, volleyError.toString(), Toast.LENGTH_LONG).show();
                }
            }) {
        @Override
        protected Map<String, String> getParams() {

            // Creating Map String Params.
            Map<String, String> params = new HashMap<String, String>();

            // Adding All values to Params.
            // The firs argument should be same sa your MySQL database table columns.
            params.put("User_Email", EmailHolder);
            params.put("User_Password", PasswordHolder);

            return params;
        }

    };

}

 

15. Calling RequestQueue to call the stringRequest method in UserRegistration() function.

// Creating RequestQueue.
RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);

// Adding the StringRequest object into requestQueue.
requestQueue.add(stringRequest);

 

16. Calling UserLogin() and CheckEditTextIsEmptyOrNot() method inside the button click scope with IF else condition So if the EditText is empty then it simply shows a toast message on screen.

// Adding click listener to button.
LoginButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {

        CheckEditTextIsEmptyOrNot();

        if (CheckEditText) {

            UserLogin();

        } else {

            Toast.makeText(MainActivity.this, "Please fill all form fields.", Toast.LENGTH_LONG).show();

        }

    }
});

 

17. Adding New activity in your project named as ” ProfileActivity “. If you don’t know how to add activity in existing Android Studio project then read my this tutorial. This would help you.

 

18. Adding One TextView and one Button in activity_profile.xml file.

<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/TextViewUserEmail"
    android:gravity="center"
    android:textStyle="bold"
    android:textSize="18dp"
    android:text="Welcome - "
    android:layout_marginTop="50dp"
    />

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="LOGOUT"
        android:id="@+id/button_logout"
        android:layout_below="@+id/TextViewUserEmail"
        android:layout_marginTop="50dp"/>

 

19. Add TextView and button objects in ProfileActivity.java file.

TextView textView;
Button logout;

 

20. Assign ID’s to them.

// Assign ID's to textview and button.
textView = (TextView)findViewById(R.id.TextViewUserEmail);
logout = (Button)findViewById(R.id.button_logout);

 

21. Receive User Email coming form Login activity using Intent and store into string.

// Receiving value into activity using intent.
String TempHolder = getIntent().getStringExtra("UserEmailTAG");

 

22. Setting up received value into TextView.

// Setting up received value into TextView.
textView.setText(textView.getText() + TempHolder);

 

23. Adding click listener to Logout button.

// Adding click listener to logout button.
logout.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {

        // Showing Echo Response Message Coming From Server.
        Toast.makeText(ProfileActivity.this, "Logged Out Successfully", Toast.LENGTH_LONG).show();

        // Closing the current activity.
        finish();

        // Redirect to Main Login activity after log out.
        Intent intent = new Intent(ProfileActivity.this, MainActivity.class);

        startActivity(intent);

    }
});

Complete Source code for Volley User Login:

Code for MainActivity.java file.

package com.android_examples.volleyuserlogin_android_examplescom;
import android.app.ProgressDialog;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import java.util.HashMap;
import java.util.Map;

public class MainActivity extends AppCompatActivity {

    // Creating EditText.
    EditText Email, Password;

    // Creating button;
    Button LoginButton;

    // Creating Volley RequestQueue.
    RequestQueue requestQueue;

    // Create string variable to hold the EditText Value.
    String EmailHolder, PasswordHolder;

    // Creating Progress dialog.
    ProgressDialog progressDialog;

    // Storing server url into String variable.
    String HttpUrl = "https://android-examples.000webhostapp.com/user_login.php";

    Boolean CheckEditText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Assigning ID's to EditText.
        Email = (EditText) findViewById(R.id.editText_Email);

        Password = (EditText) findViewById(R.id.editText_Password);

        // Assigning ID's to Button.
        LoginButton = (Button) findViewById(R.id.button_login);

        // Creating Volley newRequestQueue .
        requestQueue = Volley.newRequestQueue(MainActivity.this);

        // Assigning Activity this to progress dialog.
        progressDialog = new ProgressDialog(MainActivity.this);

        // Adding click listener to button.
        LoginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                CheckEditTextIsEmptyOrNot();

                if (CheckEditText) {

                    UserLogin();

                } else {

                    Toast.makeText(MainActivity.this, "Please fill all form fields.", Toast.LENGTH_LONG).show();

                }

            }
        });

    }

    // Creating user login function.
    public void UserLogin() {

        // Showing progress dialog at user registration time.
        progressDialog.setMessage("Please Wait");
        progressDialog.show();

        // Creating string request with post method.
        StringRequest stringRequest = new StringRequest(Request.Method.POST, HttpUrl,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String ServerResponse) {

                        // Hiding the progress dialog after all task complete.
                        progressDialog.dismiss();

                        // Matching server responce message to our text.
                        if(ServerResponse.equalsIgnoreCase("Data Matched")) {

                            // If response matched then show the toast.
                            Toast.makeText(MainActivity.this, "Logged In Successfully", Toast.LENGTH_LONG).show();

                            // Finish the current Login activity.
                            finish();

                            // Opening the user profile activity using intent.
                            Intent intent = new Intent(MainActivity.this, ProfileActivity.class);

                            // Sending User Email to another activity using intent.
                            intent.putExtra("UserEmailTAG", EmailHolder);

                            startActivity(intent);
                        }
                        else {

                            // Showing Echo Response Message Coming From Server.
                            Toast.makeText(MainActivity.this, ServerResponse, Toast.LENGTH_LONG).show();

                        }


                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {

                        // Hiding the progress dialog after all task complete.
                        progressDialog.dismiss();

                        // Showing error message if something goes wrong.
                        Toast.makeText(MainActivity.this, volleyError.toString(), Toast.LENGTH_LONG).show();
                    }
                }) {
            @Override
            protected Map<String, String> getParams() {

                // Creating Map String Params.
                Map<String, String> params = new HashMap<String, String>();

                // Adding All values to Params.
                // The firs argument should be same sa your MySQL database table columns.
                params.put("User_Email", EmailHolder);
                params.put("User_Password", PasswordHolder);

                return params;
            }

        };

        // Creating RequestQueue.
        RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);

        // Adding the StringRequest object into requestQueue.
        requestQueue.add(stringRequest);

    }


    public void CheckEditTextIsEmptyOrNot() {

        // Getting values from EditText.
        EmailHolder = Email.getText().toString().trim();
        PasswordHolder = Password.getText().toString().trim();

        // Checking whether EditText value is empty or not.
        if (TextUtils.isEmpty(EmailHolder) || TextUtils.isEmpty(PasswordHolder)) {

            // If any of EditText is empty then set variable value as False.
            CheckEditText = false;

        } else {

            // If any of EditText is filled then set variable value as True.
            CheckEditText = true;
        }
    }
}

Code for activity_main.xml layout file.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:layout_margin="15dp"
    tools:context="com.android_examples.volleyuserlogin_android_examplescom.MainActivity">

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/textView"
        android:textSize="20dp"
        android:textStyle="bold"
        android:text="Volley User Login System"
        android:gravity="center"
        android:layout_marginTop="20dp"/>

    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="Enter Your Email"
        android:gravity="center"
        android:id="@+id/editText_Email"
        android:layout_below="@+id/textView"
        android:layout_marginTop="20dp"/>

    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="Enter Your Email"
        android:gravity="center"
        android:id="@+id/editText_Password"
        android:inputType="textPassword"
        android:layout_below="@+id/editText_Email"
        android:layout_marginTop="20dp"/>

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="CLICK HERE TO LOGIN"
        android:id="@+id/button_login"
        android:layout_below="@id/editText_Password"
        android:layout_marginTop="20dp"/>


</RelativeLayout>

Code for ProfileActivity.java file.

package com.android_examples.volleyuserlogin_android_examplescom;

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

public class ProfileActivity extends AppCompatActivity {

    TextView textView;
    Button logout;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_profile);

        // Assign ID's to textview and button.
        textView = (TextView)findViewById(R.id.TextViewUserEmail);
        logout = (Button)findViewById(R.id.button_logout);

        // Receiving value into activity using intent.
        String TempHolder = getIntent().getStringExtra("UserEmailTAG");

        // Setting up received value into TextView.
        textView.setText(textView.getText() + TempHolder);

        // Adding click listener to logout button.
        logout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                // Showing Echo Response Message Coming From Server.
                Toast.makeText(ProfileActivity.this, "Logged Out Successfully", Toast.LENGTH_LONG).show();

                // Closing the current activity.
                finish();

                // Redirect to Main Login activity after log out.
                Intent intent = new Intent(ProfileActivity.this, MainActivity.class);

                startActivity(intent);

            }
        });
    }
}

Code for activity_profile.xml layout file.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:layout_margin="20dp"
    tools:context="com.android_examples.volleyuserlogin_android_examplescom.ProfileActivity">

<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/TextViewUserEmail"
    android:gravity="center"
    android:textStyle="bold"
    android:textSize="18dp"
    android:text="Welcome - "
    android:layout_marginTop="50dp"
    />

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="LOGOUT"
        android:id="@+id/button_logout"
        android:layout_below="@+id/TextViewUserEmail"
        android:layout_marginTop="50dp"/>

</RelativeLayout>

Code for AndroidManifest.xml file.

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

    <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=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>

Screenshots :

Volley User Login

Download Source Code

Leave a Reply

Your email address will not be published. Required fields are marked *