Android Login Register Using Volley library, PHP and MySQL database.
|Hey guys, Here is another android tutorial for Android Login Register Using Volley library, PHP and MySQL database.
In this tutorial we shall learn a couple of things which include
- Designing android login and register form.
- Designing android user profile page.
- Creating MySQL database for storing user data.
- Creating PHP files for handling user registration and login.
- Storing user data in MySQL database.
- Storing logged in user session in shared preference
- Finally we are going to use volley library to send and receive user login register details to and from database
.
-
- The output can be seen below.
-
- How the application operates is very simple way.
- On Successful registration user is directed to login page.
- During login the data user provide is checked against the data in the database
- If data provide during login is found correct user is directed to Profile Page
- As the user is directed to profile his username is stored in shared preference
- The importance of storing the username is to keep session of logged in user so as next time user will not need to logged in again
- If the user clicks logout his data is cleared from shared preference and he is directed to login page
Contents
- 1 Creating MySQL database
- 2 Creating PHP files
- 3 Creating new android project
- 4 Adding Volley Library to our project
- 5 Creating Volley library Singleton Class
- 6 Designing Background Gradient for Background
- 7 Creating Login Form
- 8 Creating Register Form
- 9 Creating Profile Page
- 10 MainActivity Setup
- 11 RegisterActivity Setup
- 12 ProfileActivity Setup
- 13 Requesting Android Permission
- 14 Share this:
- 15 Related
Creating MySQL database
-
- We are going to use MySQL database that comes with XAMPP.
- Ensure you have XAMPP installed you can download it form apachefriends
- Open your xampp and start both Apache and MySQL.
- Open your browser and type localhost/phpmyadmin.
- Create a new database and name it androidusers.
- Select your database and click SQL on the top bar of the page.
-
- Copy and Paste the code below and click go.
1 2 3 4 5 |
CREATE TABLE `androidusers`.`Users` ( `id` INT(100) NOT NULL AUTO_INCREMENT , `username` VARCHAR(100) NOT NULL , `useremail` VARCHAR(100) NOT NULL , `password` VARCHAR(100) NOT NULL , PRIMARY KEY (`id`)) ENGINE = InnoDB; |
-
- You will get a table similar to the one below.
Creating PHP files
-
- We are going to create 3 PHP files.
- Frist one is db.php file for connecting to database, Second is login.php file for handling user login and finally register.php file for handling user registration.
- We will use PDO “PHP DATA OBJECT” for connecting to the database.
- Open your directory C:/xampp/htdocs.
- Make a folder and name it android-users.
- Inside that folder create a file and name it db.php “C:/xampp/htdocs/android-users/db.php“.
- Using your best code editor copy and paste the code below in db.php file.
- You can change database credential if yours doesn’t match with the one below
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<?php try{ $host="mysql:host=localhost;dbname=androidusers"; $user_name="root"; $user_password=""; $dbh=new PDO($host,$user_name,$user_password); } catch(Exception $e){ exit("Connection Error".$e->getMessage()); } ?> |
-
- Create another file in android-users folder and name it login.php “C:/xampp/htdocs/android-users/login.php“
- Copy and Paste the code below to your login.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 |
<?php //getting user values $email=$_POST['email']; $password=$_POST['password']; //an array of response $output = array(); //requires database connection require_once('db.php'); //checking if email exit $conn=$dbh->prepare("SELECT * FROM users WHERE useremail=? and password=?"); $pass=md5($password); $conn->bindParam(1,$email); $conn->bindParam(2,$pass); $conn->execute(); if($conn->rowCount() == 0){ $output['error'] = true; $output['message'] = "Wrong Email or Password"; } //checking password correctness if($conn->rowCount() !==0){ $results=$conn->fetch(PDO::FETCH_OBJ); //we get both the username and password $username=$results->username; $correctpass=$results->password; $output['error'] = false; $output['message'] = "login sucessful"; $output['username'] = $username; } echo json_encode($output); ?> |
-
- Create another file in android-users folder and name it register.php “C:/xampp/htdocs/android-users/register.php“
- Copy and Paste the code below to your register.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 |
<?php //getting user values $username=$_POST['username']; $email=$_POST['email']; $password=$_POST['password']; //array of responses $output=array(); //require database require_once('db.php'); //checking if email exists $conn=$dbh->prepare('SELECT useremail FROM users WHERE useremail=?'); $conn->bindParam(1,$email); $conn->execute(); //results if($conn->rowCount() !==0){ $output['error'] = true; $output['message'] = "Email Exists Please Login"; }else{ $conn=$dbh->prepare('INSERT INTO users(username,useremail,password) VALUES (?,?,?)'); //encrypting the password $pass=md5($password); $conn->bindParam(1,$username); $conn->bindParam(2,$email); $conn->bindParam(3,$pass); $conn->execute(); if($conn->rowCount() == 0) { $output['error'] = true; $output['message'] = "Registration failed, Please try again"; } elseif($conn->rowCount() !==0){ $output['error'] = false; $output['message'] = "Succefully Registered"; $output['username']=$username; } } echo json_encode($output); ?> |
-
- Now we are done on web part. We get started on android part.
Creating new android project
-
- Open your android studio click File => New Project.
- Give it a name you can all it LoginRegister.
- Click Next = > Empty activity => finish.
Adding Volley Library to our project
-
- Volley library is used for transmitting network data.
- We will use volley to help us pass data from android app to our MySQL database.
- You can learn more about from here
- Include the code below in your build.gradle file .
1 2 3 4 5 |
compile 'com.android.volley:volley:1.0.0' |
Creating Volley library Singleton Class
-
- To improve volley efficiency we will create VolleySingleton class.
- This class will help use to encapsulate RequestQueue and other volley functionality.
- Create a java class by right clicking on java folder => new => java class and name it VolleySingleton.
- Open VolleySingleton and paste the code 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 |
package com.example.kamere.loginregister; import android.content.Context; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.toolbox.Volley; /** * Created by Kamere on 4/15/2018. */ public class VolleySingleton { private static VolleySingleton mInstance; private RequestQueue mRequestQueue; private static Context mCtx; private VolleySingleton(Context context) { mCtx = context; mRequestQueue = getRequestQueue(); } public static synchronized VolleySingleton getInstance(Context context) { if (mInstance == null) { mInstance = new VolleySingleton(context); } return mInstance; } public RequestQueue getRequestQueue() { if (mRequestQueue == null) { // getApplicationContext() is key, it keeps you from leaking the // Activity or BroadcastReceiver if someone passes one in. mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext()); } return mRequestQueue; } public <> void addToRequestQueue(Request<> req) { getRequestQueue().add(req); } } |
-
- To keep session of logged in user in android we will use shared preference.
- In our shared preference we shall create a storage file and name it larntech.
- We shall Create username key for storing the name of the logged in user.
- We will create methods to store user data, to check is user is logged in and to logout user.
- Create a java class by right clicking on java folder => new => java class and name it Sharedpref.
- Copy and paste the code below to your SharedPref 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 |
package com.example.kamere.loginregister; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; /** * Created by Kamere on 4/15/2018. */ public class SharedPref { //Storage File public static final String SHARED_PREF_NAME = "larntech"; //Username public static final String USER_NAME = "username"; public static SharedPref mInstance; public static Context mCtx; public SharedPref(Context context) { mCtx = context; } public static synchronized SharedPref getInstance(Context context) { if (mInstance == null) { mInstance = new SharedPref(context); } return mInstance; } //method to store user data public void storeUserName(String names) { SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putString(USER_NAME, names); editor.commit(); } //check if user is logged in public boolean isLoggedIn() { SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE); return sharedPreferences.getString(USER_NAME, null) != null; } //find logged in user public String LoggedInUser() { SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE); return sharedPreferences.getString(USER_NAME, null); } //Logout user public void logout() { SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.clear(); editor.commit(); mCtx.startActivity(new Intent(mCtx, MainActivity.class)); } } |
Designing Background Gradient for Background
-
- Create a new file in your drawable folder and call it background_color.xml .
-
- Open that file and paste the code below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<?xml version="1.0" encoding="utf-8"?> <layer-list xmlns:android="http://schemas.android.com/apk/res/android"> <!-- Bottom 2dp Shadow --> <item> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <gradient android:endColor="#f96304d1" android:startColor="#d0538abe" android:centerX="90%" android:centerY="100%" android:type="linear" android:angle="135"/> </shape> </item> </layer-list> |
-
- Background preview will look as shown below.
-
- Open colors.xml file located under values folder and change the primary color to match with the background.
- Copy and Paste the code below to your colors.xml file
1 2 3 4 5 6 7 8 9 10 |
<?xml version="1.0" encoding="utf-8"?> <resources> <color name="colorPrimary">#6823cf</color> <color name="colorPrimaryDark">#6a32cf</color> <color name="colorAccent">#f2f2f2</color> </resources> |
-
- Open your styles.xml file located under values folder and include NoActionBar theme.
- Copy and Paste the code below in your styles.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<resources> <!-- Base application theme. --> <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar"> <!-- 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="AppTheme.NoActionBar"> <item name="windowActionBar">false</item> <item name="windowNoTitle">true</item> <item name="colorControlHighlight">#4db9b5ba</item> </style> </resources> |
Creating Login Form
-
- The login form will contain email and password edit text, Login Button and Register page link.
- Open your activity_main file which is under Res => Layout => activity_main.
- Copy and paste the code below to your activity_main 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 |
<?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" android:background="@drawable/background_color" tools:context="com.example.kamere.loginregister.MainActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="61dp" android:text="Login Your Account" android:textColor="#fff" android:textSize="25dp" android:textStyle="bold|normal" /> <EditText android:id="@+id/loginEmail" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Email" android:inputType="text" android:paddingBottom="18dp" android:paddingLeft="8dp" android:paddingRight="8dp" android:layout_marginTop="190dp" android:textColor="#fff" android:textColorHint="#ffffff" android:backgroundTint="#cda7f4" android:textSize="10pt" /> <EditText android:id="@+id/loginPassword" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/loginEmail" android:hint="Password" android:inputType="textPassword" android:paddingBottom="18dp" android:paddingLeft="8dp" android:paddingRight="8dp" android:textColor="#fff" android:textColorHint="#ffffff" android:backgroundTint="#cda7f4" android:textSize="10pt" /> <Button android:id="@+id/btnLogin" android:layout_width="match_parent" android:layout_height="120px" android:paddingRight="30dp" android:paddingLeft="30dp" android:layout_marginTop="15dp" android:layout_below="@+id/loginPassword" android:layout_centerHorizontal="true" android:background="#c85ae49a" android:text="Login" android:textAllCaps="false" android:textColor="#ffffff" android:textSize="58px" /> <TextView android:id="@+id/register" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/btnLogin" android:layout_centerHorizontal="true" android:layout_marginTop="15dp" android:textSize="20dp" android:text="Or Register" android:textColor="#fff" /> </RelativeLayout> |
-
- The form should appear as shown below.
-
- To remove ActionBar open Manifest file add theme No Action Bar to your MainActivity.
1 2 3 4 5 6 7 8 |
<activity android:name=".MainActivity" android:theme="@style/AppTheme.NoActionBar"> </activity> |
Creating Register Form
-
- Create an Empty Activity.
- right click Layout => New => Activity => Empty Activity and Name it activity_register.
- Register form will contain username,email,password and confirm password fields, register button and link to login page.
- Open activity_register and copy paste the code 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 100 101 102 103 104 105 106 107 108 109 |
<?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" android:background="@drawable/background_color" tools:context="com.example.kamere.loginregister.RegisterActivity"> "> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="51dp" android:text="Create Account" android:textColor="#fff" android:textSize="25dp" android:textStyle="bold|normal" /> <EditText android:id="@+id/registerName" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="130dp" android:hint="Username" android:inputType="text" android:paddingBottom="18dp" android:paddingLeft="8dp" android:paddingRight="8dp" android:textColor="#fff" android:textColorHint="#ffffff" android:backgroundTint="#e6d9f4" android:textSize="10pt" /> <EditText android:id="@+id/registerEmail" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/registerName" android:hint="Email" android:inputType="text" android:paddingBottom="18dp" android:paddingLeft="8dp" android:paddingRight="8dp" android:textColor="#fff" android:textColorHint="#ffffff" android:backgroundTint="#e6d9f4" android:textSize="10pt" /> <EditText android:id="@+id/registerPassword" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/registerEmail" android:hint="Password" android:inputType="textPassword" android:paddingBottom="18dp" android:paddingLeft="8dp" android:paddingRight="8dp" android:textColor="#fff" android:textColorHint="#fff" android:backgroundTint="#e6d9f4" android:textSize="10pt" /> <EditText android:id="@+id/confirmpassword" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/registerPassword" android:hint="Confirm Password" android:inputType="textPassword" android:paddingBottom="18dp" android:paddingLeft="8dp" android:paddingRight="8dp" android:textColor="#fff" android:textColorHint="#ffffff" android:backgroundTint="#e6d9f4" android:textSize="10pt" /> <Button android:id="@+id/btnRegister" android:layout_width="match_parent" android:layout_height="120px" android:paddingRight="30dp" android:paddingLeft="30dp" android:layout_marginTop="15dp" android:layout_below="@+id/confirmpassword" android:layout_centerHorizontal="true" android:text="Register" android:textAllCaps="false" android:textColor="#ffffff" android:background="#c85ae49a" android:textSize="58px" /> <TextView android:id="@+id/login" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/btnRegister" android:layout_centerHorizontal="true" android:layout_marginTop="15dp" android:textSize="20dp" android:text="Or Login" android:textColor="#fff" /> </RelativeLayout> |
-
- The output for register activity will be as shown below.
-
- To remove ActionBar open Manifest file add theme No Action Bar to your RegisterActivity.
1 2 3 4 5 6 7 8 |
<activity android:name=".RegisterActivity" android:theme="@style/AppTheme.NoActionBar" android:label="Register"> </activity> |
Creating Profile Page
-
- Create an Empty Activity right click Layout => New => Activity => Empty Activity and Name it activity_profile.
- Profile page will display the name of logged in user and a logout button.
- Copy and Paste the code below in your activity_profile
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 |
<?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="com.example.kamere.loginregister.ProfileActivity"> <TextView android:id="@+id/username" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentStart="true" android:layout_alignParentTop="true" android:layout_marginStart="32dp" android:layout_marginTop="68dp" android:text="Username : " android:textColor="#000" android:textSize="20dp" android:textStyle="normal|bold" /> <Button android:id="@+id/btnLogout" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignStart="@+id/username" android:layout_below="@+id/username" android:layout_marginTop="50dp" android:background="#f5e966" android:text="Log Out" android:textAllCaps="false" android:textColor="#000" android:textSize="15dp" /> </RelativeLayout> |
-
- The output will be similar to image below
MainActivity Setup
-
- Open your MainActivity located at java => your package => MainActivity.
- This class will handle your login form.
- Receives data from activity_main and pass it to login.php .
- Remember to change loginURL to match you url.
- Copy and paste the code below in your MainActivity.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 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 |
package com.example.kamere.loginregister; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Vibrator; 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.TextView; import android.widget.Toast; import com.android.volley.AuthFailureError; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import org.json.JSONException; import org.json.JSONObject; import java.util.HashMap; import java.util.Map; public class MainActivity extends AppCompatActivity { EditText email_input,password_input; TextView register; Button btnLogin; Vibrator v; //change this to match your url final String loginURL = "http://192.168.43.254/android-users/login.php"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); email_input = findViewById(R.id.loginEmail); password_input = findViewById(R.id.loginPassword); register = findViewById(R.id.register); btnLogin = findViewById(R.id.btnLogin); v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE); btnLogin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { validateUserData(); } }); //when someone clicks on login register.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(getApplicationContext(),RegisterActivity.class); startActivity(intent); } }); } private void validateUserData() { //first getting the values final String email = email_input.getText().toString(); final String password = password_input.getText().toString(); //checking if email is empty if (TextUtils.isEmpty(email)) { email_input.setError("Please enter your email"); email_input.requestFocus(); // Vibrate for 100 milliseconds v.vibrate(100); btnLogin.setEnabled(true); return; } //checking if password is empty if (TextUtils.isEmpty(password)) { password_input.setError("Please enter your password"); password_input.requestFocus(); //Vibrate for 100 milliseconds v.vibrate(100); btnLogin.setEnabled(true); return; } //validating email if (!android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) { email_input.setError("Enter a valid email"); email_input.requestFocus(); //Vibrate for 100 milliseconds v.vibrate(100); btnLogin.setEnabled(true); return; } //Login User if everything is fine loginUser(); } private void loginUser() { //first getting the values final String email = email_input.getText().toString(); final String password = password_input.getText().toString(); //Call our volley library StringRequest stringRequest = new StringRequest(Request.Method.POST,loginURL, new Response.Listener<String>() { @Override public void onResponse(String response) { try { // Toast.makeText(getApplicationContext(),response.toString(), Toast.LENGTH_SHORT).show(); JSONObject obj = new JSONObject(response); if (obj.getBoolean("error")) { Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show(); } else { //getting user name String Username = obj.getString("username"); Toast.makeText(getApplicationContext(),Username, Toast.LENGTH_SHORT).show(); //storing the user in shared preferences SharedPref.getInstance(getApplicationContext()).storeUserName(Username); //starting the profile activity finish(); startActivity(new Intent(getApplicationContext(), ProfileActivity.class)); } } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(getApplicationContext(),"Connection Error"+error, Toast.LENGTH_SHORT).show(); error.printStackTrace(); } }) { @Override protected Map<String, String> getParams() throws AuthFailureError { Map<String, String> params = new HashMap<>(); params.put("email", email); params.put("password", password); return params; } }; VolleySingleton.getInstance(MainActivity.this).addToRequestQueue(stringRequest); } } |
RegisterActivity Setup
Open your RegisterActivity class located at java => your package => RegisterActivity.
-
- This file handles user registration.
- Receives data from activity_register and pass it to register.php.
- register.php inserts the data in the database and then user is directed to login page.
- Copy and Paste the code below to your RegisterActivity.java 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 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 |
public class RegisterActivity extends AppCompatActivity { EditText username,email,password,cpassword; TextView login; Button btnRegister; Vibrator v; //change to your register url final String registerUrl = "http://192.168.43.254/android-users/register.php"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_register); username = (EditText) findViewById(R.id.registerName); email = (EditText) findViewById(R.id.registerEmail); password = (EditText) findViewById(R.id.confirmpassword); cpassword = (EditText) findViewById(R.id.confirmpassword); btnRegister = (Button) findViewById(R.id.btnRegister); login = (TextView) findViewById(R.id.login); v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE); btnRegister.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { validateUserData(); } }); login.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(getApplicationContext(),MainActivity.class); startActivity(intent); } }); } private void validateUserData() { //find values final String reg_name = username.getText().toString(); final String reg_email = email.getText().toString(); final String reg_password = cpassword.getText().toString(); final String reg_cpassword = cpassword.getText().toString(); // checking if username is empty if (TextUtils.isEmpty(reg_name)) { username.setError("Please enter username"); username.requestFocus(); // Vibrate for 100 milliseconds v.vibrate(100); return; } //checking if email is empty if (TextUtils.isEmpty(reg_email)) { email.setError("Please enter email"); email.requestFocus(); // Vibrate for 100 milliseconds v.vibrate(100); return; } //checking if password is empty if (TextUtils.isEmpty(reg_password)) { password.setError("Please enter password"); password.requestFocus(); //Vibrate for 100 milliseconds v.vibrate(100); return; } //validating email if (!android.util.Patterns.EMAIL_ADDRESS.matcher(reg_email).matches()) { email.setError("Enter a valid email"); email.requestFocus(); //Vibrate for 100 milliseconds v.vibrate(100); return; } //checking if password matches if (!reg_password.equals(reg_cpassword)) { password.setError("Password Does not Match"); password.requestFocus(); //Vibrate for 100 milliseconds v.vibrate(100); return; } //After Validating we register User registerUser(); } private void registerUser() { final String reg_username = username.getText().toString(); final String reg_email = email.getText().toString(); final String reg_password = cpassword.getText().toString(); //Call our volley library StringRequest stringRequest = new StringRequest(Request.Method.POST,registerUrl, new Response.Listener<String>() { @Override public void onResponse(String response) { try { JSONObject obj = new JSONObject(response); if (obj.getBoolean("error")) { Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show(); } else { //starting the login activity startActivity(new Intent(getApplicationContext(),MainActivity.class)); } } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(getApplicationContext(),"Connection Error"+error, Toast.LENGTH_SHORT).show(); error.printStackTrace(); } }) { @Override protected Map<String, String> getParams() throws AuthFailureError { Map<String, String> params = new HashMap<>(); params.put("username",reg_username); params.put("email", reg_email); params.put("password", reg_password); return params; } }; VolleySingleton.getInstance(RegisterActivity.this).addToRequestQueue(stringRequest); } } |
ProfileActivity Setup
-
- Open your ProfileActivity class located at java => your package => ProfileActivity.
- Oncreate method will check if user is logged in.
- If the user is logged in we will get the username stored in the shared preference and display it.
- if user is not logged in he/she will be redirected to login page.
- When logout button is clicked user data is cleared and is redirected to login page.
- Copy and Paste the code below to your ProfileActivity class.
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 |
package com.example.kamere.loginregister; import android.content.Intent; import android.content.SharedPreferences; 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 ProfileActivity extends AppCompatActivity { TextView username; Button btnLogout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_profile); username = findViewById(R.id.username); btnLogout = findViewById(R.id.btnLogout); //check if user is logged in if (!SharedPref.getInstance(this).isLoggedIn()) { startActivity(new Intent(this, MainActivity.class)); finish(); } //getting logged in user name String loggedUsename = SharedPref.getInstance(this).LoggedInUser(); username.setText("Username : "+loggedUsename); //logging out btnLogout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { finish(); SharedPref.getInstance(getApplicationContext()).logout(); } }); } } |
Requesting Android Permission
-
- The final step is to add permission in the manifest file
- Include the permission below in your manifest file.
1 2 3 4 5 6 |
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.VIBRATE" /> |
-
- To Declare ProfileActivity as the launcher activity, Include the code below in your manifest file at .ProfileActivity
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 |
public class ProfileActivity extends AppCompatActivity { TextView username; Button btnLogout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_profile); username = findViewById(R.id.username); btnLogout = findViewById(R.id.btnLogout); //check if user is logged in if (!SharedPref.getInstance(this).isLoggedIn()) { startActivity(new Intent(this, MainActivity.class)); finish(); } //getting logged in user name String loggedUsename = SharedPref.getInstance(this).LoggedInUser(); username.setText("Username : "+loggedUsename); //logging out btnLogout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { finish(); SharedPref.getInstance(getApplicationContext()).logout(); } }); } } |
-
- The final code for your manifest file should look like the one 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 |
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.kamere.loginregister"> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.VIBRATE" /> <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=".MainActivity" android:theme="@style/AppTheme.NoActionBar"></activity> <activity android:name=".ProfileActivity" android:label="Profile" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".RegisterActivity" android:theme="@style/AppTheme.NoActionBar" android:label="Register" ></activity> </application> </manifest> |
-
- Now run your app and you will get output similar to one below.
- Register Page
-
- Login page
-
- Profile Page
-
- Database
- To download the source code click the link here.
- That’s all, If you have a question or need help please comment below.