Hello friends we have already covered a couple of tutorials  for android login example using php mysql.
But in the above mentioned tutorials, we were not maintaining the login session. Like once user has logged in to our app, user do not need to login again.
So in this android login example we will see how we can do Android User Session Management. And we will give a logout button from where user can logout from our app.
Android Login Example – Video
- You can check the following video to know exactly what we will be creating in this android log in tutorial.
- Now if you want to create this android login example, go ahead in this tutorial.
Creating Database and PHP Scripts
- For this tutorial I am using wamp server.
- This is my MySQL database.
- As you can see I have a very small table with only three columns (id, email and password). You have to create the same.
- Now we will create two php script. The first one to connect to the database (dbConnect.php).
1 2 3 4 5 6 7 8 9 |
<?php define('HOST','localhost'); define('USER','root'); define('PASS',''); define('DB','androiddb'); $con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect'); |
Quick Tip: Are you are thinking that closing php tag  ‘ ?> ‘ is missing? Actually we do not need the closing tag for the files having only php code on it. You can still put the ?> closing tag but it will not make any difference.
- The next script to handle our login request. Create a new php file login.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 |
<?php if($_SERVER['REQUEST_METHOD']=='POST'){ //Getting values $username = $_POST['email']; $password = $_POST['password']; //Creating sql query $sql = "SELECT * FROM users WHERE email='$username' AND password='$password'"; //importing dbConnect.php script require_once('dbConnect.php'); //executing query $result = mysqli_query($con,$sql); //fetching result $check = mysqli_fetch_array($result); //if we got some result if(isset($check)){ //displaying success echo "success"; }else{ //displaying failure echo "failure"; } mysqli_close($con); } |
Android Login Example
- Create a new Android Project.
- Add android volley library to your project dependencies.
1 2 3 4 5 6 7 8 9 |
dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) testCompile 'junit:junit:4.12' compile 'com.android.support:appcompat-v7:23.1.0' compile 'com.android.support:design:23.0.0' compile 'com.mcxiaoke.volley:library-aar:1.0.0' } |
- Now create a new class named Config.java to store some important constants.
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 |
package net.simplifiedcoding.androidloginlogout; /** * Created by Belal on 11/14/2015. */ public class Config { //URL to our login.php file public static final String LOGIN_URL = "http://192.168.94.1/Android/LoginLogout/login.php"; //Keys for email and password as defined in our $_POST['key'] in login.php public static final String KEY_EMAIL = "email"; public static final String KEY_PASSWORD = "password"; //If server response is equal to this that means login is successful public static final String LOGIN_SUCCESS = "success"; //Keys for Sharedpreferences //This would be the name of our shared preferences public static final String SHARED_PREF_NAME = "myloginapp"; //This would be used to store the email of current logged in user public static final String EMAIL_SHARED_PREF = "email"; //We will use this to store the boolean in sharedpreference to track user is loggedin or not public static final String LOGGEDIN_SHARED_PREF = "loggedin"; } |
Desiging Android Login Activity
- First we will define colors. Inside values-> colors.xml write the following code.
1 2 3 4 5 6 7 8 9 10 |
<?xml version="1.0" encoding="utf-8"?> <resources> <color name="colorPrimary">#085682</color> <color name="colorPrimaryDark">#033855</color> <color name="colorAccent">#FFFFFF</color> <color name="colorBackground">#147fbb</color> </resources> |
- In the layout file of your login activity 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 |
<?xml version="1.0" encoding="utf-8"?> <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:background="@color/colorBackground" android:layout_width="fill_parent" android:layout_height="fill_parent" android:fitsSystemWindows="true"> <LinearLayout android:layout_gravity="center_vertical" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="wrap_content" android:paddingTop="56dp" android:paddingLeft="24dp" android:paddingRight="24dp"> <ImageView android:background="@drawable/logo" android:layout_gravity="center_horizontal" android:layout_width="150dp" android:layout_height="150dp" /> <android.support.design.widget.TextInputLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="8dp" android:layout_marginBottom="8dp"> <EditText android:id="@+id/editTextEmail" android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="textEmailAddress" android:hint="Email" /> </android.support.design.widget.TextInputLayout> <android.support.design.widget.TextInputLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="8dp" android:layout_marginBottom="8dp"> <EditText android:id="@+id/editTextPassword" android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="textPassword" android:hint="Password"/> </android.support.design.widget.TextInputLayout> <android.support.v7.widget.AppCompatButton android:id="@+id/buttonLogin" android:layout_width="fill_parent" android:layout_height="wrap_content" android:background="@color/colorPrimary" android:textColor="@color/colorAccent" android:layout_marginTop="24dp" android:layout_marginBottom="24dp" android:padding="12dp" android:text="Login"/> <TextView android:id="@+id/linkSignup" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginBottom="24dp" android:text="No account yet? Create one" android:gravity="center" android:textSize="16dip"/> </LinearLayout> </ScrollView> |
- The above code will produce the following layout. We are not creating an Android Registration Form here. User will directly see the login page.
- Now come to the java code (In my case it is LoginActivity.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 |
package net.simplifiedcoding.androidloginlogout; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.AppCompatButton; import android.view.Menu; import android.view.View; import android.widget.EditText; import android.widget.Toast; import com.android.volley.AuthFailureError; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import java.util.HashMap; import java.util.Map; public class LoginActivity extends AppCompatActivity implements View.OnClickListener { //Defining views private EditText editTextEmail; private EditText editTextPassword; private AppCompatButton buttonLogin; //boolean variable to check user is logged in or not //initially it is false private boolean loggedIn = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); //Initializing views editTextEmail = (EditText) findViewById(R.id.editTextEmail); editTextPassword = (EditText) findViewById(R.id.editTextPassword); buttonLogin = (AppCompatButton) findViewById(R.id.buttonLogin); //Adding click listener buttonLogin.setOnClickListener(this); } @Override protected void onResume() { super.onResume(); //In onresume fetching value from sharedpreference SharedPreferences sharedPreferences = getSharedPreferences(Config.SHARED_PREF_NAME,Context.MODE_PRIVATE); //Fetching the boolean value form sharedpreferences loggedIn = sharedPreferences.getBoolean(Config.LOGGEDIN_SHARED_PREF, false); //If we will get true if(loggedIn){ //We will start the Profile Activity Intent intent = new Intent(LoginActivity.this, ProfileActivity.class); startActivity(intent); } } private void login(){ //Getting values from edit texts final String email = editTextEmail.getText().toString().trim(); final String password = editTextPassword.getText().toString().trim(); //Creating a string request StringRequest stringRequest = new StringRequest(Request.Method.POST, Config.LOGIN_URL, new Response.Listener<String>() { @Override public void onResponse(String response) { //If we are getting success from server if(response.equalsIgnoreCase(Config.LOGIN_SUCCESS)){ //Creating a shared preference SharedPreferences sharedPreferences = LoginActivity.this.getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE); //Creating editor to store values to shared preferences SharedPreferences.Editor editor = sharedPreferences.edit(); //Adding values to editor editor.putBoolean(Config.LOGGEDIN_SHARED_PREF, true); editor.putString(Config.EMAIL_SHARED_PREF, email); //Saving values to editor editor.commit(); //Starting profile activity Intent intent = new Intent(LoginActivity.this, ProfileActivity.class); startActivity(intent); }else{ //If the server response is not success //Displaying an error message on toast Toast.makeText(LoginActivity.this, "Invalid username or password", Toast.LENGTH_LONG).show(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { //You can handle error here if you want } }){ @Override protected Map<String, String> getParams() throws AuthFailureError { Map<String,String> params = new HashMap<>(); //Adding parameters to request params.put(Config.KEY_EMAIL, email); params.put(Config.KEY_PASSWORD, password); //returning parameter return params; } }; //Adding the string request to the queue RequestQueue requestQueue = Volley.newRequestQueue(this); requestQueue.add(stringRequest); } @Override public void onClick(View v) { //Calling the login function login(); } } |
- Now we need to code the next activity (Create a new activity for profile ProfileActivity.java).
- For this activity we need to create a menu for our logout button. So inside menu -> menu.xml write the following.
1 2 3 4 5 6 |
<?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/menuLogout" android:title="Logout" /> </menu> |
- We need to create only a single TextView in our layout file for this activity (activity_profile.xml).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:orientation="vertical" android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context="net.simplifiedcoding.androidloginlogout.ProfileActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceLarge" android:text="Large Text" android:id="@+id/textView" /> </LinearLayout> |
- Write the following code in ProfileActivity.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 |
package net.simplifiedcoding.androidloginlogout; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.widget.TextView; public class ProfileActivity extends AppCompatActivity { //Textview to show currently logged in user private TextView textView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_profile); //Initializing textview textView = (TextView) findViewById(R.id.textView); //Fetching email from shared preferences SharedPreferences sharedPreferences = getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE); String email = sharedPreferences.getString(Config.EMAIL_SHARED_PREF,"Not Available"); //Showing the current logged in email to textview textView.setText("Current User: " + email); } //Logout function private void logout(){ //Creating an alert dialog to confirm logout AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this); alertDialogBuilder.setMessage("Are you sure you want to logout?"); alertDialogBuilder.setPositiveButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface arg0, int arg1) { //Getting out sharedpreferences SharedPreferences preferences = getSharedPreferences(Config.SHARED_PREF_NAME,Context.MODE_PRIVATE); //Getting editor SharedPreferences.Editor editor = preferences.edit(); //Puting the value false for loggedin editor.putBoolean(Config.LOGGEDIN_SHARED_PREF, false); //Putting blank value to email editor.putString(Config.EMAIL_SHARED_PREF, ""); //Saving the sharedpreferences editor.commit(); //Starting login activity Intent intent = new Intent(ProfileActivity.this, LoginActivity.class); startActivity(intent); } }); alertDialogBuilder.setNegativeButton("No", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface arg0, int arg1) { } }); //Showing the alert dialog AlertDialog alertDialog = alertDialogBuilder.create(); alertDialog.show(); } @Override public boolean onCreateOptionsMenu(Menu menu) { //Adding our menu to toolbar getMenuInflater().inflate(R.menu.menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.menuLogout) { //calling logout method when the logout button is clicked logout(); } return super.onOptionsItemSelected(item); } } |
- Add Internet Permission to Your AndroidManifest.xmlÂ
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 |
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="net.simplifiedcoding.androidloginlogout" > <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=".LoginActivity" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".ProfileActivity" > </activity> </application> </manifest> |
- Thats it, run your application now.
- Bingo! its working fine.
- You can also download my source code from github. Visit the link given below.
[sociallocker id=1372] Download this Android Project from GitHub [/sociallocker]
[wp_ad_camp_1]
Common Error with this Android Login Example
- If you are using wamp or xampp server and getting blank toast message. Then this is often cause when your emulator cannot access your host. So you have to write the correct URL in Config.java file.
- To know what is your URL open your command prompt and type ipconfig.
- Here you will see your IP Address. 192.168.94.1 -> this is my root and I stored my php scripts inside Android/LoginLogout/
- So my URL is http://192.168.94.1/Android/LoginLogout/login.php
- To confirm it is correct open your emulator and write http://192.168.94.1/Android/LoginLogout (You have to write your address) in browser and check the browser can access it or not.
- If your browser can access your URL then it is fine.
- If you got more than one IP with ipconfig command. Try accessing all the IPs one by one in your browser to get the correct one.
Some More Android Application Development Tutorial To Check
- Android Retrofit Tutorial to Insert into MySQL Database
- Android Spinner Example to Load JSON using Volley
- Android Volley tutorial to Get JSON from Server
- Android Session Management using Shared Preferences
So thats all for this Android Login Example friends. Feel free to leave your comments if you are having any doubts or queries. Thank You 🙂