Android Login Registration With PHP MySQL Example Tutorial

How to add online server login and SignUP inside android app using HttpURLconnection source code download .

This tutorial is one of the most demanded tutorial on internet because every android developer who wish to create a fully dynamic android application is mostly used login and registration feature on their android app with server side code included . So here is the complete step by step tutorial for Android Login Registration With PHP MySQL Example Tutorial

android-project-download-code-button

Before getting started things you need to prepare :

  • Android Studio .
  • Emulator or Your android phone ( To test the app ) .
  • Online free hosting server that supports PHP .
  • Working internet connection in your mobile phone .
  • Just read all the below instructions .

List of all activities in this project :

  1. MainActivity.java .
  2. LoginActivity.java .
  3. Profile .

List of all layout files in this project :

  1. activity_login.xml .
  2. activity_main.xml .
  3. activity_profile.xml .

List of all PHP files in this project used for server connectivity :

  1. dbconfig.php .
  2. insert-registration-data.php .
  3. android-login.php .

Please follow the steps to import org.apache.http.legacy library in your project :

1. Open your project’s build.gradle(Module : App) file .

2. Now type useLibrary ‘org.apache.http.legacy’ inside android scope like i did in below screenshot .

Here you Go now this library will be successfully imported in your project . Next step is to start coding .

Android Login Registration With PHP MySQL Example Tutorial .

Code for MainActivity.java file.

package com.android_examples.androidloginregistration_android_examplescom;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    Button register , login ;
    EditText name, email , password ;
    String RegisterURL = "http://androidblog.esy.es/login/insert-registration-data.php" ;
    Boolean CheckEditText ;
    String Response;
    HttpResponse response ;
    String NameHolder, EmailHolder, PasswordHolder ;

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

        register = (Button)findViewById(R.id.button);
        login = (Button)findViewById(R.id.button2);

        name = (EditText)findViewById(R.id.name);
        email = (EditText)findViewById(R.id.email);
        password = (EditText)findViewById(R.id.password);

        register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {


                GetCheckEditTextIsEmptyOrNot();

                if(CheckEditText){

                    SendDataToServer(NameHolder, EmailHolder, PasswordHolder);

                }
                else {

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

                }


            }
        });

        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

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

            }
        });
    }

    public void GetCheckEditTextIsEmptyOrNot(){

        NameHolder = name.getText().toString();
        EmailHolder = email.getText().toString();
        PasswordHolder = password.getText().toString();

        if(TextUtils.isEmpty(NameHolder) || TextUtils.isEmpty(EmailHolder) || TextUtils.isEmpty(PasswordHolder))
        {

            CheckEditText = false;

        }
        else {

            CheckEditText = true ;
        }

    }

    public void SendDataToServer(final String name, final String email, final String password){
        class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
            @Override
            protected String doInBackground(String... params) {

                String QuickName = name ;
                String QuickEmail = email ;
                String QuickPassword = password;

                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

                nameValuePairs.add(new BasicNameValuePair("name", QuickName));
                nameValuePairs.add(new BasicNameValuePair("email", QuickEmail));
                nameValuePairs.add(new BasicNameValuePair("password", QuickPassword));

                try {
                    HttpClient httpClient = new DefaultHttpClient();

                    HttpPost httpPost = new HttpPost(RegisterURL);

                    httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                    HttpResponse response = httpClient.execute(httpPost);

                    HttpEntity entity = response.getEntity();


                } catch (ClientProtocolException e) {

                } catch (IOException e) {

                }
                return "Data Submit Successfully";
            }

            @Override
            protected void onPostExecute(String result) {
                super.onPostExecute(result);

                Toast.makeText(MainActivity.this, "Data Submit Successfully", Toast.LENGTH_LONG).show();

            }
        }
        SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
        sendPostReqAsyncTask.execute(name, email, password);
    }

}

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:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#03A9F4"
    android:padding="20dp"
    tools:context="com.android_examples.androidloginregistration_android_examplescom.MainActivity">


    <TextView
        android:text="Register Here"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/textView"
        android:textColor="#ffffff"
        android:textSize="30dp"
        android:gravity="center"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="30dp"
        />

    <EditText
        android:layout_width="fill_parent"
        android:layout_height="50dp"
        android:inputType="textPersonName"
        android:ems="10"
        android:layout_below="@+id/textView"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="30dp"
        android:id="@+id/name"
        android:gravity="center"
        android:background="#fbfefd"
        android:hint="Enter Name Here"
        />

    <EditText
        android:layout_width="fill_parent"
        android:layout_height="50dp"
        android:inputType="textEmailAddress"
        android:ems="10"
        android:layout_marginTop="30dp"
        android:id="@+id/email"
        android:gravity="center"
        android:background="#fbfefd"
        android:hint="Enter Email Here"
        android:layout_below="@+id/name"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <EditText
        android:layout_width="fill_parent"
        android:inputType="textPassword"
        android:layout_marginTop="30dp"
        android:ems="10"
        android:id="@+id/password"
        android:gravity="center"
        android:background="#fbfefd"
        android:hint="Enter Password Here"
        android:layout_height="50dp"
        android:layout_centerVertical="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <Button
        android:text="REGISTER"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/password"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="30dp"
        android:id="@+id/button"
        />

    <Button
        android:text="Already Register! Login From Here"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/button"
        android:layout_centerHorizontal="true"
        android:id="@+id/button2"
        android:layout_marginTop="10dp"/>

</RelativeLayout>

Code for LoginActivity.java file.

package com.android_examples.androidloginregistration_android_examplescom;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
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 java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import javax.net.ssl.HttpsURLConnection;

public class Login_Activity extends AppCompatActivity {

    Button login ;
    ProgressDialog progressDialog;
    EditText email, password ;
    String EmailHolder, PasswordHolder ;
    boolean CheckEditText ;
    String ServerLoginURL = "http://androidblog.esy.es/login/android-login.php";
    public static final String UserEmail = "";
    String finalResult ;
    HashMap<String,String> hashMap = new HashMap<>();
    URL url;
    String FinalHttpData = "";
    BufferedWriter bufferedWriter ;
    LoginParseClass loginParseClass = new LoginParseClass();
    BufferedReader bufferedReader ;
    OutputStream outputStream ;
    StringBuilder stringBuilder = new StringBuilder();
    String Result ;

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

        login = (Button)findViewById(R.id.button);

        email = (EditText) findViewById(R.id.email);

        password = (EditText)findViewById(R.id.password);

        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                GetCheckEditTextIsEmptyOrNot();

                if(CheckEditText){

                    LoginFunction(EmailHolder,PasswordHolder);

                }
                else {

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

                }



            }
        });
    }

    public void GetCheckEditTextIsEmptyOrNot(){

        EmailHolder = email.getText().toString();
        PasswordHolder = password.getText().toString();

        if(TextUtils.isEmpty(EmailHolder) || TextUtils.isEmpty(PasswordHolder))
        {

            CheckEditText = false;

        }
        else {

            CheckEditText = true ;
        }

    }

    public void LoginFunction(final String email, final String password){

        class LoginFunctionClass extends AsyncTask<String,Void,String> {

            @Override
            protected void onPreExecute() {
                super.onPreExecute();

                progressDialog = ProgressDialog.show(Login_Activity.this,"Loading Data",null,true,true);
            }

            @Override
            protected void onPostExecute(String httpResponseMsg) {

                super.onPostExecute(httpResponseMsg);

                progressDialog.dismiss();

                if(httpResponseMsg.equalsIgnoreCase("Data Matched")){

                    finish();

                    Intent intent = new Intent(Login_Activity.this, profile.class);

                    intent.putExtra(UserEmail,email);

                    startActivity(intent);
                }else{

                    Toast.makeText(Login_Activity.this,httpResponseMsg,Toast.LENGTH_LONG).show();
                }
            }

            @Override
            protected String doInBackground(String... params) {

                hashMap.put("email",params[0]);

                hashMap.put("password",params[1]);

                finalResult = loginParseClass.postRequest(hashMap);

                return finalResult;
            }
        }

        LoginFunctionClass loginFunctionClass = new LoginFunctionClass();
        loginFunctionClass.execute(email,password);
    }

    public class LoginParseClass {

        public String postRequest(HashMap<String, String> Data) {

            try {
                url = new URL(ServerLoginURL);

                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();

                httpURLConnection.setReadTimeout(12000);

                httpURLConnection.setConnectTimeout(12000);

                httpURLConnection.setRequestMethod("POST");

                httpURLConnection.setDoInput(true);

                httpURLConnection.setDoOutput(true);

                outputStream = httpURLConnection.getOutputStream();

                bufferedWriter = new BufferedWriter(

                        new OutputStreamWriter(outputStream, "UTF-8"));

                bufferedWriter.write(FinalDataParse(Data));

                bufferedWriter.flush();

                bufferedWriter.close();

                outputStream.close();

                if (httpURLConnection.getResponseCode() == HttpsURLConnection.HTTP_OK) {

                    bufferedReader = new BufferedReader(
                            new InputStreamReader(
                                    httpURLConnection.getInputStream()
                            )
                    );
                    FinalHttpData = bufferedReader.readLine();
                }
                else {
                    FinalHttpData = "Something Went Wrong";
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            return FinalHttpData;
        }

        public String FinalDataParse(HashMap<String, String> hashMap2) throws UnsupportedEncodingException {

            for(Map.Entry<String, String> map_entry : hashMap2.entrySet()){

                stringBuilder.append("&");

                stringBuilder.append(URLEncoder.encode(map_entry.getKey(), "UTF-8"));

                stringBuilder.append("=");

                stringBuilder.append(URLEncoder.encode(map_entry.getValue(), "UTF-8"));

            }

            Result = stringBuilder.toString();

            return Result ;
        }
    }

}

Code for activity_login.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:id="@+id/activity_login_"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#03A9F4"
    android:padding="20dp"
    tools:context="com.android_examples.androidloginregistration_android_examplescom.Login_Activity">

    <TextView
        android:text="Log-In Panel "
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/textView"
        android:textColor="#ffffff"
        android:textSize="30dp"
        android:gravity="center"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="70dp"
        />

    <EditText
        android:layout_width="fill_parent"
        android:layout_height="50dp"
        android:inputType="textEmailAddress"
        android:ems="10"
        android:layout_below="@+id/textView"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="30dp"
        android:id="@+id/email"
        android:gravity="center"
        android:background="#fbfefd"
        android:hint="Enter Email Here"

        />

    <EditText
        android:layout_width="fill_parent"
        android:layout_height="50dp"
        android:inputType="textPassword"
        android:ems="10"
        android:layout_marginTop="30dp"
        android:id="@+id/password"
        android:gravity="center"
        android:background="#fbfefd"
        android:hint="Enter Password Here"
        android:layout_below="@+id/email"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <Button
        android:text="LOGIN"
        android:layout_width="fill_parent"
        android:layout_marginTop="30dp"
        android:layout_height="wrap_content"
        android:id="@+id/button"
        android:layout_centerVertical="true"
        android:layout_below="@+id/password" />

</RelativeLayout>

Code for profile.java file.

package com.android_examples.androidloginregistration_android_examplescom;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class profile extends AppCompatActivity {

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

        textView = (TextView)findViewById(R.id.textviewprofile);

        button = (Button)findViewById(R.id.button) ;

        Intent intent = getIntent();

        String username = intent.getStringExtra(Login_Activity.UserEmail);

        textView.setText(username);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                finish();

                Intent intent = new Intent(profile.this, Login_Activity.class);

                startActivity(intent);

                Toast.makeText(profile.this, "Log Out Successfully", Toast.LENGTH_LONG).show();

            }
        });

    }

    @Override
    public void onBackPressed() {

        Toast.makeText(profile.this, "Please Click on Log Out button .", Toast.LENGTH_LONG).show();

        return;
    }
}

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:id="@+id/activity_profile"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.android_examples.androidloginregistration_android_examplescom.profile"
    android:background="#03A9F4">

    <TextView
        android:text="SuccessFully Logged In, Your Email =  "
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/textView"
        android:textColor="#ffffff"
        android:textSize="30dp"
        android:gravity="center"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="150dp"
        />

    <TextView
        android:text=""
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#ffffff"
        android:textSize="30dp"
        android:gravity="center"
        android:layout_below="@+id/textView"
        android:layout_centerHorizontal="true"
        android:id="@+id/textviewprofile"/>

    <Button
        android:layout_marginTop="30dp"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/button"
        android:text="Logout"
        android:layout_below="@+id/textviewprofile"/>

</RelativeLayout>

Code for styles.xml file.

 <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>

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.androidloginregistration_android_examplescom">

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        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=".Login_Activity" />
        <activity android:name=".profile"></activity>
    </application>

</manifest>

PHP Files Code :

Code for dbconfig.php file.

 <?php
//This script is designed by Android-Examples.com
//Define your host here.
$servername = "mysql.hostinger.in";
//Define your database username here.
$username = "u288012116_and";
//Define your database password here.
$password = "GArpOsx4KVa0GJDquJ";
//Define your database name here.
$dbname = "u288012116_and";
?>

Code for insert-registration-data.php file.

 <?php

include 'dbconfig.php';

 $con = mysqli_connect($servername,$username,$password,$dbname);
 
 $name = $_POST['name'];
 $email = $_POST['email'];
 $password = $_POST['password'];
 
 $Sql_Query = "insert into AndroidLoginTable (name,email,password) values ('$name','$email','$password')";
 
 if(mysqli_query($con,$Sql_Query)){
 
 echo 'Data Inserted Successfully';
 
 }
 else{
 
 echo 'Try Again';
 
 }
 mysqli_close($con);
?>

Code for android-login.php file.

 <?php

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

 include 'dbconfig.php';
 
 $con = mysqli_connect($servername,$username,$password,$dbname);
 
 $email = $_POST['email'];
 $password = $_POST['password'];
 
 $Sql_Query = "select * from AndroidLoginTable where email = '$email' and 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);

Screenshots :

Android Login Registration With PHP MySQL Example Tutorial

Click here to download Android Login Registration With PHP MySQL Example Tutorial project with source code.

Leave a Reply

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