How to Create Registration and Login Form in Android using MySQL Database?
In this tutorial we are going to create a simple registration and login form in android using MySQL Database.
Things to understand before doing this project.
Android apps execution, thread and AsynTask:
Now let’s talk about android apps execution. Android appplication code by default runs in a single thread called as main thread or UI thread. Since all the codes are running in a single thread every statements gets executed in sequence. Thus if we perform a long lasting operation, the application blocks the thread until the corresponding operation has been finished.Hence it is better to perform such long lasting operation asynchronously or in new thread. Here we have two option either we can use thread or asynTask to do our network operation of our application. Talking about thread, A Thread is a single sequential flow of control within a program means when we create new thread in our application the code inside that thread gets executed first. And when talking about asynTask, A asynTask is defined by a computation that runs on a background thread and whose result is published on UI thread. asynTask is one of the easiest ways to implement parallelism in android without having to deal with more complex methods like Threads.
That’s why we are going to use asynTask in our application. Now we have to understand in details about asynTask. It has four methods onPreExecute(), doInBackground(), onProgresUpdate() and onPostExecute(). Let’s understand in short what are these methods are:
i) onPreExecute(): This method contain the code which is executed before the background processing starts.
ii) doInBackground(): it contains the code which needs to be executed in background. In this method, we can send results multiple times to the UI thread by publishProgress() method.
iii) onProgressUpdate(): This method receives progress update from doInBackground() method.
iv)onPostExecute(): This method is called after doInBackground() method completes processing. Result from doInBackground() is passed to this method.
Before doing this project, you have to installed any server application like WAMP server in your system and run it because we are going to use PHP in our back-end.
STEPS:
[sociallocker]
1. Now we have to create database in MySQL. So, open any browsing software like chrome. Enter 127.0.0.1 or localhost in the address bar and then enter. Now scroll down and find phpmyadmin click it and login to it by enter username and password that you set while installing it(Default username is root; password leave empty as it is). Now click New from the left pane, give database name and click create. Now give table name and Number of column 5 click Go. give column name like name, address, email, username and password, select data type as varchar and the length whatever you want like 50 click Go.
2. Now open any text editing software and write following code; save this code inside www folder of WAMP Server; if you are using XAMPP save it inside htdocs.
a. Code for registration:
<?php $servername="localhost"; $mysql_user="root"; $mysql_pass=""; $dbname="YOUR_DATABASE_NAME"; $conn=mysqli_connect($servername, $mysql_user, $mysql_pass, $dbname); if($conn){ echo("connection success"); }else{ echo("connection not success"); } if($_SERVER['REQUEST_METHOD']=='POST'){ $name=$_POST['name']; $add=$_POST['address']; $email=$_POST['email']; $user=$_POST['username']; $pass=$_POST['password']; $query="INSERT INTO `YOUR_TABLE_NAME`(`name`, `address`, `email`, `username`, `password`) VALUES ('$name', '$add', '$email', '$user', '$pass')"; if(mysqli_query($conn, $query)){ echo("registered successfully"); }else{ echo("error in registration"); } }else{ echo("error in request method"); } ?>
b. code for login:
<?php $servername="localhost"; $mysql_user="root"; $mysql_pass=""; $dbname="YOUR_DATABASE_NAME"; $conn=mysqli_connect($servername, $mysql_user, $mysql_pass, $dbname); if($conn){ echo("connection success"); }else{ echo("connection not success"); } $user_name=$_POST['username']; $pass_word=$_POST['password']; $query="SELECT `username`, `password` FROM `YOUR_TABLE_NAME` WHERE username='$user_name' and password='$pass_word'"; $result=mysqli_query($conn, $query); if(mysqli_num_rows($result)>0){ echo("login success"); }else{ echo("login failed"); }?>
3. Now open Android Studio. Go to file>new project>give name of your project>select phone and tablet>next>and then select empty activity and click next and then click on finish.
4. Goto app>res>layout>activity_main.xml by click the project field from left pane of your android studio and write the following code inside the ConstraintLayout tag. or Drag and Drop five plainText, two Button over your Layout. Now you have to change the properties ( ID, text and text size) as you like or write the following code by for this you have to go to the text of your xml file you can find it at the lower end of android studio. For more Detail, watch the video. In this step we complete the user interface part.
a. Registration Designing Code:
<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <EditText android:id="@+id/txtName" android:layout_width="349dp" android:layout_height="wrap_content" android:layout_marginTop="16dp" android:ems="10" android:hint="name" android:inputType="textPersonName" android:textSize="18sp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <EditText android:id="@+id/txtAdd" android:layout_width="349dp" android:layout_height="wrap_content" android:layout_marginBottom="22dp" android:layout_marginLeft="16dp" android:layout_marginStart="16dp" android:layout_marginTop="87dp" android:ems="10" android:hint="address" android:inputType="textPersonName" android:textSize="18sp" app:layout_constraintBottom_toTopOf="@+id/txtEmail" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <EditText android:id="@+id/txtEmail" android:layout_width="349dp" android:layout_height="wrap_content" android:layout_marginBottom="32dp" android:layout_marginLeft="16dp" android:layout_marginStart="16dp" android:ems="10" android:hint="email" android:inputType="textPersonName" app:layout_constraintBottom_toTopOf="@+id/txtUser" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/txtAdd" /> <EditText android:id="@+id/txtUser" android:layout_width="349dp" android:layout_height="wrap_content" android:layout_marginBottom="29dp" android:layout_marginLeft="16dp" android:layout_marginStart="16dp" android:ems="10" android:hint="username" android:inputType="textPersonName" app:layout_constraintBottom_toTopOf="@+id/txtPass" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/txtEmail" /> <EditText android:id="@+id/txtPass" android:layout_width="349dp" android:layout_height="wrap_content" android:layout_marginBottom="36dp" android:layout_marginLeft="16dp" android:layout_marginStart="16dp" android:ems="10" android:hint="password" android:inputType="textPersonName" app:layout_constraintBottom_toTopOf="@+id/btnReg" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/txtUser" /> <Button android:id="@+id/btnReg" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="73dp" android:layout_marginLeft="16dp" android:layout_marginStart="16dp" android:text="Register" android:textSize="20sp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/txtPass" /> <Button android:id="@+id/btnLogin" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginEnd="16dp" android:layout_marginRight="16dp" android:text="Login" android:textSize="20sp" app:layout_constraintBottom_toBottomOf="@+id/btnReg" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toTopOf="@+id/btnReg" /> </android.support.constraint.ConstraintLayout>
b. Login Design Code:
For this you have to add another activity in your apps. So expand app directory again expand java directory now right click over top directory. right click>new>activity>empty activity> give the activity name as login and click finish.
Again app>res>layout>activity_login.xml and drag and drop two plain text and one button and change the properties( ID, text and text size) as you like or write the following code by for this you have to go to the text of your xml file you can find it at the lower end of android studio.
<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".login" tools:layout_editor_absoluteY="81dp"> <EditText android:id="@+id/txtUsername" android:layout_width="0dp" android:layout_height="0dp" android:layout_marginBottom="41dp" android:layout_marginEnd="16dp" android:layout_marginLeft="16dp" android:layout_marginRight="16dp" android:layout_marginStart="16dp" android:layout_marginTop="83dp" android:ems="10" android:hint="username" android:inputType="textPersonName" app:layout_constraintBottom_toTopOf="@+id/txtPassword" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <EditText android:id="@+id/txtPassword" android:layout_width="0dp" android:layout_height="0dp" android:layout_marginBottom="54dp" android:layout_marginEnd="16dp" android:layout_marginLeft="16dp" android:layout_marginRight="16dp" android:layout_marginStart="16dp" android:ems="10" android:hint="password" android:inputType="textPersonName" app:layout_constraintBottom_toTopOf="@+id/btnLog" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/txtUsername" /> <Button android:id="@+id/btnLog" android:layout_width="170dp" android:layout_height="0dp" android:layout_marginBottom="183dp" android:layout_marginLeft="73dp" android:layout_marginStart="73dp" android:text="LOGIN" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintStart_toStartOf="@+id/txtPassword" app:layout_constraintTop_toBottomOf="@+id/txtPassword" /> </android.support.constraint.ConstraintLayout>
5. Now goto app>java> and top directory>right click>new>java class. Give class name as BackgroundTask click OK. and then write the following piece of code inside that class.
import android.content.Context; import android.os.AsyncTask; import android.support.constraint.ConstraintLayout; import android.widget.Toast; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLEncoder; public class BackgroundTask extends AsyncTask<String, String, String> { Context context; BackgroundTask(Context ctx){ context=ctx; } @Override protected String doInBackground(String... strings) { String type=strings[0]; String loginURL="http://10.0.2.2/Example/andphplogin.php"; String regURL="http://10.0.2.2/Example/andphpreg.php"; if(type.equals("reg")){ String name= strings[1]; String address=strings[2]; String email= strings[3]; String username=strings[4]; String password=strings[5]; try{ URL url= new URL(regURL); try{ HttpURLConnection httpURLConnection= (HttpURLConnection)url.openConnection(); httpURLConnection.setRequestMethod("POST"); httpURLConnection.setDoOutput(true); httpURLConnection.setDoInput(true); OutputStream outputStream= httpURLConnection.getOutputStream(); OutputStreamWriter outputStreamWriter= new OutputStreamWriter(outputStream, "UTF-8"); BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter); String insert_data = URLEncoder.encode("name", "UTF-8")+"="+URLEncoder.encode(name, "UTF-8")+ "&"+URLEncoder.encode("address", "UTF-8")+"="+URLEncoder.encode(address, "UTF-8")+ "&"+URLEncoder.encode("email", "UTF-8")+"="+URLEncoder.encode(email, "UTF-8")+ "&"+URLEncoder.encode("username", "UTF-8")+"="+URLEncoder.encode(username, "UTF-8")+ "&"+URLEncoder.encode("password", "UTF-8")+"="+URLEncoder.encode(password, "UTF-8"); bufferedWriter.write(insert_data); bufferedWriter.flush(); bufferedWriter.close(); InputStream inputStream= httpURLConnection.getInputStream(); InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "ISO-8859-1"); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); String result=""; String line=""; StringBuilder stringBuilder= new StringBuilder(); while ((line=bufferedReader.readLine())!=null){ stringBuilder.append(line).append("\n"); } result=stringBuilder.toString(); bufferedReader.close(); inputStream.close(); httpURLConnection.disconnect(); return result; } catch (IOException e) { e.printStackTrace(); } } catch (MalformedURLException e) { e.printStackTrace(); } }else if(type.equals("login")) { String user_name = strings[1]; String pass_word = strings[2]; try { URL url = new URL(loginURL); try { HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setRequestMethod("POST"); httpURLConnection.setDoOutput(true); httpURLConnection.setDoInput(true); OutputStream outputStream = httpURLConnection.getOutputStream(); OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream, "UTF-8"); BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter); String login_data = URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(user_name, "UTF-8") + "&" + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(pass_word, "UTF-8"); bufferedWriter.write(login_data); bufferedWriter.flush(); bufferedWriter.close(); InputStream inputStream = httpURLConnection.getInputStream(); InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "ISO-8859-1"); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); String result = ""; String line = ""; StringBuilder stringBuilder = new StringBuilder(); while ((line = bufferedReader.readLine()) != null) { stringBuilder.append(line).append("\n"); } result = stringBuilder.toString(); bufferedReader.close(); inputStream.close(); httpURLConnection.disconnect(); return result; } catch (IOException e) { e.printStackTrace(); } } catch (MalformedURLException e) { e.printStackTrace(); } } return null; } @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected void onPostExecute(String s) { Toast.makeText(context, s, Toast.LENGTH_LONG).show(); //super.onPostExecute(s); } }
6. Now goto app>java>expand that top folder and double click that MainActivity.java and write the following code inside it.
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.EditText; public class MainActivity extends AppCompatActivity { Button _btnReg, _btnLogin; EditText _txtName, _txtAdd, _txtEmail, _txtUser, _txtPass; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); _btnLogin=(Button)findViewById(R.id.btnLogin); _btnReg=(Button)findViewById(R.id.btnReg); _txtName=(EditText)findViewById(R.id.txtName); _txtAdd=(EditText)findViewById(R.id.txtAdd); _txtEmail=(EditText)findViewById(R.id.txtEmail); _txtUser=(EditText)findViewById(R.id.txtUser); _txtPass=(EditText)findViewById(R.id.txtPass); _btnReg.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String name=_txtName.getText().toString(); String address=_txtAdd.getText().toString(); String email=_txtEmail.getText().toString(); String username=_txtUser.getText().toString(); String password=_txtPass.getText().toString(); String type="reg"; BackgroundTask backgroundTask= new BackgroundTask(getApplicationContext()); backgroundTask.execute(type, name, address, email, username, password); } }); _btnLogin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent= new Intent(MainActivity.this, login.class); startActivity(intent); } }); } }
7. Double click login.java and write the following Code:
import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; public class login extends AppCompatActivity { Button _btnLog; EditText _txtUsername, _txtPassword; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); _btnLog=findViewById(R.id.btnLog); _txtUsername=findViewById(R.id.txtUsername); _txtPassword=findViewById(R.id.txtPassword); _btnLog.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String user_name=_txtUsername.getText().toString(); String pass_word=_txtPassword.getText().toString(); String type="login"; BackgroundTask backgroundTask= new BackgroundTask(getApplicationContext()); backgroundTask.execute(type, user_name, pass_word); } }); } }
Now we are sending data from our apps to MySQL Database via HTTP so you have to provide your apps to use internet. For this go to app>manifests> double click that AndroidManifest.xml file and write the follwing code above <application> tag:
<uses-permission android:name="android.permission.INTERNET" />
8. Now run you application by clicking that run button. Select any devices in which you want to run your apps like android emulator or third party emulator or may be your real devices and fill the form click register, you data need to be inserted in your database check your database. That’s all.
[/sociallocker]
if you have any confusion, feel free to watch these videos: