Android Login Register tutorial using volley and php

Android login using volley cover image

Hello guys In this tutorial I’m going to show you how to create an android application in which user can register and login using Volley and PHP. If you have missed my previous tutorial on SharedPreferences file then do check it out here Android Shared Preferences tutorial. If you are a beginner then don’t worry i have covered the very basics in this tutorial. I will show you both the process in server side and android side. When I tried to search this topic on how to create register and login i couldn’t find one with my expectations. So decided to created this tutorial to understand very basics of volley and the rest api creation. Hope you will enjoy this one too just like others. So lets jump right in to the tutorial.

Contents of this tutorial

  1. Introduction 000webhost hosting service.
  2. Creating and editing PHP files.
  3. Checking the database.
  4. Creating android project

NB: If you don’t want to host php files for Android, skip to Creating Android Project part.

Introduction to 000Webhost hosting service

000webhost is one of the very few websites which offer free hosting for your website without paying a penny.

top features are

  1. 1500 MB disk space.
  2. 100 GB Data Transfer.
  3. PHP with MySQL support.
  4. cPanel Control Panel.

Creating and editing php files

For our purpose, we only need two php files, one for the registration and other for the login.

To create a file in 000Webhost navigate to your domain name -> manage website -> filemanager -> upload files now it will navigate you to file manager, in which you can easily create php file register.php and login.php by clicking on new file icon(make sure you are in the public_html folder). Now add the following code to the files.


register.php

 

<?php 
$con=mysqli_connect("localhost","username","password","databasename");
$username = $_POST["username"];
$email = $_POST["email"];
$password =$_POST["password"];
$sql = "INSERT INTO tablename(username,email,password)
VALUES ('$username','$email','$password')"
;
$result = mysqli_query( $con,$sql );
if($result) {
echo "registered successfully";
}else {
echo "some error occured";
}
?>

login.php

<?php 
$username = $_POST["username"];
$password = $_POST["password"];
$con=mysqli_connect("localhost","username","password","databasename");
$sql = "SELECT * FROM tablename WHERE  username = '$username' AND password = '$password'";
$result = mysqli_query($con,$sql);
if($result->num_rows > 0){
echo "logged in successfully" ;
}else{
   echo "user not found";
}
?>










Now, let’s move to the database part, I’m not going to cover all the methods to create database.hope you have basic knowledge about phpmyadmin. If not you can ask it in the comments below I will add another tutorial for this.

In the 000webhost home page click on Manage database. Scroll down to see an option to create database and click on it. Give a databasename,username and password.

Then click on Manage -> phpmyadmin and you will be navigated to phpmyadmin logn page. login using previously created credentials.

Now in Phpmyadmin create a table with columns username, email, and password.

In the above file, in the connection change database name, username, password to yours.

Creating Project and adding Resources

1. Open Android studio click on File->New->NewProject then enter the details of the project like name, backward compatibility, and package name.
2. Create an empty activity and name it the default one which is MainActivity (I just want to make it simple) then click finish. Now you have created your project. Make sure that there is no error by tapping on the RUN button at the top.
3. In the styles.xml file located under res->values change the line

Theme.AppCompat.Light.DarkActionBar to Theme.AppCompat.Light.NoActionBar to hide the default action bar(This step is optional).

styles.xml

 

<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>

</style>
</resources>

Adding the dependencies

Navigate to app->build.gradle. Add the bold code inside the dependencies tag.

build.gradle

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    implementation 'com.mcxiaoke.volley:library:1.0.19'
}

t

Now let’s add the internet permission in android_manifest.xml

android_manifest.xml

 

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.techpakka.loginregister">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:name=".AppController"
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">

</activity>
<activity android:name=".RegisterActivity" />
<activity android:name=".LoginActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

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

Adding the layout for register and login

open activity_login.xml under res->layout. add the following code to get a form like below.

activity_login.xml

 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".LoginActivity">
    <TextView
        android:id="@+id/textView"
        android:layout_gravity="center_horizontal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:text="Login"
        android:textAppearance="@style/TextAppearance.AppCompat.Title"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
    <EditText
        android:id="@+id/ed_username"
        android:layout_width="match_parent"
        android:layout_height="42dp"
        android:layout_marginEnd="16dp"
        android:layout_marginStart="16dp"
        android:layout_marginTop="32dp"
        android:ems="10"
        android:hint="username"
        android:inputType="textPersonName"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView" />

    <EditText
        android:id="@+id/ed_password"
        android:layout_width="match_parent"
        android:layout_height="42dp"
        android:layout_marginEnd="16dp"
        android:layout_marginStart="16dp"
        android:layout_marginTop="8dp"
        android:ems="10"
        android:hint="Password"
        android:inputType="textPassword"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/ed_username" />



    <Button
        android:id="@+id/btn_login"
        style="@style/Widget.AppCompat.Button.Colored"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginEnd="24dp"
        android:layout_marginStart="24dp"
        android:layout_marginTop="32dp"
        android:onClick="Login"
        android:padding="20dp"
        android:text="Login"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/ed_password" />

    <LinearLayout
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="24dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <TextView
            android:id="@+id/textView2"
            android:layout_width="wrap_content"
            android:layout_height="23dp"
            android:text="Not yet registered?"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.285"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/btn_login" />

        <Button
            android:id="@+id/button"
            style="@style/Widget.AppCompat.Button.Borderless"
            android:layout_width="wrap_content"
            android:layout_height="40dp"
            android:layout_marginStart="8dp"
            android:text="Register"
            android:onClick="navigatetoRegister"
            android:textColor="@color/colorAccent"
            app:layout_constraintStart_toEndOf="@+id/textView2"
            tools:layout_editor_absoluteY="289dp" />
    </LinearLayout>


</LinearLayout>

activity_register.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".RegisterActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:text="Register"
        android:layout_gravity="center_horizontal"
        android:textAppearance="@style/TextAppearance.AppCompat.Title" />


    <EditText
        android:id="@+id/ed_username"
        android:layout_width="match_parent"
        android:layout_height="42dp"
        android:layout_marginEnd="16dp"
        android:layout_marginStart="16dp"
        android:layout_marginTop="32dp"
        android:ems="10"
        android:hint="username"
        android:inputType="textPersonName" />

    <EditText
        android:id="@+id/ed_email"
        android:layout_width="match_parent"
        android:layout_height="42dp"
        android:layout_marginEnd="16dp"
        android:layout_marginStart="16dp"
        android:layout_marginTop="16dp"
        android:ems="10"
        android:hint="Email"
        android:inputType="textPersonName" />

    <EditText
        android:id="@+id/ed_password"
        android:layout_width="match_parent"
        android:layout_height="42dp"
        android:layout_marginEnd="16dp"
        android:layout_marginStart="16dp"
        android:layout_marginTop="8dp"
        android:ems="10"
        android:hint="Password"
        android:inputType="textPassword" />


    <Button
        android:id="@+id/btn_register"
        style="@style/Widget.AppCompat.Button.Colored"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginEnd="24dp"
        android:layout_marginStart="24dp"
        android:onClick="Register"
        android:layout_marginTop="32dp"
        android:padding="20dp"
        android:text="Register"/>
    <LinearLayout
        android:layout_marginTop="24dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/textView3"
            android:layout_width="wrap_content"
            android:layout_height="23dp"
            android:text="Already registered?"/>

        <Button
            android:id="@+id/button2"
            android:onClick="navigatetologin"
            style="@style/Widget.AppCompat.Button.Borderless"
            android:layout_width="wrap_content"
            android:layout_height="35dp"
            android:text="Login"
            android:textColor="@color/colorAccent" />
    </LinearLayout>
</LinearLayout>

now we have created the design for our app lets add the java code

Java code

Lets add code to registration first. add below code to register.java
process done in register file are :-

  1. fetching the reference of components in the layout file(Edittext,Button) using findViewById
  2.  call method register() on button click.
    3. Create StringRequest of Volley to send userdata to server.
    4. show the response from server as toast.
    5. Creating a button to navigate to login page.

register.java

 

package com.techpakka.loginregister;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import java.util.HashMap;
import java.util.Map;
public class RegisterActivity extends AppCompatActivity {

EditText ed_username,ed_email,ed_password;
String str_username,str_email,str_password;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
ed_email = findViewById(R.id.ed_email);
ed_username = findViewById(R.id.ed_username);
ed_password = findViewById(R.id.ed_password);

}

public void Register(View view) {
str_email = ed_email.getText().toString();
str_username = ed_username.getText().toString();
str_password = ed_password.getText().toString();
StringRequest stringRequest = new StringRequest(Request.Method.POST, WebConfig.register_url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Toast.makeText(RegisterActivity.this, response, Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(RegisterActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
}
}){
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new HashMap<String, String>();
params.put("username",str_username);
params.put("email",str_email);
params.put("password",str_password);

return params;
}
};
AppController.getInstance().addToRequestQueue(stringRequest);
}

public void navigatetologin(View view) {
Intent intent = new Intent(RegisterActivity.this,LoginActivity.class);
startActivity(intent);
}
}

run the app and check if you get a message showing successfully registered. Also check database in 000webhostapp if user’s data is present. If so lets jump in to login section.
Add below code to Login.java. and run the app.

Login.java

 

package com.techpakka.loginregister;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import java.util.HashMap;
import java.util.Map;
public class LoginActivity extends AppCompatActivity {

EditText ed_username,ed_password;
String str_username,str_password;
String username = "jobin";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
ed_username = findViewById(R.id.ed_username);
ed_password = findViewById(R.id.ed_password);
}
public void Login(View view){
str_username = ed_username.getText().toString();
str_password = ed_password.getText().toString();
StringRequest stringRequest = new StringRequest(Request.Method.POST, WebConfig.login_url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Toast.makeText(LoginActivity.this, response, Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(LoginActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
}
}){
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new HashMap<String, String>();
params.put("username",str_username);
params.put("password",str_password);

return params;
}
};
AppController.getInstance().addToRequestQueue(stringRequest);
}

public void navigatetoRegister(View view) {
Intent intent = new Intent(LoginActivity.this,RegisterActivity.class);
startActivity(intent);
}
public int get(){
return 1;
}

}

enter the credential of previously registered user check if you get a success message. If so voila! you have succesfully created your Login and registration app.

Thats it for this tutorial. If you ran into any error dont be shy to discuss the error in comments below. Im always ready to help!. In the previous tutorial i have discussed in detail about sharedpreferences file.If you have not seen the post
you can check it here. Stay tuned for more exiting tutorials like this.In the next post i will be writing in detail about Webview.See ya next time.