How to create android user registration app including same email exists condition with User Login and insert User Name, Email, Password on dynamic online server in android studio tutorial with all the source code.
Project Description : In this tutorial we would going to create an android application with three different activities performs the task of User Registration where application user insert their First Name, Last Name, Email and Password. All that details would store – insert directly into MySQL database present on online hosting server. The technology to insert All the data on server including receiving and inserting data is performed using PHP language. After register user would goto login screen where he put its Email and Password to login into application. After successfully login user would redirect to the User Profile Dashboard screen. So here is the complete step by step tutorial for Android Server Login And Registration With PHP MySQL.
Main features in this project :
- User Registration Form Including same email exist condition so duplicate email user would not register again.
Project File Description :
Activity Files in this project:
- MainActivity.java
- UserLoginActivity.java
- DashboardActivity.java
Java files in this project :
- HttpParse.java
Layout files in this project :
- activity_main.xml
- activity_user_login.xml
- activity_dashboard.xml
PHP files in this project :
- DatabaseConfig.php
- UserRegistration.php
- UserLogin.php
Contents in this project Android Server Login And Registration With PHP MySQL :
- Watch Live Demo Video.
- Create database including table on your hosting server.
- Create PHP script to receive and insert registration and login details into MySQL database.
- Start a new android application project.
- Add internet permission.
- Start Coding.
1. Watch live demo :
2. Create database including table on your hosting server :
Next step is to create a database on your online server and inside that database create a fresh table which will used to insert User registration details like i did in below screenshot.
3. Create PHP script to receive and insert registration and login details into MySQL database :
Code for DatabaseConfig.php file.
<?php //Define your host here. $HostName = "localhost"; //Define your database username here. $HostUser = "id632449_androidjson"; //Define your database password here. $HostPass = "kdfjdfdskljomew9ry3873"; //Define your database name here. $DatabaseName = "id632449_androidjson"; ?>
Code for UserRegistration.php file.
<?php if($_SERVER['REQUEST_METHOD']=='POST'){ include 'DatabaseConfig.php'; $con = mysqli_connect($HostName,$HostUser,$HostPass,$DatabaseName); $F_name = $_POST['f_name']; $L_name = $_POST['L_name']; $email = $_POST['email']; $password = $_POST['password']; $CheckSQL = "SELECT * FROM UserLoginTable WHERE user_email='$email'"; $check = mysqli_fetch_array(mysqli_query($con,$CheckSQL)); if(isset($check)){ echo 'Email Already Exist'; } else{ $Sql_Query = "INSERT INTO UserLoginTable (first_name,last_name,user_email,user_password) values ('$F_name','$L_name','$email','$password')"; if(mysqli_query($con,$Sql_Query)) { echo 'Registration Successfully'; } else { echo 'Something went wrong'; } } } mysqli_close($con); ?>
Code for UserLogin.php file.
<?php if($_SERVER['REQUEST_METHOD']=='POST'){ include 'DatabaseConfig.php'; $con = mysqli_connect($HostName,$HostUser,$HostPass,$DatabaseName); $email = $_POST['email']; $password = $_POST['password']; $Sql_Query = "select * from UserLoginTable where user_email = '$email' and user_password = '$password' "; $check = mysqli_fetch_array(mysqli_query($con,$Sql_Query)); if(isset($check)){ echo "Data Matched"; } else{ echo "Invalid Username or Password Please Try Again"; } }else{ echo "Check Again"; } mysqli_close($con); ?>
4. Start a new android application project .
5. Add internet permission :
Open your Project’s AndroidManifest.xml file and add below internet permission.
<uses-permission android:name="android.permission.INTERNET" />
6. Start Coding for project Android Server Login & Register :
Code for MainActivity.java file.
package com.androidjson.userloginreg_androidjsoncom; import android.app.ProgressDialog; import android.content.Intent; import android.os.AsyncTask; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import java.util.HashMap; public class MainActivity extends AppCompatActivity { Button register, log_in; EditText First_Name, Last_Name, Email, Password ; String F_Name_Holder, L_Name_Holder, EmailHolder, PasswordHolder; String finalResult ; String HttpURL = "https://androidjsonblog.000webhostapp.com/User/UserRegistration.php"; Boolean CheckEditText ; ProgressDialog progressDialog; HashMap<String,String> hashMap = new HashMap<>(); HttpParse httpParse = new HttpParse(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //Assign Id'S First_Name = (EditText)findViewById(R.id.editTextF_Name); Last_Name = (EditText)findViewById(R.id.editTextL_Name); Email = (EditText)findViewById(R.id.editTextEmail); Password = (EditText)findViewById(R.id.editTextPassword); register = (Button)findViewById(R.id.Submit); log_in = (Button)findViewById(R.id.Login); //Adding Click Listener on button. register.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // Checking whether EditText is Empty or Not CheckEditTextIsEmptyOrNot(); if(CheckEditText){ // If EditText is not empty and CheckEditText = True then this block will execute. UserRegisterFunction(F_Name_Holder,L_Name_Holder, EmailHolder, PasswordHolder); } else { // If EditText is empty then this block will execute . Toast.makeText(MainActivity.this, "Please fill all form fields.", Toast.LENGTH_LONG).show(); } } }); log_in.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(MainActivity.this,UserLoginActivity.class); startActivity(intent); } }); } public void CheckEditTextIsEmptyOrNot(){ F_Name_Holder = First_Name.getText().toString(); L_Name_Holder = Last_Name.getText().toString(); EmailHolder = Email.getText().toString(); PasswordHolder = Password.getText().toString(); if(TextUtils.isEmpty(F_Name_Holder) || TextUtils.isEmpty(L_Name_Holder) || TextUtils.isEmpty(EmailHolder) || TextUtils.isEmpty(PasswordHolder)) { CheckEditText = false; } else { CheckEditText = true ; } } public void UserRegisterFunction(final String F_Name, final String L_Name, final String email, final String password){ class UserRegisterFunctionClass extends AsyncTask<String,Void,String> { @Override protected void onPreExecute() { super.onPreExecute(); progressDialog = ProgressDialog.show(MainActivity.this,"Loading Data",null,true,true); } @Override protected void onPostExecute(String httpResponseMsg) { super.onPostExecute(httpResponseMsg); progressDialog.dismiss(); Toast.makeText(MainActivity.this,httpResponseMsg.toString(), Toast.LENGTH_LONG).show(); } @Override protected String doInBackground(String... params) { hashMap.put("f_name",params[0]); hashMap.put("L_name",params[1]); hashMap.put("email",params[2]); hashMap.put("password",params[3]); finalResult = httpParse.postRequest(hashMap, HttpURL); return finalResult; } } UserRegisterFunctionClass userRegisterFunctionClass = new UserRegisterFunctionClass(); userRegisterFunctionClass.execute(F_Name,L_Name,email,password); } }
Code for UserLoginActivity.java file.
package com.androidjson.userloginreg_androidjsoncom; import android.app.ProgressDialog; import android.content.Intent; import android.os.AsyncTask; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import java.util.HashMap; public class UserLoginActivity extends AppCompatActivity { EditText Email, Password; Button LogIn ; String PasswordHolder, EmailHolder; String finalResult ; String HttpURL = "https://androidjsonblog.000webhostapp.com/User/UserLogin.php"; Boolean CheckEditText ; ProgressDialog progressDialog; HashMap<String,String> hashMap = new HashMap<>(); HttpParse httpParse = new HttpParse(); public static final String UserEmail = ""; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_user_login); Email = (EditText)findViewById(R.id.email); Password = (EditText)findViewById(R.id.password); LogIn = (Button)findViewById(R.id.Login); LogIn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { CheckEditTextIsEmptyOrNot(); if(CheckEditText){ UserLoginFunction(EmailHolder, PasswordHolder); } else { Toast.makeText(UserLoginActivity.this, "Please fill all form fields.", Toast.LENGTH_LONG).show(); } } }); } public void CheckEditTextIsEmptyOrNot(){ EmailHolder = Email.getText().toString(); PasswordHolder = Password.getText().toString(); if(TextUtils.isEmpty(EmailHolder) || TextUtils.isEmpty(PasswordHolder)) { CheckEditText = false; } else { CheckEditText = true ; } } public void UserLoginFunction(final String email, final String password){ class UserLoginClass extends AsyncTask<String,Void,String> { @Override protected void onPreExecute() { super.onPreExecute(); progressDialog = ProgressDialog.show(UserLoginActivity.this,"Loading Data",null,true,true); } @Override protected void onPostExecute(String httpResponseMsg) { super.onPostExecute(httpResponseMsg); progressDialog.dismiss(); if(httpResponseMsg.equalsIgnoreCase("Data Matched")){ finish(); Intent intent = new Intent(UserLoginActivity.this, DashboardActivity.class); intent.putExtra(UserEmail,email); startActivity(intent); } else{ Toast.makeText(UserLoginActivity.this,httpResponseMsg,Toast.LENGTH_LONG).show(); } } @Override protected String doInBackground(String... params) { hashMap.put("email",params[0]); hashMap.put("password",params[1]); finalResult = httpParse.postRequest(hashMap, HttpURL); return finalResult; } } UserLoginClass userLoginClass = new UserLoginClass(); userLoginClass.execute(email,password); } }
Code for DashboardActivity.java file.
package com.androidjson.userloginreg_androidjsoncom; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; public class DashboardActivity extends AppCompatActivity { Button LogOut; TextView EmailShow; String EmailHolder; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_dashboard); LogOut = (Button)findViewById(R.id.button); EmailShow = (TextView)findViewById(R.id.EmailShow); Intent intent = getIntent(); EmailHolder = intent.getStringExtra(UserLoginActivity.UserEmail); EmailShow.setText(EmailHolder); LogOut.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { finish(); Intent intent = new Intent(DashboardActivity.this, UserLoginActivity.class); startActivity(intent); Toast.makeText(DashboardActivity.this, "Log Out Successfully", Toast.LENGTH_LONG).show(); } }); } }
Code for HttpParse.java file.
package com.androidjson.userloginreg_androidjsoncom; 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; /** * Created by Juned on 3/3/2017. */ public class HttpParse { String FinalHttpData = ""; String Result ; BufferedWriter bufferedWriter ; OutputStream outputStream ; BufferedReader bufferedReader ; StringBuilder stringBuilder = new StringBuilder(); URL url; public String postRequest(HashMap<String, String> Data, String HttpUrlHolder) { try { url = new URL(HttpUrlHolder); HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setReadTimeout(14000); httpURLConnection.setConnectTimeout(14000); httpURLConnection.setRequestMethod("POST"); httpURLConnection.setDoInput(true); httpURLConnection.setDoOutput(true); outputStream = httpURLConnection.getOutputStream(); bufferedWriter = new BufferedWriter( new OutputStreamWriter(outputStream, "UTF-8")); bufferedWriter.write(FinalDataParse(Data)); bufferedWriter.flush(); bufferedWriter.close(); outputStream.close(); if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) { bufferedReader = new BufferedReader( new InputStreamReader( httpURLConnection.getInputStream() ) ); FinalHttpData = bufferedReader.readLine(); } else { FinalHttpData = "Something Went Wrong"; } } catch (Exception e) { e.printStackTrace(); } return FinalHttpData; } public String FinalDataParse(HashMap<String,String> hashMap2) throws UnsupportedEncodingException { for(Map.Entry<String,String> map_entry : hashMap2.entrySet()){ stringBuilder.append("&"); stringBuilder.append(URLEncoder.encode(map_entry.getKey(), "UTF-8")); stringBuilder.append("="); stringBuilder.append(URLEncoder.encode(map_entry.getValue(), "UTF-8")); } Result = stringBuilder.toString(); return Result ; } }
Code for activity_main.xml layout file.
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.androidjson.userloginreg_androidjsoncom.MainActivity" android:background="#FF5722" android:padding="20dp"> <TextView android:text="User Registration Form" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:id="@+id/textView" android:gravity="center" android:textSize="20dp" android:textColor="#fff"/> <EditText android:layout_width="fill_parent" android:layout_height="50dp" android:background="#fbfefd" android:inputType="textPersonName" android:ems="10" android:layout_below="@+id/textView" android:layout_centerHorizontal="true" android:layout_marginTop="10dp" android:id="@+id/editTextF_Name" android:hint="Enter Your First Name" android:gravity="center" /> <EditText android:layout_width="fill_parent" android:layout_height="50dp" android:background="#fbfefd" android:inputType="textPersonName" android:ems="10" android:layout_below="@+id/editTextF_Name" android:layout_centerHorizontal="true" android:layout_marginTop="10dp" android:id="@+id/editTextL_Name" android:hint="Enter Your Last Name" android:gravity="center"/> <EditText android:layout_width="fill_parent" android:layout_height="50dp" android:background="#fbfefd" android:inputType="textEmailAddress" android:ems="10" android:layout_below="@+id/editTextL_Name" android:layout_centerHorizontal="true" android:layout_marginTop="10dp" android:id="@+id/editTextEmail" android:hint="Enter Your Email" android:gravity="center"/> <EditText android:layout_width="fill_parent" android:layout_height="50dp" android:background="#fbfefd" android:inputType="textPassword" android:ems="10" android:layout_below="@+id/editTextEmail" android:layout_centerHorizontal="true" android:layout_marginTop="10dp" android:id="@+id/editTextPassword" android:hint="Enter Your Password" android:gravity="center"/> <Button android:text="Register" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_below="@+id/editTextPassword" android:layout_centerHorizontal="true" android:layout_marginTop="10dp" android:id="@+id/Submit" /> <Button android:text="Already Register | Log In Here" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_below="@+id/Submit" android:layout_centerHorizontal="true" android:layout_marginTop="5dp" android:id="@+id/Login" /> </RelativeLayout>
Code for activity_user_login.xml layout file.
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_user_login" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.androidjson.userloginreg_androidjsoncom.UserLoginActivity" android:background="#FF5722" android:padding="20dp"> <TextView android:text="User Login Form" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:id="@+id/textView" android:gravity="center" android:textSize="20dp" android:textColor="#fff"/> <EditText android:layout_width="fill_parent" android:layout_height="50dp" android:background="#fbfefd" android:inputType="textPersonName" android:ems="10" android:layout_below="@+id/textView" android:layout_centerHorizontal="true" android:layout_marginTop="20dp" android:id="@+id/email" android:hint="Enter Your Email Here" android:gravity="center" /> <EditText android:layout_width="fill_parent" android:layout_height="50dp" android:background="#fbfefd" android:inputType="textPassword" android:ems="10" android:layout_below="@+id/email" android:layout_centerHorizontal="true" android:layout_marginTop="20dp" android:id="@+id/password" android:hint="Enter Your Password Here" android:gravity="center"/> <Button android:text="Log In Here" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_below="@+id/password" android:layout_centerHorizontal="true" android:layout_marginTop="20dp" android:id="@+id/Login" /> </RelativeLayout>
Code for activity_dashboard.xml file.
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_dashboard" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#FF5722" android:padding="5dp" tools:context="com.androidjson.userloginreg_androidjsoncom.DashboardActivity"> <TextView android:text="SuccessFully Logged In, Your Email = " android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="150dp" android:id="@+id/textView" android:textColor="#ffffff" android:textSize="30dp" android:gravity="center" /> <TextView android:text="" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:id="@+id/EmailShow" android:textColor="#ffffff" android:textSize="30dp" android:gravity="center" android:layout_below="@+id/textView"/> <Button android:layout_marginTop="30dp" android:layout_width="fill_parent" android:layout_below="@+id/EmailShow" android:layout_height="wrap_content" android:id="@+id/button" android:text="Logout"/> </RelativeLayout>
Code for AndroidManifest.xml file.
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.androidjson.userloginreg_androidjsoncom"> <uses-permission android:name="android.permission.INTERNET" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".UserLoginActivity" /> <activity android:name=".DashboardActivity"></activity> </application> </manifest>
Screenshots:
Hey, one question, if on successful login we want to send some data from php to android code, e.g. if user john logins in php script we select his age, city and score from DB and send it from php to android , please help. i’m trying to do this for months
plz tell me how to set session of particular user n android appliction
Tajveez read my this tutorial https://androidjson.com/android-php-insert-display-select-update-delete/ using this you can get data from PHP to android after login by making a query with email or ID .
Hi, congratulations beautiful tutorial.
I have a problem, I filled out the error-free project in android studio by modifying the links you got php, i loaded the php file into my host space by entering the data in my database.
When i go to run the apk by re-writing, I get a script in the app after loading data like this: .
You can help me.
Thank you.
Marco please explain your question more briefly ?
I created the table on my host space, I compiled the app by inserting the linked php file link. When I go to the recording I write: “No accounts are created within the database. I wish I could send you pictures to show you …. Thank you
Can I have a direct contact with you? Thanks so I’m sending you the screens to figure out where I’m wrong
Marco you can send me your screenshots on my mail :- [email protected]
Thanks Admin, I wrote to you.
Marco check you mail box, i have solved your issue.
Work fine thanks Admin!!!
Welcome Marco.
If you would like to expand the project by entering a checkbox that saves the login email and password as I can do? Give me some tips on the code … Thank you
Yes you can do this by using Sharedpreferences . All you have to do is every time when user tick the check box then store that password into Sharedpreference and each time when the activity start use a if condition to check whether there is a previous password value available or not. If available then set that value into password’s edittext. You can read my these tutorials these would help you :
http://www.android-examples.com/android-sharedpreferences-insert-update-delete-remove/
http://www.android-examples.com/add-setonclicklistener-to-checkbox-in-android/
Hey Admin,
Any chance you could give me a little help please? My dashboard activity has a number of errors which i cant resolve
Yes Paddy tell me what error is coming ?
I will email you screen shots
is the email above your correct email admin?
Also.. i keep getting email already exists?