How To Create Login And Registration Page In Android Studio
Android Login And Registration Using PHP And MySQL
This tutorial describes how to create Android Login And Registration Using PHP And MySQL database in android studio.
The user can register with his email address. So, it is important to validate that email is right email and format and make conditions for password length.
Login and Registration With PHP and MySQL database Tutorial
A. Server Side Step (local server installation)
There are three types of local servers based on operating system.
- Advertisement -
Wamp Server if you are using Windows operating system.
https://www.wampserver.com/en/
Xampp Server is the second, for mac OS.
https://www.apachefriends.org/download.html
LAMP server, for linux operating system.
- Advertisement -
https://www.linux.com/training-tutorials/easy-lamp-server-installation/
I am using Wamp server for my tutorial. Open the server and wait until it`s tray icon become green. Then open your browser and type (localhost/phpmyadmin) in address bar. Use root as user name and leave password empty and click Go. Then, create a new database and users table.
Go to WWW directory folder and create new folder with name it "loginregister" (note that you will use this name in the URL). Then create the next three PHP files.
Login And Registration With PHP And MySQL Project PHP Files
Server Connection PHP File
The next file should be in the same directory of login and registration files or change php scripts at line (require "conn.php") to the new path. ex. (require "folder/conn.php").
- Advertisement -
<?php $db_name = "users_database"; $username = "root"; $password = ""; $servename = "127.0.0.1"; $conn = mysqli_connect($servename ,$username ,$password ,$db_name ); mysqli_set_charset($conn ,"utf-8"); ?> Login PHP File
<?php require "conn.php";
$email = $_POST["email"];
$password = $_POST["psw"];
/$email = "abdo@gmail.com"; $password = "123456";/
$isValidEmail = filter_var($email, FILTER_VALIDATE_EMAIL);
if($conn){
if( $isValidEmail === false){
echo "This Email is not valid";
}else{
$sqlCheckEmail = "SELECT * FROMusers_tableWHERE
$usernameQuery = mysqli_query($conn,$sqlCheckEmail);
if(mysqli_num_rows($usernameQuery) > 0){
$sqlLogin = "SELECT * FROMusers_tableWHEREpasswordLIKE '$password'";
$loginQuery = mysqli_query($conn,$sqlLogin);
if(mysqli_num_rows($loginQuery) > 0){
echo "Login Success";
}
else{
echo "Wrong Password";
}
}else{
echo "This Email is not registered";
}
}
}
else{
echo "Connection Error";
} ?>
Register PHP File
require "conn.php"; $username = $_POST["username"]; $email = $_POST["email"]; $password = $_POST["psw"]; $mobile = $_POST["mobile"]; $gender = $_POST["gender"]; /$username = "Abdo"; $email = "abdelhamid@yahoo.com"; $password = "123456"; $mobile = "01222225522"; $gender = "Male";/ $isValidEMail = filter_var($email , FILTER_VALIDATE_EMAIL); if($conn){ if(strlen($password ) > 40 || strlen($password ) < 6){ echo "Password length must be more than 6 and less than 40"; } else if($isValidEMail === false){ echo "This Email is not valid"; }else{ $sqlCheckUname = "SELECT * FROM users_table WHERE username LIKE '$username'"; $u_name_query = mysqli_query($conn, $sqlCheckUname); $sqlCheckEmail = "SELECT * FROM users_table WHERE email LIKE '$email'"; $email_query = mysqli_query($conn, $sqlCheckEmail); if(mysqli_num_rows($u_name_query) > 0){ echo "User name allready used type another one"; }else if(mysqli_num_rows($email_query) > 0){ echo "This Email is allready registered"; }else{ $sql_register = "INSERT INTO users_table (username,email,password,phone,gender) VALUES ('$username','$email','$password','$mobile','$gender')"; if(mysqli_query($conn,$sql_register)){ echo "You are registered successfully"; }else{ echo "Failed to register you account"; } } } } else{ echo "Connection Error"; } PHP Tutorial missing.
Filter Input
To receive POST or GET values from rest API it is important to use filter input. It gets a specific external variable by name and optionally filters it. The following example show how to receive parameter from rest API using filter input:
$email = filter_input(INPUT_GET, "email"); When you send GET Request.
$email = filter_input(INPUT_POST, "email"); When you send POST Request.
B. Login and registration Android Studio Steps
Project Settings
Required Dependencies
dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation 'androidx.appcompat:appcompat:1.1.0' implementation 'androidx.constraintlayout:constraintlayout:1.1.3' testImplementation 'junit:junit:4.13' androidTestImplementation 'androidx.test:runner:1.2.0' androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0' implementation 'com.android.volley:volley:1.1.1' implementation 'com.android.support:design:28.0.0' implementation 'com.rengwuxian.materialedittext:library:2.1.4' } Manifest File
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".AppSatartActivity"> </activity> <activity android:name=".RegisterActivity" > </activity> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> Styles XML File
<resources> <!-- Base application theme. --> <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar"> <!-- Customize your theme here. --> <item name="colorPrimary">@color/colorPrimary</item> <item name="colorPrimaryDark">@color/colorPrimaryDark</item> <item name="colorAccent">@color/colorAccent</item> </style> <style name="menustyle" parent="Theme.AppCompat.Light"> <item name="android:background">@android:color/white</item> </style> Colors XML File
<?xml version="1.0" encoding="utf-8"?> <resources> <color name="colorPrimary">#008577</color> <color name="colorPrimaryDark">#008577</color> <color name="colorAccent">#008577</color> </resources> Login And Registration With PHP And MySQL Project XML Layout Files
Login Layout XML File
<?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=".MainActivity" > <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:layout_centerVertical="true" > <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:text="Login" android:textSize="30sp" android:textStyle="bold" android:layout_marginTop="10dp" android:textColor="@color/colorPrimary" /> <com.rengwuxian.materialedittext.MaterialEditText android:id="@+id/email" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:layout_marginLeft="20dp" android:layout_marginRight="20dp" android:layout_marginTop="50dp" app:met_floatingLabel="normal" android:background="@android:color/white" android:hint="Email Address" android:inputType="textEmailAddress"/> <com.rengwuxian.materialedittext.MaterialEditText android:id="@+id/password" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:layout_marginLeft="20dp" android:layout_marginRight="20dp" app:met_floatingLabel="normal" android:layout_marginTop="10dp" android:background="@android:color/white" android:hint="Password" android:inputType="textPassword"/> <androidx.appcompat.widget.AppCompatCheckBox android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Keep Me Logged In" android:buttonTint="@color/colorPrimaryDark" android:textColor="@color/colorPrimaryDark" android:layout_gravity="center" android:id="@+id/checkbox" android:layout_marginTop="10dp"/> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="20dp" android:layout_marginRight="20dp" android:layout_marginTop="20dp" android:text="Login" android:textColor="@android:color/white" android:textAllCaps="false" android:id="@+id/login" android:background="@color/colorPrimaryDark"/> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="20dp" android:layout_marginRight="20dp" android:layout_marginTop="20dp" android:text="Register" android:textColor="@android:color/white" android:textAllCaps="false" android:id="@+id/register" android:background="@color/colorPrimaryDark"/> </LinearLayout> </RelativeLayout> Register Layout XML File
<?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=".RegisterActivity"> <include android:id="@+id/toolbar" layout="@layout/bar_layout"/> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:layout_below="@+id/toolbar"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:text="Create New Account" android:gravity="center" android:textColor="@color/colorPrimaryDark" android:textSize="20dp" android:textStyle="bold"/> <com.rengwuxian.materialedittext.MaterialEditText android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="User Name" android:layout_marginRight="20dp" android:layout_marginLeft="20dp" android:layout_marginTop="10dp" android:id="@+id/username" android:padding="5dp" /> <com.rengwuxian.materialedittext.MaterialEditText android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Email Address" android:layout_marginRight="20dp" android:layout_marginLeft="20dp" android:layout_marginTop="10dp" android:id="@+id/email" android:padding="5dp" /> <com.rengwuxian.materialedittext.MaterialEditText android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Password" android:layout_marginRight="20dp" android:layout_marginLeft="20dp" android:layout_marginTop="10dp" android:inputType="textPassword" android:id="@+id/password" android:padding="5dp" /> <com.rengwuxian.materialedittext.MaterialEditText android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Mobile" android:layout_marginRight="20dp" android:layout_marginLeft="20dp" android:layout_marginTop="10dp" android:id="@+id/mobile" android:padding="5dp" /> <RadioGroup android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:layout_marginTop="10dp" android:padding="10dp" android:id="@+id/radioButton"> <RadioButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:textStyle="bold" android:textSize="14sp" android:textColor="@color/colorPrimaryDark" android:text="Male" android:buttonTint="@color/colorPrimaryDark" android:id="@+id/male"/> <RadioButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:textStyle="bold" android:textSize="14sp" android:buttonTint="@color/colorPrimaryDark" android:textColor="@color/colorPrimaryDark" android:text="Female" android:layout_marginTop="10dp" android:id="@+id/female"/> </RadioGroup> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="20dp" android:background="@color/colorPrimaryDark" android:layout_marginLeft="30dp" android:layout_marginRight="30dp" android:text="Register" android:textColor="@android:color/white" android:textAllCaps="false" android:id="@+id/register"/> </LinearLayout> </RelativeLayout> App Start Activity XML File
<?xml version="1.0" encoding="utf-8"?> <LinearLayout 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=".AppSatartActivity" android:orientation="vertical" > <include android:id="@+id/toolbar" layout="@layout/bar_layout"/> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Welcome to App Start Activity" android:textColor="@color/colorPrimaryDark" android:layout_gravity="center_vertical" android:gravity="center" android:layout_marginTop="200dp" android:textSize="40sp" android:textStyle="bold"/> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Log out" android:textAllCaps="false" android:id="@+id/logout" android:textColor="@android:color/white" android:background="@color/colorPrimaryDark" android:layout_marginTop="50dp"/> </LinearLayout> Application Bar Layout
<?xml version="1.0" encoding="utf-8"?> <androidx.appcompat.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@color/colorPrimaryDark" style="@style/Base.ThemeOverlay.AppCompat.Dark.ActionBar" app:popupTheme="@style/menustyle" android:id="@+id/toolbar"> </androidx.appcompat.widget.Toolbar> Loign And Registration With PHP And MySQL Project Java Files
Main Activity java File
public class MainActivity extends AppCompatActivity { MaterialEditText email,password; Button register,login; CheckBox checkedStatus; SharedPreferences sharedPreferences; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); email = findViewById(R.id.email); password = findViewById(R.id.password); checkedStatus = findViewById(R.id.checkbox); sharedPreferences = getSharedPreferences("UserInfo", Context.MODE_PRIVATE); String loginStatus = sharedPreferences.getString(getResources().getString(R.string.prefStatus),""); if (loginStatus.equals("loggedin")){ startActivity(new Intent(MainActivity.this,AppSatartActivity.class)); finish(); } login = findViewById(R.id.login); login.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String tex_email = email.getText().toString(); String tex_password = password.getText().toString(); if (TextUtils.isEmpty(tex_email) || TextUtils.isEmpty(tex_password)){ Toast.makeText(MainActivity.this, "All Fields Required", Toast.LENGTH_SHORT).show(); } else{ login(tex_email,tex_password); } } }); register = findViewById(R.id.register); register.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(MainActivity.this,RegisterActivity.class)); finish(); } }); } private void login(final String email, final String password){ final ProgressDialog progressDialog = new ProgressDialog(MainActivity.this); progressDialog.setTitle("Registering your account"); progressDialog.setCancelable(false); progressDialog.setCanceledOnTouchOutside(false); progressDialog.setIndeterminate(false); progressDialog.show(); String uRl = "http://10.0.2.2/login-register-app/login.php"; StringRequest request = new StringRequest(Request.Method.POST, uRl, new Response.Listener<String>() { @Override public void onResponse(String response) { if (response.equals("Login Success Welcome")){ Toast.makeText(MainActivity.this, response, Toast.LENGTH_SHORT).show(); SharedPreferences.Editor editor = sharedPreferences.edit(); if (checkedStatus.isChecked()){ editor.putString(getResources().getString(R.string.prefStatus),"loggedin"); } else{ editor.putString(getResources().getString(R.string.prefStatus),"loggedout"); } editor.apply(); startActivity(new Intent(MainActivity.this,AppSatartActivity.class)); progressDialog.dismiss(); finish(); } else { Toast.makeText(MainActivity.this, response, Toast.LENGTH_SHORT).show(); progressDialog.dismiss(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(MainActivity.this, error.toString(), Toast.LENGTH_SHORT).show(); progressDialog.dismiss(); } }){ @Override protected Map<String, String> getParams() throws AuthFailureError { HashMap<String,String> param = new HashMap<>(); param.put("email",email); param.put("psw",password); return param; } }; request.setRetryPolicy(new DefaultRetryPolicy(30000,DefaultRetryPolicy.DEFAULT_MAX_RETRIES,DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)); MySingleton.getmInstance(MainActivity.this).addToRequestQueue(request); } } Register Activity Java File
public class RegisterActivity extends AppCompatActivity { MaterialEditText userName,emailAddress,password,mobile; RadioGroup radioGroup; Button register; @RequiresApi(api = Build.VERSION_CODES.KITKAT) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_register); Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); Objects.requireNonNull(getSupportActionBar()).setTitle("Register"); getSupportActionBar().setDisplayHomeAsUpEnabled(true); userName = findViewById(R.id.username); emailAddress = findViewById(R.id.email); password = findViewById(R.id.password); mobile = findViewById(R.id.mobile); radioGroup = findViewById(R.id.radioButton); register = findViewById(R.id.register); register.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final String user_name = userName.getText().toString(); final String email = emailAddress.getText().toString(); final String txt_password = password.getText().toString(); final String txt_mobile = mobile.getText().toString(); int checkedId = radioGroup.getCheckedRadioButtonId(); RadioButton selected_gender = radioGroup.findViewById(checkedId); if (selected_gender == null){ Toast.makeText(RegisterActivity.this, "Select gender please", Toast.LENGTH_SHORT).show(); } else { final String gender = selected_gender.getText().toString(); if(TextUtils.isEmpty(user_name) || TextUtils.isEmpty(email) || TextUtils.isEmpty(txt_password) || TextUtils.isEmpty(txt_mobile)){ Toast.makeText(RegisterActivity.this, "All fields are required", Toast.LENGTH_SHORT).show(); } else{ register(user_name,email,txt_password,txt_mobile,gender); } } } }); } private void register(final String username, final String email, final String password, final String mobile, final String gender){ final ProgressDialog progressDialog = new ProgressDialog(RegisterActivity.this); progressDialog.setTitle("Registering your account"); progressDialog.setCancelable(false); progressDialog.setCanceledOnTouchOutside(false); progressDialog.setIndeterminate(false); progressDialog.show(); String uRl = "http://10.0.2.2/login-register-app/register.php"; StringRequest request = new StringRequest(Request.Method.POST, uRl, new Response.Listener<String>() { @Override public void onResponse(String response) { if (response.equals("You are registered successfully")){ Toast.makeText(RegisterActivity.this, response, Toast.LENGTH_SHORT).show(); startActivity(new Intent(RegisterActivity.this,MainActivity.class)); progressDialog.dismiss(); finish(); }else { Toast.makeText(RegisterActivity.this, response, Toast.LENGTH_SHORT).show(); progressDialog.dismiss(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(RegisterActivity.this, error.toString(), Toast.LENGTH_SHORT).show(); progressDialog.dismiss(); } }){ @Override protected Map<String, String> getParams() throws AuthFailureError { HashMap<String,String> param = new HashMap<>(); param.put("username",username); param.put("email",email); param.put("psw",password); param.put("mobile",mobile); param.put("gender",gender); return param; } }; request.setRetryPolicy(new DefaultRetryPolicy(30000,DefaultRetryPolicy.DEFAULT_MAX_RETRIES,DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)); MySingleton.getmInstance(RegisterActivity.this).addToRequestQueue(request); } } App Start Activity File
public class AppSatartActivity extends AppCompatActivity { Button logout; SharedPreferences sharedPreferences; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_app_satart); logout = findViewById(R.id.logout); sharedPreferences = getSharedPreferences("UserInfo", Context.MODE_PRIVATE); logout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putString(getResources().getString(R.string.prefStatus),"logout"); editor.apply(); startActivity(new Intent(AppSatartActivity.this,MainActivity.class)); finish(); } }); } } Singleton Java File
public class MySingleton { private static MySingleton mInstance; private RequestQueue mRequestQueue; private Context mCtx; public MySingleton(Context mCtx) { this.mCtx = mCtx; mRequestQueue = getmRequestQueue(); } public RequestQueue getmRequestQueue(){ if(mRequestQueue == null){ Cache cache = new DiskBasedCache(mCtx.getCacheDir(),1024*1024); Network network = new BasicNetwork(new HurlStack()); mRequestQueue = new RequestQueue(cache,network); mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext()); } return mRequestQueue; } public static synchronized MySingleton getmInstance(Context context){ if (mInstance == null){ mInstance = new MySingleton(context); } return mInstance; } public<T> void addToRequestQueue(Request<T> request){ mRequestQueue.add(request); } } How To Create Login And Registration Page In Android Studio
Source: https://androidhands.com/android-login-and-registration-using-php-and-mysql/
Posted by: wojciechowskiadint1981.blogspot.com

0 Response to "How To Create Login And Registration Page In Android Studio"
Post a Comment