Android Tutorials : Firebase Login and Authentication Tutorial
Note : Here is the Updated version of this tutorial for new Firebase SDK.
Firebase is a powerful platform to build great mobile applications. It helps in building the backend for your application. Firebase helps you with User authentication, Real time database and also static hosting. So you need not worry about complex infrastructure. It allows you to focus on User Experience or User Interface. Firebase has a NoSQL JSON database. One of the most exciting features about this is, it does Data Synchronization. Whenever the client device writes to Firebase, it will be automatically synchronized with Firebase servers and then it will be pushed down to every other device connected to your Firebase account.
Every piece of data has its own URL. We know JSON is a tree structure. URLs are a tree structure too. So every piece of Data is mapped (Every Number, Every String etc) to its own URL. So you can reference data with an absolute path or with a relative path. Also these are browser compatible and hence you can see a graphical view of your data.
Most applications need to know the identity of a user. Knowing a user’s identity allows an app to provide a customized experience and grant them permissions to access their data. The process of proving a user’s identity is called authentication.
When a user authenticates to a Firebase app, three things happen:
1. Information about the user is returned in callbacks on the client device. This allows you to customize your app’s user experience for that specific user.
2. The user information returned contains a uid (a unique ID), which is guaranteed to be distinct across all providers, and to never change for a specific authenticated user.
3. The value of the auth variable in your app’s Security and Firebase Rules becomes defined. This variable is null for unauthenticated users, but for authenticated users it is an object containing the user’s unique (auth.uid) and potentially other data about the user. This allows you to securely control data access on a per-user basis.
Firebase apps have built-in support for logging in with email & password, social login providers such as Facebook, Google, Twitter, and GitHub, and single-session anonymous login. Apps that use Firebase’s built-in auth services can handle user login entirely with client-side code, saving you time and the headache of operating your own backend.Firebase makes it easy to support email and password authentication in your app. Firebase automatically stores your users’ credentials securely (using bcrypt) and redundantly (with replication and daily off-site backups).This separates sensitive user credentials from your application data, and lets you focus on the user interface and experience for your app.
Let us build an Android Application using Firebase as a backend to store user credentials in this tutorial. The steps are described in 4 lengthy yet very simple parts :
Part ! : Includes account creation and getting your firebase reference
1. The first thing you need to do to get started with Firebase is sign up for a free account.
2. After clicking on ‘Sign Up with Google’ you will be asked to allow the Firebase to view your Email and your basic profile. Click on Allow button to continue.
3. A brand new Firebase app will automatically be created for you with its own unique URL ending in firebaseio.com. But let us create another firebase app for using it in our android application tutorial. Give a unique App Name. I gave the App Name as androidbashfirebase and the App URL was automatically generated. Click on Create New App button.
4. Now you can see a new firebase app created with the app URL as androidbashfirebase.firebaseio.com. Now click on Manage App button to see your Firebase database for the app you have created.
5. Initially as there will be no users, the database will be empty and it looks as shown in the following image.
6. Now as we need to implement login functionality in our android application we need to Enable Email and Password authentication under Login and Authentication Tab of your Firebase app.
Now we are done with the First part and let’s move on to the next part.
Part !! : Includes steps to create a new Android application and set up Firebase in it.
1. Create a new Android Project using Android Studio. Give it a name and select the Minimum SDK on which your app will run on. I chose API 16 : Android 4.1 (JELLY_BEAN).
2.. When you are prompted to add an activity to your application choose Blank Activity and click on next button.
3. In the next step click on Finish and in few seconds your application should be loaded in Android Studio.
4. Open build.gradle(Module:App) file of your application and add compile ‘com.firebase:firebase-client-android:2.5.2+’ inside dependencies section of build.gradle file.
1 2 3 4 5 6 |
dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) compile 'com.android.support:appcompat-v7:23.3.0' compile 'com.android.support:design:23.3.0' compile 'com.firebase:firebase-client-android:2.5.2+' } |
5. Now add the packagingOptions directive to your build.gradle file as shown 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 |
apply plugin: 'com.android.application' android { compileSdkVersion 23 buildToolsVersion "23.0.2" defaultConfig { applicationId "com.androidbash.androidbashfirebase" minSdkVersion 16 targetSdkVersion 23 versionCode 1 versionName "1.0" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } packagingOptions { exclude 'META-INF/LICENSE' exclude 'META-INF/LICENSE-FIREBASE.txt' exclude 'META-INF/NOTICE' } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) compile 'com.android.support:appcompat-v7:23.3.0' compile 'com.android.support:design:23.3.0' compile 'com.firebase:firebase-client-android:2.5.2+' } |
6. The Firebase library requires the android.permission.INTERNET permission to operate. Your app will not work unless you add these permissions to your AndroidManifest.xml file:
1 2 3 4 |
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.GET_ACCOUNTS" /> <uses-permission android:name="android.permission.READ_PROFILE" /> <uses-permission android:name="android.permission.READ_CONTACTS" /> |
Now the Second Part is done and we can move on to the next part.
Part !!! : Includes steps to create a new XML layouts and modifications to existing XML files.
1. Open the activity_main.xml file of your application and add the following code in it.
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 |
<?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="@android:color/white" android:fitsSystemWindows="true" tools:context=".MainActivity"> <android.support.design.widget.AppBarLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:theme="@style/AppTheme.AppBarOverlay"> <android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="@color/colorAccent" app:popupTheme="@style/AppTheme.PopupOverlay" /> </android.support.design.widget.AppBarLayout> <RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_marginTop="50dp" android:gravity="center"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="50dp" android:orientation="vertical"> <TextView android:id="@+id/text_view_name" android:layout_width="match_parent" android:layout_height="match_parent" android:enabled="true" android:gravity="center_horizontal" android:textColor="@color/icons" android:textSize="20sp" /> <TextView android:id="@+id/text_view_welcome" android:layout_width="match_parent" android:layout_height="match_parent" android:enabled="true" android:gravity="center" android:textColor="@color/icons" android:textSize="24sp" /> <Space android:layout_width="1dp" android:layout_height="10dp" /> <Button android:id="@+id/button_change" android:layout_width="match_parent" android:layout_height="40dp" android:layout_marginLeft="0dp" android:layout_marginRight="4dp" android:layout_marginTop="14dp" android:background="@color/colorPrimary" android:paddingLeft="8dp" android:paddingRight="8dp" android:text="Change Welcome Text" android:textColor="#ffffff" android:textSize="18sp" /> <Space android:layout_width="1dp" android:layout_height="10dp" /> <Button android:id="@+id/button_revert" android:layout_width="match_parent" android:layout_height="40dp" android:layout_marginLeft="1dp" android:layout_marginRight="4dp" android:layout_marginTop="14dp" android:background="@color/colorPrimary" android:paddingLeft="8dp" android:paddingRight="8dp" android:text="Revert Text" android:textColor="#ffffff" android:textSize="18sp" /> </LinearLayout> </RelativeLayout> </RelativeLayout> |
2. Create a new XML layout resource file under the layout folder and name it as activity_sign_up.xml. This contains a layout design for our Sign Up page. Add the following code in it.
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 |
<?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:fitsSystemWindows="true" tools:context=".SignUpActivity"> <android.support.design.widget.AppBarLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:theme="@style/AppTheme.AppBarOverlay"> <android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="@color/colorAccent" app:popupTheme="@style/AppTheme.PopupOverlay" /> </android.support.design.widget.AppBarLayout> <RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_marginTop="50dp" android:gravity="center_horizontal"> <ProgressBar android:id="@+id/progress_bar_sign_up" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_centerHorizontal="true" android:layout_marginBottom="8dp" android:visibility="gone" /> <LinearLayout android:id="@+id/email_sign_up_form" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="@dimen/activity_horizontal_margin" android:orientation="vertical"> <TextView android:id="@+id/text_view_username" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="15dp" android:layout_marginTop="15dp" android:fontFamily="sans-serif-medium" android:text="Enter Your User Name" android:textColor="#000000" android:textSize="18sp" android:textStyle="bold|italic" /> <EditText android:id="@+id/edit_text_username" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="15dp" android:inputType="textPersonName" /> <TextView android:id="@+id/text_view_phone_number" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="15dp" android:layout_marginTop="15dp" android:fontFamily="sans-serif-medium" android:text="Enter Your Phone Number" android:textColor="#000000" android:textSize="18sp" android:textStyle="bold|italic" /> <EditText android:id="@+id/edit_text_phone_number" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="15dp" android:inputType="number" /> <TextView android:id="@+id/text_view_new_email" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="15dp" android:layout_marginTop="15dp" android:fontFamily="sans-serif-medium" android:text="Enter Your Mail Id" android:textColor="#000000" android:textSize="18sp" android:textStyle="bold|italic" /> <EditText android:id="@+id/edit_text_new_email" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="15dp" android:inputType="textEmailAddress" /> <TextView android:id="@+id/text_view_new_password" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="15dp" android:layout_marginTop="15dp" android:fontFamily="sans-serif-medium" android:text="Enter Your Password" android:textColor="#000000" android:textSize="18sp" android:textStyle="bold|italic" /> <EditText android:id="@+id/edit_text_new_password" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="15dp" android:inputType="textPassword" /> <Space android:layout_width="1dp" android:layout_height="30dp" /> <Button android:id="@+id/button_user_sign_up" style="?android:textAppearanceSmall" android:layout_width="fill_parent" android:layout_height="fill_parent" android:onClick="onSignUpClicked" android:background="@color/colorPrimary" android:padding="10dp" android:text="Sign Up Now" android:textStyle="bold" /> </LinearLayout> </RelativeLayout> </RelativeLayout> |
3. Create a new XML layout resource file under the layout folder and name it as activity_login.xml. This contains a layout design for our Login page. Add the following code in it.
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 |
<?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="@android:color/white" android:fitsSystemWindows="true" tools:context=".LoginActivity"> <android.support.design.widget.AppBarLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:theme="@style/AppTheme.AppBarOverlay"> <android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="@color/colorAccent" app:popupTheme="@style/AppTheme.PopupOverlay" /> </android.support.design.widget.AppBarLayout> <RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_marginTop="50dp" android:gravity="center_horizontal"> <ProgressBar android:id="@+id/progress_bar_login" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_marginBottom="8dp" android:visibility="gone" /> <LinearLayout android:id="@+id/login_details" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <TextView android:id="@+id/text_view_email_id" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="15dp" android:layout_marginTop="15dp" android:fontFamily="sans-serif-medium" android:text="Enter Your Email" android:textColor="#000000" android:textSize="18sp" android:textStyle="bold|italic" /> <EditText android:id="@+id/edit_text_email_id" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="15dp" android:inputType="textEmailAddress" /> <TextView android:id="@+id/text_view_password" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="15dp" android:layout_marginTop="15dp" android:fontFamily="sans-serif-medium" android:text="Enter Your Password" android:textColor="#000000" android:textSize="18sp" android:textStyle="bold|italic" /> <EditText android:id="@+id/edit_text_password" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignLeft="@+id/text_view_password" android:layout_marginLeft="15dp" android:inputType="textPassword" /> <Space android:layout_width="1dp" android:layout_height="30dp" /> <Button android:id="@+id/button_sign_in" style="?android:textAppearanceSmall" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="@color/colorPrimaryDark" android:onClick="onLoginClicked" android:padding="10dp" android:text="Log In" android:textStyle="bold" /> <Space android:layout_width="1dp" android:layout_height="10dp" /> <Button android:id="@+id/button_sign_up" style="?android:textAppearanceSmall" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="@color/colorPrimary" android:onClick="onSignUpClicked" android:padding="10dp" android:text="New User? Please Sign Up" android:textStyle="bold" /> </LinearLayout> </RelativeLayout> </RelativeLayout> |
4. The menu_main.xml file in the menu folder looks like this.
1 2 3 4 5 6 |
<menu 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" tools:context=".MainActivity"> <item android:id="@+id/action_logout" android:title="@string/action_logout" app:showAsAction="never" /> </menu> |
5. The colors.xml file in the values folder looks like this
1 2 3 4 5 6 7 8 9 10 11 |
<?xml version="1.0" encoding="utf-8"?> <resources> <color name="primary_light">#FFE0B2</color> <color name="colorPrimary">#FF9800</color> <color name="colorPrimaryDark">#F57C00</color> <color name="colorAccent">#FFEB3B</color> <color name="colorText">#000000</color> <color name="secondary_text">#727272</color> <color name="icons">#212121</color> <color name="divider">#B6B6B6</color> </resources> |
6. The styles.xml file in the values folder looks like this
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<resources> <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar"> <item name="colorPrimary">#FFE0BB</item> <item name="colorPrimaryDark">#FFAA00</item> <item name="colorAccent">#FFEB3B</item> </style> <style name="AppTheme.NoActionBar"> <item name="windowActionBar">false</item> <item name="windowNoTitle">true</item> </style> <style name="AppTheme.LoginActionbar" parent="AppTheme.NoActionBar"></style> <style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" /> <style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" /> </resources> |
7. The strings.xml file in the values folder looks like this.
1 2 3 4 |
<resources> <string name="app_name">AndroidBashFirebase</string> <string name="action_logout"> Log Out</string> </resources> |
Now we are done with the Third Part and we can move to the last part.
Part !V : Includes steps to create new Activities (Java class files) and modification to MainActivity.java.
1. The Firebase library must be initialized once with an Android context. This must happen before any Firebase app reference is created or used. You can add the setup code to your Android Application’s onCreate method. Create a new Java class file under src folder and name it as CustomApplication.java. Add the following code in it.
1 2 3 4 5 6 7 8 9 10 11 12 |
package com.androidbash.androidbashfirebase; import com.firebase.client.Firebase; public class CustomApplication extends android.app.Application { @Override public void onCreate() { super.onCreate(); Firebase.setAndroidContext(this); } } |
2. Create a new Java class file under src folder and name it as User.java. Add the following code in it.
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 |
package com.androidbash.androidbashfirebase; import com.firebase.client.Firebase; public class User { private String id; private String name; private String phoneNumber; private String email; private String password; public User() { } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public void saveUser() { Firebase myFirebaseRef = new Firebase("https://androidbashfirebase.firebaseio.com/"); myFirebaseRef = myFirebaseRef.child("users").child(getId()); myFirebaseRef.setValue(this); } } |
3. Create a new Java class file under src folder and name it as SignUpActivity.java. Add the following code in it.
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 |
package com.androidbash.androidbashfirebase; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.EditText; import android.widget.ProgressBar; import android.widget.Toast; import com.firebase.client.Firebase; import com.firebase.client.FirebaseError; import java.util.Map; public class SignUpActivity extends AppCompatActivity { private Firebase myFirebaseRef; private User user; private EditText name; private EditText phoneNumber; private EditText email; private EditText password; private ProgressBar progressBar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sign_up); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); //Creates a reference for your Firebase database myFirebaseRef = new Firebase("https://androidbashfirebase.firebaseio.com/"); } @Override protected void onStart() { super.onStart(); name = (EditText) findViewById(R.id.edit_text_username); phoneNumber=(EditText) findViewById(R.id.edit_text_phone_number); email = (EditText) findViewById(R.id.edit_text_new_email); password = (EditText) findViewById( R.id.edit_text_new_password); progressBar = (ProgressBar) findViewById(R.id.progress_bar_sign_up); } protected void setUpUser(){ user = new User(); user.setName(name.getText().toString()); user.setPhoneNumber(phoneNumber.getText().toString()); user.setEmail(email.getText().toString()); user.setPassword(password.getText().toString()); } public void onSignUpClicked(View view){ progressBar.setVisibility(View.VISIBLE); setUpUser(); //createUser method creates a new user account with the given email and password. //Parameters are : // email - The email for the account to be created // password - The password for the account to be created // handler - A handler which is called with the result of the operation myFirebaseRef.createUser( user.getEmail(), user.getPassword(), new Firebase.ValueResultHandler<Map<String, Object>>() { @Override public void onSuccess(Map<String, Object> stringObjectMap) { user.setId(stringObjectMap.get("uid").toString()); user.saveUser(); myFirebaseRef.unauth(); Toast.makeText(getApplicationContext(), "Your Account has been Created", Toast.LENGTH_LONG).show(); Toast.makeText(getApplicationContext(), "Please Login With your Email and Password", Toast.LENGTH_LONG).show(); progressBar.setVisibility(View.GONE); finish(); } @Override public void onError(FirebaseError firebaseError) { Toast.makeText(getApplicationContext(), "" + firebaseError.getMessage(), Toast.LENGTH_LONG).show(); progressBar.setVisibility(View.GONE); } } ); } } |
4. Create a new Java class file under src folder and name it as LoginActivity.java. Add the following code in it.
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 |
package com.androidbash.androidbashfirebase; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.EditText; import android.widget.ProgressBar; import android.widget.Toast; import com.firebase.client.AuthData; import com.firebase.client.Firebase; import com.firebase.client.FirebaseError; public class LoginActivity extends AppCompatActivity { private Firebase myFirebaseRef; private User user; private EditText email; private EditText password; private ProgressBar progressBar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); myFirebaseRef = new Firebase("https://androidbashfirebase.firebaseio.com/"); } @Override protected void onStart() { super.onStart(); email = (EditText) findViewById(R.id.edit_text_email_id); password = (EditText) findViewById(R.id.edit_text_password); progressBar = (ProgressBar) findViewById(R.id.progress_bar_login); checkUserLogin(); } protected void setUpUser() { user = new User(); user.setEmail(email.getText().toString()); user.setPassword(password.getText().toString()); } public void onSignUpClicked(View view) { Intent intent = new Intent(this, SignUpActivity.class); startActivity(intent); } public void onLoginClicked(View view) { progressBar.setVisibility(View.VISIBLE); setUpUser(); aunthenticateUserLogin(); } private void checkUserLogin() { //getAuth Returns the current authentication state of the Firebase client. If the client is unauthenticated, this method will return null. // Otherwise, the return value will be an object containing at least the fields such as uid,provider,token,expires,auth // https://www.firebase.com/docs/web/api/firebase/getauth.html, if (myFirebaseRef.getAuth() != null) { Intent intent = new Intent(getApplicationContext(), MainActivity.class); String uid = myFirebaseRef.getAuth().getUid(); intent.putExtra("user_id", uid); startActivity(intent); finish(); } } private void aunthenticateUserLogin() { //authWithPassword method attempts to authenticate to Firebase with the given credentials. //Paramters Are : // email - The email for the user to authenticate // password - The password for the account // handler - A handler which will be called with the result of the authentication attempt myFirebaseRef.authWithPassword( user.getEmail(), user.getPassword(), new Firebase.AuthResultHandler() { @Override public void onAuthenticated(AuthData authData) { //Log.i("TOKEN",authData.getToken()); //Log.i("PROVIDER",authData.getProvider()); //Log.i("UID",authData.getUid()); //Log.i("AUTH_MAP",authData.getAuth().toString()); progressBar.setVisibility(View.GONE); Intent intent = new Intent(getApplicationContext(), MainActivity.class); String uid = myFirebaseRef.getAuth().getUid(); intent.putExtra("user_id", uid); startActivity(intent); finish(); } @Override public void onAuthenticationError(FirebaseError firebaseError) { Toast.makeText(getApplicationContext(), "" + firebaseError.getMessage(), Toast.LENGTH_LONG).show(); progressBar.setVisibility(View.GONE); } } ); } } |
5. Open MainActivty.java file of your application and add the following code it.
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 |
package com.androidbash.androidbashfirebase; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.firebase.client.DataSnapshot; import com.firebase.client.Firebase; import com.firebase.client.FirebaseError; import com.firebase.client.ValueEventListener; public class MainActivity extends AppCompatActivity { Firebase myFirebaseRef; TextView name; TextView welcomeText; Button changeButton; Button revertButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); //Creates a reference for your Firebase database myFirebaseRef = new Firebase("https://androidbashfirebase.firebaseio.com/"); } @Override protected void onStart() { super.onStart(); name = (TextView) findViewById(R.id.text_view_name); welcomeText = (TextView) findViewById(R.id.text_view_welcome); changeButton = (Button) findViewById(R.id.button_change); revertButton = (Button) findViewById(R.id.button_revert); //Get the uid for the currently logged in User from intent data passed to this activity String uid = getIntent().getExtras().getString("user_id"); //Reffering to the name of the User who has logged in currently and adding a valueChangeListener myFirebaseRef.child("users").child(uid).child("name").addValueEventListener(new ValueEventListener() { //onDataChange is called every time the name of the User changes in your Firebase Database @Override public void onDataChange(DataSnapshot dataSnapshot) { //Inside onDataChange we can get the data as an Object from the dataSnapshot //getValue returns an Object. We can specify the type by passing the type expected as a parameter String data = dataSnapshot.getValue(String.class); name.setText("Hello "+data+", "); } //onCancelled is called in case of any error @Override public void onCancelled(FirebaseError firebaseError) { Toast.makeText(getApplicationContext(), "" + firebaseError.getMessage(), Toast.LENGTH_LONG).show(); } }); //A firebase reference to the welcomeText can be created in following ways : // You can use this : //Firebase myAnotherFirebaseRefForWelcomeText=new Firebase("https://androidbashfirebase.firebaseio.com/welcomeText");*/ //OR myFirebaseRef.child("welcomeText").addValueEventListener(new ValueEventListener() { //onDataChange is called every time the data changes in your Firebase Database @Override public void onDataChange(DataSnapshot dataSnapshot) { //Inside onDataChange we can get the data as an Object from the dataSnapshot //getValue returns an Object. We can specify the type by passing the type expected as a parameter String data = dataSnapshot.getValue(String.class); welcomeText.setText(data); } //onCancelled is called in case of any error @Override public void onCancelled(FirebaseError firebaseError) { Toast.makeText(getApplicationContext(), "" + firebaseError.getMessage(), Toast.LENGTH_LONG).show(); } }); //onClicking changeButton the value of the welcomeText in the Firebase database gets changed changeButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { myFirebaseRef.child("welcomeText").setValue("Welcome to AndroidBash"); } }); //onClicking revertButton the value of the welcomeText in the Firebase database gets changed revertButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { myFirebaseRef.child("welcomeText").setValue("Welcome to Learning @ AndroidBash"); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.action_logout) { myFirebaseRef.unauth(); finish(); } return super.onOptionsItemSelected(item); } } |
6. And at the last AndriodManifest.xml looks like this.
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.androidbash.androidbashfirebase"> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.GET_ACCOUNTS" /> <uses-permission android:name="android.permission.READ_PROFILE" /> <uses-permission android:name="android.permission.READ_CONTACTS" /> <application android:name=".CustomApplication" android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="AndroidBashFirebase" android:theme="@style/AppTheme"> <activity android:name=".LoginActivity" android:label="AndroidBashFirebase Log In" android:theme="@style/AppTheme.NoActionBar"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".SignUpActivity" android:label="Sign Up Activity" android:theme="@style/AppTheme.NoActionBar" /> <activity android:name=".MainActivity" android:label="AndroidBash Home" android:theme="@style/AppTheme.NoActionBar"/> </application> </manifest> |
That’s it. You can run your application to test it. Also you can download the project from the link given below. If you have followed our tutorial please do let us know by commenting below. It makes us write more and more articles on android application development.
Here is the Video Demo to show the working of this application.
Very nice tutorial on Firebase. I shall try and let you know the result. Thank you
Thank yu. The tutorial was very useful. Can you teach us how to integrate Facebook Login or Google sign in in Firebase?
greetings from Ecuador, thanks for the tutorial I served much …. Could you help me one thing … I am what I do from my database activate your account and disable the user’s account and can not enter without I will accept from my database ….. thanks
I did not get your question. Can you please rephrase your question so that i can look in to it?
hello sir.i just used your code to perform registration and login.but i faced a problem and the problem is when i run the project on my phone they say that “project created must use the new firebase auth sdk”
can u please help me to solve this problem.
thank u sir
No worries. Just wait for few hours. I will be uploading another updated authentication tutorial. Firebase has been updated recently. They have included lot more features. Thank You:)
We have updated 🙂 Here is the Link http://androidbash.com/firebase-classic-email-login-facebook-login-android/
im getting error like “Projects created at console.firebase.google.com must use the new Firebase Authentication SDKs available from firebase.google.com/docs/auth” when i clicked sign up button
I have enabled email sign in option also .Please help me and reply me the error @ reddyprakash939@gmail.com
Hello Prakash, Please follow our updated tutorial on Firebase Authentication.
I am new to firebase i used your code but getting error as “Projects created at console.firebase.google.com must use the new Firebase Authentication SDKs available from firebase.google.com/docs/auth” i checked your updated tutorial too but couldnt find solution
Hello Hemathri, Please follow our updated tutorial on Firebase Authentication. Thank You.
Such a useful and very deep concept of knowing about login and registration form in android using firebase
Thank you:) Glad to hear from you. Please refer to our updated tutorial also.
Sir there is message pop up when i run this app unfortunately app has stopped working
how i can fix it
Sir tell me please
Hi, There will be some exception generated when you Run the app. That will be shown in the console of the Android Studio. Let me know the Exception that is generated in the logcat, so that i can tell you what is the cause of that error.
Also Firebase team have updated their SDK. So you need to follow our updated tutorial on Firebase authentication:)
Sir now its working
but When I login the name does not show with Hello
its Comes Hello Null
And in MainActivity.java class the (uid) say
Argument might be null
please answer me
works like charm !