Hello folks, so here is a very useful post about android login and registration. You know that a registration and login screen is part of almost of the application we see. And if we talk about android then we have to save the user data in our server.
In this android login and registration tutorial we will create a very simple application that will contain 3 screens. The User Registration Screen, User Login Screen and the User Profile Screen.
Here for the server side part we will be using PHP and MySQL with our XAMPP (you can use wamp or lamp as well) server.
So without wasting time lets start our Android Login and Registration tutorial. 🙂
Table of Contents
Android Login and Registration Video Tutorial
- Feel boring reading long posts? More comfortable watching video tutorials? Here is a complete playlist for this post.
- And if you are ok with text content then lets move ahead.
Creating Web Services
The first phase of this tutorial covers creating web services for User Signup and Login. Â Now you may be thinking that why we need to create web services?
Why Web Services
The problem here is our application cannot access our server directly. We need some medium between server and the application so that our application can access the database residing in our web server. For this we use Web Services often called APIs, ore more specifically a RESTful API. Now here I am not discussing very much about Rest APIs or Web Services. You can check the below tutorials if you want to explore these things further.
- Build REST API using Laravel Lumen for your Application
- PHP Restful API Framework SLIM to Create REST API – 1
In this post we will not be using any framework to build our APIs. We will use the basic php only.
But for creating any kind of API you must know about JSON, and if you are completely unaware about JSON then you should go through this seven minute quick video first. Here you will understand everything about JSON.
Creating Database
- We need to following database table.
- So first you create a new database in your PhpMyAdmin (localhost/phpmyadmin).
- Inside the database we create the above shown table. And for this you can use the following query.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
-- created by belal -- website www.simplifiedcoding.net -- Table: users CREATE TABLE users ( id int NOT NULL AUTO_INCREMENT, username varchar(200) NOT NULL, email varchar(200) NOT NULL, password text NOT NULL, gender varchar(6) NOT NULL, CONSTRAINT users_pk PRIMARY KEY (id) ); -- End of file. |
- When you will execute the above given query in your database you will get the following table.
- Now we have our database table where we will store the user data. Now lets create a PHP Project for our Web Services.
Creating a new PHP Project
- Go to the htdocs folder, and create a new folder there. (This folder is actually our project). You can use an IDE like PHP Storm to create a new project but remember create it inside htdocs only (c:/xampp/htdocs). Here I am using Sublime Text.
- Now the first step is the database connection.
Connecting to the Database
- So inside your project folder create a new php file named DbConnect.php. We will use this file to connect to the database. So write the following code inside.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<? //these are the server details //the username is root by default in case of xampp //password is nothing by default //and lastly we have the database named android. if your database name is different you have to change it $servername = "localhost"; $username = "root"; $password = ""; $database = "android"; //creating a new connection object using mysqli $conn = new mysqli($servername, $username, $password, $database); //if there is some error connecting to the database //with die we will stop the further execution by displaying a message causing the error if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } |
- To confirm that the above script is working, you should open it in your browser (localhost/YourProjectFolder/DbConnect.php). If you are seeing nothing in the browser that means it is working fine.
Building Web Services
- Now here comes the main part. For the current application we need Web Services for two operation, the first one is User Registration and the second one is User Login.
- So for this create a new php file named Api.php. Inside this file we will handle all the API calls. Currently we have only two the User Registration and User Login.
- So write the following code inside Api.php.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
<?php //getting the database connection require_once 'DbConnect.php'; //an array to display response $response = array(); //if it is an api call //that means a get parameter named api call is set in the URL //and with this parameter we are concluding that it is an api call if(isset($_GET['apicall'])){ switch($_GET['apicall']){ case 'signup': //in this part we will handle the registration break; case 'login': //this part will handle the login break; default: $response['error'] = true; $response['message'] = 'Invalid Operation Called'; } }else{ //if it is not api call //pushing appropriate values to response array $response['error'] = true; $response['message'] = 'Invalid API Call'; } //displaying the response in json structure echo json_encode($response); |
Parameter Validations
- We also need to validate that the required parameters are available or not. For this at the bottom in the same file (Api.php), create the following function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
//function validating all the paramters are available //we will pass the required parameters to this function function isTheseParametersAvailable($params){ //traversing through all the parameters foreach($params as $param){ //if the paramter is not available if(!isset($_POST[$param])){ //return false return false; } } //return true if every param is available return true; } |
User Registration
- Now lets complete the user registration. So inside switch where we need to perform the registration write the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
case 'signup': //checking the parameters required are available or not if(isTheseParametersAvailable(array('username','email','password','gender'))){ //getting the values $username = $_POST['username']; $email = $_POST['email']; $password = md5($_POST['password']); $gender = $_POST['gender']; //checking if the user is already exist with this username or email //as the email and username should be unique for every user $stmt = $conn->prepare("SELECT id FROM users WHERE username = ? OR email = ?"); $stmt->bind_param("ss", $username, $email); $stmt->execute(); $stmt->store_result(); //if the user already exist in the database if($stmt->num_rows > 0){ $response['error'] = true; $response['message'] = 'User already registered'; $stmt->close(); }else{ //if user is new creating an insert query $stmt = $conn->prepare("INSERT INTO users (username, email, password, gender) VALUES (?, ?, ?, ?)"); $stmt->bind_param("ssss", $username, $email, $password, $gender); //if the user is successfully added to the database if($stmt->execute()){ //fetching the user back $stmt = $conn->prepare("SELECT id, id, username, email, gender FROM users WHERE username = ?"); $stmt->bind_param("s",$username); $stmt->execute(); $stmt->bind_result($userid, $id, $username, $email, $gender); $stmt->fetch(); $user = array( 'id'=>$id, 'username'=>$username, 'email'=>$email, 'gender'=>$gender ); $stmt->close(); //adding the user data in response $response['error'] = false; $response['message'] = 'User registered successfully'; $response['user'] = $user; } } }else{ $response['error'] = true; $response['message'] = 'required parameters are not available'; } break; |
- Now you can test the registration using a REST Client (I am here using POSTMAN).
- You see the user registration is working fine. Now lets create the User Login API.
User Login
- After registration user will login to the application. So again inside switch where we need to define the login write the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
case 'login': //for login we need the username and password if(isTheseParametersAvailable(array('username', 'password'))){ //getting values $username = $_POST['username']; $password = md5($_POST['password']); //creating the query $stmt = $conn->prepare("SELECT id, username, email, gender FROM users WHERE username = ? AND password = ?"); $stmt->bind_param("ss",$username, $password); $stmt->execute(); $stmt->store_result(); //if the user exist with given credentials if($stmt->num_rows > 0){ $stmt->bind_result($id, $username, $email, $gender); $stmt->fetch(); $user = array( 'id'=>$id, 'username'=>$username, 'email'=>$email, 'gender'=>$gender ); $response['error'] = false; $response['message'] = 'Login successfull'; $response['user'] = $user; }else{ //if the user not found $response['error'] = false; $response['message'] = 'Invalid username or password'; } } break; |
- Now you can test the login part as well.
The Complete Api Code
- This is the complete code of my Api.php file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 |
<?php require_once 'DbConnect.php'; $response = array(); if(isset($_GET['apicall'])){ switch($_GET['apicall']){ case 'signup': if(isTheseParametersAvailable(array('username','email','password','gender'))){ $username = $_POST['username']; $email = $_POST['email']; $password = md5($_POST['password']); $gender = $_POST['gender']; $stmt = $conn->prepare("SELECT id FROM users WHERE username = ? OR email = ?"); $stmt->bind_param("ss", $username, $email); $stmt->execute(); $stmt->store_result(); if($stmt->num_rows > 0){ $response['error'] = true; $response['message'] = 'User already registered'; $stmt->close(); }else{ $stmt = $conn->prepare("INSERT INTO users (username, email, password, gender) VALUES (?, ?, ?, ?)"); $stmt->bind_param("ssss", $username, $email, $password, $gender); if($stmt->execute()){ $stmt = $conn->prepare("SELECT id, id, username, email, gender FROM users WHERE username = ?"); $stmt->bind_param("s",$username); $stmt->execute(); $stmt->bind_result($userid, $id, $username, $email, $gender); $stmt->fetch(); $user = array( 'id'=>$id, 'username'=>$username, 'email'=>$email, 'gender'=>$gender ); $stmt->close(); $response['error'] = false; $response['message'] = 'User registered successfully'; $response['user'] = $user; } } }else{ $response['error'] = true; $response['message'] = 'required parameters are not available'; } break; case 'login': if(isTheseParametersAvailable(array('username', 'password'))){ $username = $_POST['username']; $password = md5($_POST['password']); $stmt = $conn->prepare("SELECT id, username, email, gender FROM users WHERE username = ? AND password = ?"); $stmt->bind_param("ss",$username, $password); $stmt->execute(); $stmt->store_result(); if($stmt->num_rows > 0){ $stmt->bind_result($id, $username, $email, $gender); $stmt->fetch(); $user = array( 'id'=>$id, 'username'=>$username, 'email'=>$email, 'gender'=>$gender ); $response['error'] = false; $response['message'] = 'Login successfull'; $response['user'] = $user; }else{ $response['error'] = false; $response['message'] = 'Invalid username or password'; } } break; default: $response['error'] = true; $response['message'] = 'Invalid Operation Called'; } }else{ $response['error'] = true; $response['message'] = 'Invalid API Call'; } echo json_encode($response); function isTheseParametersAvailable($params){ foreach($params as $param){ if(!isset($_POST[$param])){ return false; } } return true; } |
- So we are finished creating with APIs. Now lets move to android side. But before moving ahead if you need you can download my API code.
Download PHP Scripts
Android Login and Registration PHP Scripts Download
Android Login and Registration
Now here comes the android part. The first thing we will do on the android side is the register operation. So lets create a new Android Studio Project.
Creating a New Android Project
- Now create an android project with Empty Activity. I created a project named SimplifiedCoding.
- Once the project is completely loaded we will create two more activities in our project. As we will have 3 screens so first create all the 3 screens. The first screen is created by default we need to create the other two. For this right click on your package go to new -> activity -> EmptyActivity. Do this two times and create LoginActivity and ProfileActivity.
- So finally we have MainActivity for registration, LoginActivity for login and ProfileActivity for the user profile that we will show after login.
Designing User Interface
- First we will start designing all the screens. We have 3 Activities so lets start with designing the registration screen which is activity_main.xml (res->layout->activity_main.xml).
Registration Screen
- For registration screen (activity_main.xml) we will design the screen as shown below.
- To create the above UI you can use the xml code given below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 |
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout 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="net.simplifiedlearning.simplifiedcoding.MainActivity"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerVertical="true" android:orientation="vertical" android:padding="10dp"> <EditText android:id="@+id/editTextUsername" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="8dp" android:layout_marginTop="8dp" android:hint="Username" android:inputType="text" /> <EditText android:id="@+id/editTextEmail" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="8dp" android:layout_marginTop="8dp" android:hint="Email" android:inputType="textEmailAddress" /> <EditText android:id="@+id/editTextPassword" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="8dp" android:layout_marginTop="8dp" android:fontFamily="sans-serif" android:hint="Password" android:inputType="textPassword" /> <RadioGroup android:id="@+id/radioGender" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="8dp" android:layout_marginTop="8dp" android:orientation="horizontal"> <RadioButton android:id="@+id/radioButtonMale" android:layout_width="wrap_content" android:layout_height="wrap_content" android:checked="true" android:text="Male" /> <RadioButton android:id="@+id/radioButtonFemale" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Female" /> </RadioGroup> <Button android:id="@+id/buttonRegister" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="8dp" android:layout_marginTop="8dp" android:text="Register" /> <TextView android:id="@+id/textViewLogin" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="8dp" android:layout_marginTop="8dp" android:text="Already Registered?\nLogin Here" android:textAlignment="center" android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium" /> </LinearLayout> <ProgressBar android:visibility="gone" android:id="@+id/progressBar" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" /> </RelativeLayout> |
Login Screen
- Now we will design the login screen (activity_login.xml) as below.
- And for the above design you can use the following xml code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout 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="net.simplifiedlearning.simplifiedcoding.LoginActivity"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerVertical="true" android:orientation="vertical" android:padding="10dp"> <EditText android:id="@+id/editTextUsername" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="8dp" android:layout_marginTop="8dp" android:hint="Username" android:inputType="text" /> <EditText android:id="@+id/editTextPassword" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="8dp" android:layout_marginTop="8dp" android:fontFamily="sans-serif" android:hint="Password" android:inputType="textPassword" /> <Button android:id="@+id/buttonLogin" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="8dp" android:layout_marginTop="8dp" android:text="Login" /> <TextView android:id="@+id/textViewRegister" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="8dp" android:layout_marginTop="8dp" android:text="Dont' have an account?\nRegister Here" android:textAlignment="center" android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium" /> </LinearLayout> <ProgressBar android:visibility="gone" android:id="@+id/progressBar" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" /> </RelativeLayout> |
Profile Screen
- Now lastly I have following for the profile screen.
- The layout is very simple and can be built using the following xml code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 |
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout 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="net.simplifiedlearning.simplifiedcoding.ProfileActivity"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <TableLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <TableRow> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:padding="10dp" android:text="Id" android:textAppearance="@style/Base.TextAppearance.AppCompat.Large" /> <TextView android:id="@+id/textViewId" android:layout_width="wrap_content" android:layout_height="wrap_content" android:padding="10dp" android:text="1" android:textAppearance="@style/Base.TextAppearance.AppCompat.Large" /> </TableRow> <TableRow> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:padding="10dp" android:text="Username" android:textAppearance="@style/Base.TextAppearance.AppCompat.Large" /> <TextView android:id="@+id/textViewUsername" android:layout_width="wrap_content" android:layout_height="wrap_content" android:padding="10dp" android:text="probelalkhan" android:textAppearance="@style/Base.TextAppearance.AppCompat.Large" /> </TableRow> <TableRow> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:padding="10dp" android:text="Email" android:textAppearance="@style/Base.TextAppearance.AppCompat.Large" /> <TextView android:id="@+id/textViewEmail" android:layout_width="wrap_content" android:layout_height="wrap_content" android:padding="10dp" android:text="probelalkhan@gmail.com" android:textAppearance="@style/Base.TextAppearance.AppCompat.Large" /> </TableRow> <TableRow> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:padding="10dp" android:text="Gender" android:textAppearance="@style/Base.TextAppearance.AppCompat.Large" /> <TextView android:id="@+id/textViewGender" android:layout_width="wrap_content" android:layout_height="wrap_content" android:padding="10dp" android:text="Male" android:textAppearance="@style/Base.TextAppearance.AppCompat.Large" /> </TableRow> </TableLayout> <Button android:id="@+id/buttonLogout" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Logout" /> </LinearLayout> </RelativeLayout> |
- Now we have done designing all the screens. Lets add functionalities now.
Creating Helper Classes
- We will need some classes to organize our code. So lets create all the helper classes first.
User Model Class
- First we will create a class to store our user. For this create a new class named user and write the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
package net.simplifiedlearning.simplifiedcoding; /** * Created by Belal on 9/5/2017. */ //this is very simple class and it only contains the user attributes, a constructor and the getters // you can easily do this by right click -> generate -> constructor and getters public class User { private int id; private String username, email, gender; public User(int id, String username, String email, String gender) { this.id = id; this.username = username; this.email = email; this.gender = gender; } public int getId() { return id; } public String getUsername() { return username; } public String getEmail() { return email; } public String getGender() { return gender; } } |
SharedPreferences Manager Class
- When the user registers or log in we will create a login session using SharedPreferences. So to make it simple we will create a separate class that will handle the SharedPreferences operations.
- So create a new class named SharedPrefManager.java and write the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 |
package net.simplifiedlearning.simplifiedcoding; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; /** * Created by Belal on 9/5/2017. */ //here for this class we are using a singleton pattern public class SharedPrefManager { //the constants private static final String SHARED_PREF_NAME = "simplifiedcodingsharedpref"; private static final String KEY_USERNAME = "keyusername"; private static final String KEY_EMAIL = "keyemail"; private static final String KEY_GENDER = "keygender"; private static final String KEY_ID = "keyid"; private static SharedPrefManager mInstance; private static Context mCtx; private SharedPrefManager(Context context) { mCtx = context; } public static synchronized SharedPrefManager getInstance(Context context) { if (mInstance == null) { mInstance = new SharedPrefManager(context); } return mInstance; } //method to let the user login //this method will store the user data in shared preferences public void userLogin(User user) { SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putInt(KEY_ID, user.getId()); editor.putString(KEY_USERNAME, user.getUsername()); editor.putString(KEY_EMAIL, user.getEmail()); editor.putString(KEY_GENDER, user.getGender()); editor.apply(); } //this method will checker whether user is already logged in or not public boolean isLoggedIn() { SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE); return sharedPreferences.getString(KEY_USERNAME, null) != null; } //this method will give the logged in user public User getUser() { SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE); return new User( sharedPreferences.getInt(KEY_ID, -1), sharedPreferences.getString(KEY_USERNAME, null), sharedPreferences.getString(KEY_EMAIL, null), sharedPreferences.getString(KEY_GENDER, null) ); } //this method will logout the user public void logout() { SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.clear(); editor.apply(); mCtx.startActivity(new Intent(mCtx, LoginActivity.class)); } } |
Class to store Web Service URls
- We also need to define the URLs that will be called for the user registration and login. Remember using localhost will not work. You need to identify the IP. If you don’t know how to do this then you can learn it here.
- Make sure you are using the correct IP address and your device where you are testing the application can access your server. If your server is not accessible from your device then it will not work.Â
- Check this video from 6:00 to learn how you can find your IP and how you can use your real device to test your application.Â
- So create a class named URLs.java and write the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
package net.simplifiedlearning.simplifiedcoding; /** * Created by Belal on 9/5/2017. */ public class URLs { private static final String ROOT_URL = "http://192.168.101.1/Android/Api.php?apicall="; public static final String URL_REGISTER = ROOT_URL + "signup"; public static final String URL_LOGIN= ROOT_URL + "login"; } |
- Remember in the above code you need to change the IP according to your system.
Class for Sending http Request
- As we need to send POST Request to our Web Service URL. So to make it simple lets create a separate class that will handle the Request.
- So I am here creating a class named RequestHandler.java.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 |
package net.simplifiedlearning.simplifiedcoding; 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; /** * Created by Belal on 9/5/2017. */ public class RequestHandler { //this method will send a post request to the specified url //in this app we are using only post request //in the hashmap we have the data to be sent to the server in keyvalue pairs public String sendPostRequest(String requestURL, HashMap<String, String> postDataParams) { URL url; StringBuilder sb = new StringBuilder(); try { url = new URL(requestURL); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(15000); conn.setConnectTimeout(15000); conn.setRequestMethod("POST"); conn.setDoInput(true); conn.setDoOutput(true); OutputStream os = conn.getOutputStream(); BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(os, "UTF-8")); writer.write(getPostDataString(postDataParams)); writer.flush(); writer.close(); os.close(); int responseCode = conn.getResponseCode(); if (responseCode == HttpsURLConnection.HTTP_OK) { BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); sb = new StringBuilder(); String response; while ((response = br.readLine()) != null) { sb.append(response); } } } catch (Exception e) { e.printStackTrace(); } return sb.toString(); } //this method is converting keyvalue pairs data into a query string as needed to send to the server private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException { StringBuilder result = new StringBuilder(); boolean first = true; for (Map.Entry<String, String> entry : params.entrySet()) { if (first) first = false; else result.append("&"); result.append(URLEncoder.encode(entry.getKey(), "UTF-8")); result.append("="); result.append(URLEncoder.encode(entry.getValue(), "UTF-8")); } return result.toString(); } } |
- Now thats all for the helper classes. Lets code the app functionalities now.
Adding Internet Permission in the Manifest
- As we are going to perform network operation. We have to add internet permission in the AndroidManifest.xml file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="net.simplifiedlearning.simplifiedcoding"> <!-- adding internet permission --> <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" android:usesCleartextTraffic="true"> <activity android:name=".ProfileActivity"></activity> <activity android:name=".LoginActivity" /> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> |
- You also need to add usesCleartextTraffic=”true” attribute in your manifest file. We use this attribute when we want our app to communicate with http protocol. Because by default it blocks the protocols that are not https.
Completing the Registration Part
- Now come inside MainActivity.java to finish the registration.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 |
package net.simplifiedlearning.simplifiedcoding; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.text.TextUtils; import android.view.View; import android.widget.EditText; import android.widget.ProgressBar; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.Toast; import org.json.JSONException; import org.json.JSONObject; import java.util.HashMap; public class MainActivity extends AppCompatActivity { EditText editTextUsername, editTextEmail, editTextPassword; RadioGroup radioGroupGender; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //if the user is already logged in we will directly start the profile activity if (SharedPrefManager.getInstance(this).isLoggedIn()) { finish(); startActivity(new Intent(this, ProfileActivity.class)); return; } editTextUsername = (EditText) findViewById(R.id.editTextUsername); editTextEmail = (EditText) findViewById(R.id.editTextEmail); editTextPassword = (EditText) findViewById(R.id.editTextPassword); radioGroupGender = (RadioGroup) findViewById(R.id.radioGender); findViewById(R.id.buttonRegister).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //if user pressed on button register //here we will register the user to server registerUser(); } }); findViewById(R.id.textViewLogin).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //if user pressed on login //we will open the login screen finish(); startActivity(new Intent(MainActivity.this, LoginActivity.class)); } }); } private void registerUser() { final String username = editTextUsername.getText().toString().trim(); final String email = editTextEmail.getText().toString().trim(); final String password = editTextPassword.getText().toString().trim(); final String gender = ((RadioButton) findViewById(radioGroupGender.getCheckedRadioButtonId())).getText().toString(); //first we will do the validations if (TextUtils.isEmpty(username)) { editTextUsername.setError("Please enter username"); editTextUsername.requestFocus(); return; } if (TextUtils.isEmpty(email)) { editTextEmail.setError("Please enter your email"); editTextEmail.requestFocus(); return; } if (!android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) { editTextEmail.setError("Enter a valid email"); editTextEmail.requestFocus(); return; } if (TextUtils.isEmpty(password)) { editTextPassword.setError("Enter a password"); editTextPassword.requestFocus(); return; } //if it passes all the validations class RegisterUser extends AsyncTask<Void, Void, String> { private ProgressBar progressBar; @Override protected String doInBackground(Void... voids) { //creating request handler object RequestHandler requestHandler = new RequestHandler(); //creating request parameters HashMap<String, String> params = new HashMap<>(); params.put("username", username); params.put("email", email); params.put("password", password); params.put("gender", gender); //returing the response return requestHandler.sendPostRequest(URLs.URL_REGISTER, params); } @Override protected void onPreExecute() { super.onPreExecute(); //displaying the progress bar while user registers on the server progressBar = (ProgressBar) findViewById(R.id.progressBar); progressBar.setVisibility(View.VISIBLE); } @Override protected void onPostExecute(String s) { super.onPostExecute(s); //hiding the progressbar after completion progressBar.setVisibility(View.GONE); try { //converting response to json object JSONObject obj = new JSONObject(s); //if no error in response if (!obj.getBoolean("error")) { Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show(); //getting the user from the response JSONObject userJson = obj.getJSONObject("user"); //creating a new user object User user = new User( userJson.getInt("id"), userJson.getString("username"), userJson.getString("email"), userJson.getString("gender") ); //storing the user in shared preferences SharedPrefManager.getInstance(getApplicationContext()).userLogin(user); //starting the profile activity finish(); startActivity(new Intent(getApplicationContext(), ProfileActivity.class)); } else { Toast.makeText(getApplicationContext(), "Some error occurred", Toast.LENGTH_SHORT).show(); } } catch (JSONException e) { e.printStackTrace(); } } } //executing the async task RegisterUser ru = new RegisterUser(); ru.execute(); } } |
- Now you can test the registration part it should work.
- So it is working fine. But we need to code the Profile Activity now.
Completing Profile Part
- Now come inside ProfileActivity.java and write the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
package net.simplifiedlearning.simplifiedcoding; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.TextView; public class ProfileActivity extends AppCompatActivity { TextView textViewId, textViewUsername, textViewEmail, textViewGender; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_profile); //if the user is not logged in //starting the login activity if (!SharedPrefManager.getInstance(this).isLoggedIn()) { finish(); startActivity(new Intent(this, LoginActivity.class)); } textViewId = (TextView) findViewById(R.id.textViewId); textViewUsername = (TextView) findViewById(R.id.textViewUsername); textViewEmail = (TextView) findViewById(R.id.textViewEmail); textViewGender = (TextView) findViewById(R.id.textViewGender); //getting the current user User user = SharedPrefManager.getInstance(this).getUser(); //setting the values to the textviews textViewId.setText(String.valueOf(user.getId())); textViewUsername.setText(user.getUsername()); textViewEmail.setText(user.getEmail()); textViewGender.setText(user.getGender()); //when the user presses logout button //calling the logout method findViewById(R.id.buttonLogout).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { finish(); SharedPrefManager.getInstance(getApplicationContext()).logout(); } }); } } |
- Now run your application again.
- You see now the profile is working fine. You can press on the logout button and it will log you out. Now the only thing remaining is the Login Screen.
Completing Login Part
- Come inside LoginActivity.java and write the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 |
package net.simplifiedlearning.simplifiedcoding; 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.EditText; import android.widget.ProgressBar; import android.widget.Toast; import org.json.JSONException; import org.json.JSONObject; import java.util.HashMap; public class LoginActivity extends AppCompatActivity { EditText editTextUsername, editTextPassword; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); editTextUsername = (EditText) findViewById(R.id.editTextUsername); editTextPassword = (EditText) findViewById(R.id.editTextPassword); //if user presses on login //calling the method login findViewById(R.id.buttonLogin).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { userLogin(); } }); //if user presses on not registered findViewById(R.id.textViewRegister).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //open register screen finish(); startActivity(new Intent(getApplicationContext(), MainActivity.class)); } }); } private void userLogin() { //first getting the values final String username = editTextUsername.getText().toString(); final String password = editTextPassword.getText().toString(); //validating inputs if (TextUtils.isEmpty(username)) { editTextUsername.setError("Please enter your username"); editTextUsername.requestFocus(); return; } if (TextUtils.isEmpty(password)) { editTextPassword.setError("Please enter your password"); editTextPassword.requestFocus(); return; } //if everything is fine class UserLogin extends AsyncTask<Void, Void, String> { ProgressBar progressBar; @Override protected void onPreExecute() { super.onPreExecute(); progressBar = (ProgressBar) findViewById(R.id.progressBar); progressBar.setVisibility(View.VISIBLE); } @Override protected void onPostExecute(String s) { super.onPostExecute(s); progressBar.setVisibility(View.GONE); try { //converting response to json object JSONObject obj = new JSONObject(s); //if no error in response if (!obj.getBoolean("error")) { Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show(); //getting the user from the response JSONObject userJson = obj.getJSONObject("user"); //creating a new user object User user = new User( userJson.getInt("id"), userJson.getString("username"), userJson.getString("email"), userJson.getString("gender") ); //storing the user in shared preferences SharedPrefManager.getInstance(getApplicationContext()).userLogin(user); //starting the profile activity finish(); startActivity(new Intent(getApplicationContext(), ProfileActivity.class)); } else { Toast.makeText(getApplicationContext(), "Invalid username or password", Toast.LENGTH_SHORT).show(); } } catch (JSONException e) { e.printStackTrace(); } } @Override protected String doInBackground(Void... voids) { //creating request handler object RequestHandler requestHandler = new RequestHandler(); //creating request parameters HashMap<String, String> params = new HashMap<>(); params.put("username", username); params.put("password", password); //returing the response return requestHandler.sendPostRequest(URLs.URL_LOGIN, params); } } UserLogin ul = new UserLogin(); ul.execute(); } } |
- Now we have coded all the screen.You can test the login.
- As you can see it is working absolutely fine.
Android Login and Registration Source Code Download
- I tried my best to explain the things but if you are still having problems then you can get my source code from below. You need to pay me a like, share or tweet to get the source code 😛 (LOL). The source code contains the Android Studio Project, PHP Files and Database File.
Android Login and Registration Source Code Download
So thats all for this Android Login and Registration Tutorial friends. Hope you liked it. Please feel free to leave your comments if you want to discuss something regarding this Android Login and Registration Tutorial.
Also if you found this Android Login and Registration Tutorial helpful, please SHARE this among your friends. Thank You 🙂