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 🙂

Hi, my name is Belal Khan and I am a Google Developers Expert (GDE) for Android. The passion of teaching made me create this blog. If you are an Android Developer, or you are learning about Android Development, then I can help you a lot with Simplified Coding.
Sir Belal how to make change profile/edit profile for registered user profile? please help me.
Any chance of forgot password feature
i am getting an error org.json.JSONException: End of input at character 0 of , how to resolve this ?
i am getting this error java.lang.String cannot be converted to JSONObject how to resolve this
i have used the exact code.
Can you paste here the response you are getting from the server?
@Deepak
Can you find the solution ?
this is your PHP error
check your PHP code
hi im getting simply “[ ]” in postman for apicall=signup
change GET to POST in Postman
Hi Belal. Can you explain this to me please.. I got error “Cannot resolve symbol s” in mainactivity.java line129. Why we use “s” in there
how can i get the ip ?? I am using a free hosting yovamacua.hospedajeymas.com but it connects to me I do not know what the ip is.
If you are using a free hosting.. then you have to use the free sub domain that you got from that free hosting.. I would recommend that don’t use a free host, they just suck and you might face a lot of troubles. Use XAMPP, WAMP or a paid hosting.
Error :- System.err: org.json.JSONException: End of input at character 0 of
JSONObject obj = new JSONObject(s); Here is show the error and class RegisterUser extends AsyncTask Here its show the error.
I got this error too, how can I solve this?
if i have message that some error occured what is the wrong in the code??
could you make an example where after logging loads the data from another table and not the profile?
not getting any response..no login no sign up…i changed ip address to my pc’s ip but still not getting response.
am getting the same error no response on both login and register,what could be the problem
email me
am getting the same error… did you find the solution
Api.php showing me this message:
connect_error) { die(“Connection failed: ” . $conn->connect_error); } {“error”:true,”message”:”Invalid API Call”}
Do i have to make changes in Api.php as well?
Did you find any solution to this?
Have you found a solution for this?
since you are using latest version of xampp server
Paste this code
<?
$servername = "localhost";
$username = "root";
$password = "";
$database = "android";
mysqli_connect("$servername", "$username", "$password", "$database");
Kudos Belal. Works Perfect
i get this error
connect_error) { die(“Connection failed: ” . $conn->connect_error); } {“error”:true,”message”:”Invalid API Call”}
hello,
when i try to test signup i see this error on postman,
Fatal error: Call to a member function prepare() on null in
do you know how can i fix this?
The problem is in your SQL Query. Try executing it directly on PHPMYADMIN and check if it is working or not.
Thank you its works perfect.
Very hepful post. Thank you very much!!
Cannot connect to local server. No error message or any exception.
When registering user, some error occured.
When registering user, some error occured.
Android Login and Registration Tutorial with PHP MySQL
I have been attempting to download the source code for the above project. Besides subscribing to the newsletter, I have also provided the requested like for access to the download, but still I just get a screen which says download is locked.
How do I / WE solve this dilema.
Thanks
I sent the code link to your email, the email that you’ve given here.
Android Login and Registration Tutorial with PHP MySQL
I have been attempting to download the source code for the above project. Besides subscribing to the newsletter, I have also provided the requested like for access to the download, but still I just get a screen which says download is locked.
How do I / WE solve this dilema.
Thanks
Sent the link to your email.
hello
thank you so much for this tutorials. but I face difficulty in “SharedPreferences” means when I update data in the database table and again load profile activity, its display old data. I want updated data. please help asap.
I am getting socket time out exception and org.json.JSONException: End of input at character 0 of this exception please solve this issue.
Check you are getting a valid json from the api or not?
Hello Belal sir i got the error is org.json.JSONException: Value http of type java.lang.String cannot be converted to JSONObject how to solve this problem.
my exception error is solved but now in php code is not run successfully. the error is {“error”:true,”message”:”required parameters are not available”} plz reply fast sir.
hi dude it seems u forgot to add
public int getId() {
return id;
}
in User Class
hope u update your code
yaa this article was such a great information thanku belal sir
please can you give me your Api.php is not working for me
Hello, when I use postman to test Api.php?apicall=signup i have an error :
{“error”:true,”message”:”required parameters are not available”}
I don’t understand why because i used ur source code, if you have a solution .. i want it please ! ^^
W/System.err: org.json.JSONException: No value for user
04-06 16:18:39.254 5162-5162/com.zelectrospace.ramikki W/System.err: at org.json.JSONObject.get(JSONObject.java:389)
at org.json.JSONObject.getJSONObject(JSONObject.java:609)
at com.zelectrospace.ramikki.account$1UserLogin.onPostExecute(account.java:134)
at com.zelectrospace.ramikki.account$1UserLogin.onPostExecute(account.java:110)
at android.os.AsyncTask.finish(AsyncTask.java:636)
at android.os.AsyncTask.access$500(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:653)
at android.os.Handler.dispatchMessage(Handler.java:102)
04-06 16:18:39.255 5162-5162/com.zelectrospace.ramikki W/System.err: at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Did you have a solution to this?
Thank you. This tutorial is very useful for me…
Now, I want to upload the image from registration form and save this image on my server folder..how can I do this..please give me a suggestion…
Hello, I’m a beginner in PHP.
I would like to understand what this stanza means “$ stmt = $ conn-> prepare (” SELECT id, username, in “linking the prepare, because for me it did not work.
I’m using the PHP 7.0 bug.
Is there a relationship?
when I use postman to test Api.php?apicall=signup i have an error :
{“error”:true,”message”:”required parameters are not available”}
Sir if my ‘KEY_ID’ type is STRING how can i complete SharedPreferences Manager Class ? because it must be use INT but i already have data the ID type is STRING
thank you…
Thanks, excellent Work
Everything works fine, but when i register or login after i fill the blanks with right information the onPostExecute wont take me to ProfileActivity using startActivity, i tried changing profileactivity to mainactivity in startActivity argument and it also didnt start the activity..please help me with this problem..
Did you ever find a solution to this?
Hello , How can i check this in postman, i am getting error like connected{“error”:true,”message”:”required parameters are not available”}
Its not an error it is a response. It clearly saying that the required parameters are not available. You have to pass all the required parameters while sending the request.
Sir, I’m getting error even after passing all the parameters
Its shows Invalis API calss why such errors coming
when i login or register, its not connecting to Api.php file.. can you please help me
Register page does not open the profile page .progress bar shows and it stays on the same page .
{“error”:true,”message”:”Invalid API Call”}
what to do?
Simply wish to say your article is as astonishing. The clarity on your publish is just nice and that i could suppose you’re knowledgeable on this subject. Well with your permission allow me to take hold of your feed to stay up to date with drawing close post. Thank you one million and please continue the rewarding work.
hi sir the user is inserted into database but the android app crashes along the line
Hi. I really appreciate for all of your tutorials. While executing Login and Sing Up tutorials, I got an error that says error org.json.JSONException: End of input at character 0 of . I kind of did research for this error and some says I have to put sending request method into doInBackground because while getting no message, the program is parsing Json. I just wanted to know if the code above works as it is. Thanks again from South Korea.
It’s working on local host but when I work with online server it’s showing 500 error.
very helpful code thank you so much
Hey Belal,
That’s one coolest project i’ve seen till date.
I just have one small problem.This code is successfully compiling and running too.
The only problem is that , the page isn’t responding. I inserted values through postman and those are entered into mysql database. But the values send through this Android app aren’t. The values aren’t entring the database.
Can you tell me where the error i made please.
Answer me ASAP. :))
Thanks.
Good way of explaining, and pleasant paragraph to take data concerning my presentation subject, which i am going to convey in academy.
Attempt to invoke virtual method ‘void android.widget.ProgressBar.setVisibility(int)’ on a null object reference
this error shown in this code please help me
You forget to initialize the progressbar, it is a very simple NullPointerException.
Sir in Web Service URL file U wrote “You need to identify the IP” wht does it mean please explain it to me …
{“error”:true,”message”:”Invalid API Call”}
error on reg
You are passing the wrong get parameter, cross check it carefully.
not working for me i tried at localhost
Terrific post however I was wanting to know if you could write a litte more on this topic? I’d be very grateful if you could elaborate a little bit further. Appreciate it!
If you want a very detailed explanation, you can watch this series on Youtube.
https://www.youtube.com/watch?v=kxKwuUOLGEc&list=PLk7v1Z2rk4hhGfJw-IQCm6kjywmuJX4Rh
You actually make it seem so easy together with your presentation but I in finding this matter to be really something that I think I might never understand. It seems too complex and very huge for me. I am looking ahead in your next publish, I will attempt to get the grasp of it!
im getting error on sharedPrefManager saying cannot resolve method getId(). I have tried creating a getId method in the user class but still does not work. What else can i do to fix this?
Did you try downloading my source code?
the link is not found. would you send the link to my email?
Links are updated. You can download now.
unable to download the code
nothing happen when i click on the register button the data is not going to db even not enter in to the next activity. plz tell me sol of this prolem
Hello Sir, I tried above code any for registration it works perfectly but for login part when i’m testing it on postman and giving username and password parameter its showing invalid username and password , though its right its giving same error for all registered user so can you tell me what is the error in login.php?please….
Thank you so much for the detailed instructions. Its useful as the source code is embedded in your tutorial so that we can try ourself.
Please keep doing such great works.. Hats off sir
Everything is working perfect except getID. SIr please add this code. You have left it undone …I took source code from this page itself. Please look into this sir
Can’t download the source code
Sir, You saved my life. Thank You
hey i got message login successful but it doesnt go to next activity ….
i used fname instead of username everywhere
help please
i got this…
W/System.err: org.json.JSONException: No value for fname
W/System.err: at org.json.JSONObject.get(JSONObject.java:392)
at org.json.JSONObject.getString(JSONObject.java:553)
W/System.err: at com.example.ok.LoginActivity$1UserLogin.onPostExecute(LoginActivity.java:134)
at com.example.ok.LoginActivity$1UserLogin.onPostExecute(LoginActivity.java:107)
at android.os.AsyncTask.finish(AsyncTask.java:695)
at android.os.AsyncTask.-wrap1(Unknown Source:0)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:712)
All Db connection code is properly saved but the received msg connection failed that could’t understand please help
i’m posting all parameters with ResTer Client on firefox but i still ge this response
{“error”:true,”message”:”required parameters are not available”}
Wow, It’s working perfect. Thank you for your tutorial.
Getting a log error
W/System.err: org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
never writes to database
You are not getting proper result from your php scripts. Check that.
i got this message {“error”:true,”message”:”Invalid API Call”} when run api.php file.when try to run project only login and sign up page show nothing activity happen next no registration no login
Hi Belal ,
Very nicely explained. It helped me a lot. I need a small help. I am able to update and read the database using method explained above. I need a small help.
I am trying to read multiple records/rows from the database and then trying to display them on listview.
I have added another switch case in the SQL API. However my query will be returning multiple rows. I am wondering how can i receive multiple rows in the app and then display them
$stmt = $conn->prepare(“SELECT col1,col2 FROM my_tableWHERE col3 = ? “);
$stmt->bind_param(“s”,$col3);
$stmt->execute();
$stmt->bind_result($col1, $col2);
$stmt->fetch();
$user = array(
‘col1’=>$col1,
‘col2’=>$col2
);
Great tutorial. Have enough insight
hi again you removed my comment with out tell me why your downloaded app not working
sorry it didn’t remove but didn’t answer
Niceeeeee work. but i have a little Problem.
i have delete the “Gender” lines and all works good but in the Profile Page schows me now the Username the Email Adress instead Username and instead my Email shows me the md5 Password.
Wehre must i look to fix this
It’s good but, DbConnect.php file how safe to public? the file show username and password.
Please make a video, How to make 405 error and 403 error in xampp server.