Firebase email authentication android

Firebase email authentication android is a process by which we can validate email address of the user. By this we can add a layer of the authentic user. Now a days its is quite useful. Manually if we need to validate the user we need to create a whole system to do so.

Like we need to deploy the database and api and send the email to authenticate user. Instead of doing all this we can just use the firebase email authentication method which saves a lot of time and dependency on the backend technologies.

So lets get started Firebase email authentication android

1- I hope you have already created the account on the firebase console if not you can go thorught this link.

2- Go to firebase console.

3- Go to Authentication and Sign-in Methods Enable email authentication then click save button.

Firebase email authentication

4- To send verification link from the android app create a email password field and submit button added in EmailVerificationActivity.

package com.example.sampleproject;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;

public class EmailVerificationActivity extends AppCompatActivity {

private FirebaseAuth mAuth;
private Helper helper;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_email_verification);
mAuth= FirebaseAuth.getInstance();
helper = new Helper(this);

((Button)findViewById(R.id.bt_submit)).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
EditText email = (EditText)findViewById(R.id.et_email);
String email_string = email.getText().toString();
EditText et_password = (EditText)findViewById(R.id.et_password);
String pasword = et_password.getText().toString();
createNewUser(email_string,pasword);

}
});
}
void createNewUser(String email,String password){
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(EmailVerificationActivity.this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
// Toast.makeText(SignupMaterial.this, "createUserWithEmail:onComplete:" + task.isSuccessful(), Toast.LENGTH_SHORT).show();
// If sign in fails, helper.display a message to the admin. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in admin can be handled in the listener.

if (!task.isSuccessful()) {
// admin alreeady exists
// VerifyEmail();
helper.display("Email already exists");
helper.hideDialog();
} else {
VerifyEmail();
// startActivity(new Intent(SignupActivity.this, ChangeMailActivity.class));
// finish();
}
}


});
}
private void VerifyEmail() {
final FirebaseUser user = mAuth.getCurrentUser();
if (user != null){
user.sendEmailVerification()
.addOnCompleteListener(EmailVerificationActivity.this, (OnCompleteListener) task -> {
// Re-enable button
if (task.isSuccessful()) {
FirebaseUser firebase_user = mAuth.getCurrentUser();
String firebase_uid=firebase_user.getUid();
helper.display("Email verification send");

} else {
Log.e("", "sendEmailVerification", task.getException());
helper.display("Failed to send verification email.");
}
});
}else {
// Toast.makeText(SignupMaterial.this, "null", Toast.LENGTH_SHORT).show();
}

}
}

on submit button email will be send.

Note: email should be unique.

email from firebase

Tagged : /

Upload image on Firebase storage

Upload image on Firebase storage Uploading an image to any server is quite a hectic task and it also as for so much of memory and processing time on the front end. This can be achieve with new RxJava By using this we can create multiple task with quite a minimum time.

What is Firebase Storage?

Cloud Storage for Firebase lets you upload and share user generated content, such as images and video, which allows you to build rich media content into your apps. Your data is stored in a Google Cloud Storage bucket, an exabyte scale object storage solution with high availability and global redundancy. Cloud Storage lets you securely upload these files directly from mobile devices and web browsers, handling spotty networks with ease.

Why RxJava?

RxJava is a Java VM implementation of Reactive Extensions: a library for composing asynchronous and event-based programs by using observable sequences.

How to upload image on firebase

How to Upload image on Firebase storage

1- First you need to add the android app to Firebase Console if not done yet you can get through this from here.

2- Add firebase storage to your firebase console.

3- In this tutorial we are using dexter for permission and glide.

4- Add Some helper class For camera upload CameraIntent.java and helper.java.

5- Add layout file activity_sign_up.xml.
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

    <com.google.android.material.appbar.AppBarLayout
        android:id="@+id/app_bar_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        android:fitsSystemWindows="true">

        <com.google.android.material.appbar.CollapsingToolbarLayout
            android:id="@+id/collapsing_toolbar"
            android:layout_width="match_parent"
            android:layout_height="250dp"
            android:fitsSystemWindows="true"
            app:layout_scrollFlags="scroll|exitUntilCollapsed"
            >

            <androidx.appcompat.widget.AppCompatImageView
                android:layout_width="match_parent"
                android:layout_height="250dp"
                android:id="@+id/iv_profile_pic"
                android:background="@color/white"
                android:fitsSystemWindows="true"
                android:contentDescription="@string/app_name"
                android:src="@mipmap/ic_profile"
                app:layout_collapseMode="parallax"/>

            <androidx.appcompat.widget.Toolbar
                android:id="@+id/Appbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
                android:title="recent_news"
                app:layout_collapseMode="pin" />
        </com.google.android.material.appbar.CollapsingToolbarLayout>
    </com.google.android.material.appbar.AppBarLayout>


    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/iv_profile_pic_select"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="16dp"
        android:clickable="true"
        app:elevation="6dp"
        android:src="@drawable/upload_button"
        app:pressedTranslationZ="12dp"
        app:layout_anchor="@id/app_bar_layout"
        app:layout_anchorGravity="bottom|right|end"/>
</androidx.coordinatorlayout.widget.CoordinatorLayout>

6- Now signup activity.

Create a function for upload image

private UploadTask saveImage(Bitmap image_bitmap_load, StorageReference storage, String file_name_small,int type) {

    //Play with bitmap
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    image_bitmap_load.compress(Bitmap.CompressFormat.JPEG, 100, baos);
    final byte[] data = baos.toByteArray();
    Date date = new Date();

    final StorageReference ref = storage.child(file_name_small);
    UploadTask  uploadTask = ref.putBytes(data);

    Task<Uri> urlTask = uploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
        @Override
        public Task<Uri> then(@NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
            if (!task.isSuccessful()) {
                Toast.makeText(SignUpActivity.this, "unable to upload", Toast.LENGTH_SHORT).show();

                throw task.getException();
            }


            return ref.getDownloadUrl();
        }
    }).addOnCompleteListener(new OnCompleteListener<Uri>() {
                                 @Override
                                 public void onComplete(@NonNull Task<Uri> task) {
                                     if (task.isSuccessful()) {
                                         Uri downloadUri = task.getResult();

                                     } else {
                                         // Handle failures
                                         Toast.makeText(SignUpActivity.this, "unable to upload", Toast.LENGTH_SHORT).show();

                                     }
                                 }
                             }
    );
    return uploadTask;


}
7- And initialize observable
private final CompositeDisposable disposables = new CompositeDisposable();

Observable<UploadTask> sampleObservable(final UploadTask large_image_task, final UploadTask normal_image_task, final UploadTask small_image_task) {
    StorageReference storage = FirebaseStorage.getInstance().getReference();
    return Observable.defer(new Callable<Observable<UploadTask>>() {
        @Override public Observable<UploadTask> call() throws Exception {
            // Do some long running operation
            //   SystemClock.sleep(5000);

            return Observable.just(large_image_task,normal_image_task,small_image_task);
        }
    });
}

8- Add task to disposables

disposables.add(sampleObservable(large_image_task,normal_image_task,small_image_task)
// Run on a background thread
.subscribeOn(Schedulers.io())
// Be notified on the main thread
.observeOn(AndroidSchedulers.mainThread())

.subscribeWith(new DisposableObserver<Task>() {
@Override public void onComplete() {
Log.d(TAG, "onComplete()");

}

@Override public void onError(Throwable e) {
Log.e(TAG, "onError()", e);
}

@Override public void onNext(Task task) {
Log.d(TAG, "onNext(" + task + ")");
}
}));

It will trigger oncomplete File will be uploaded to the firebase storage. You can comment below for any queries. You can also get the code from here.

That’s all for how to upload image using Rx java.

Tagged : /

Add Firebase Mobile Authentication

Why we need to add Firebase mobile Authentication in Android Application?

Mobile authentication is much needed nowadays to verify the user authentic information land to remove the fake users and to get the credibility of the user. You can easily track the user by the mobile number and put all checks to you’r system. Someone can put a random number and access you’r data which will hurt you’r business and put you’r data at much higher risk.

1- First you need to add the android app to Firebase Console if not done yet you can get through this from here.

2- Go to Firebase console > Authentication > Sign In Methods and enable phone authentication.

Firebase mobile authentication

You can also add testing numbers for development purpose and the authentication key . So let’s get started on add Firebase mobile authentication android on android studio.

3- For production purpose you also need to add the SHA 1 certificate fingerprints. To get the fingerprints go to project > gradle > project > android > signin reports then you can get the fingerprint from bottom on the screen (optional).

Firebase authentication
Get SHA 1 from android studio

In app build.gradle you need to add.

implementation 'com.google.firebase:firebase-auth:19.3.0'.

Then in MainActivity.java where user enter the mobile number and country code to request the otp.

package com.example.sampleproject;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.google.firebase.FirebaseException;
import com.google.firebase.FirebaseTooManyRequestsException;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseAuthInvalidCredentialsException;
import com.google.firebase.auth.PhoneAuthCredential;
import com.google.firebase.auth.PhoneAuthProvider;

import java.util.concurrent.TimeUnit;

public class MainActivity extends AppCompatActivity {

private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks;
private FirebaseAuth mAuth;
private Helper helper;
private UserModel mUser = new UserModel();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
helper= new Helper(this);
phoneAuth();
Button bt_login = (Button) findViewById(R.id.bt_login);
final EditText et_mobile_no = (EditText) findViewById(R.id.et_mobile_no);
final EditText et_country_code = (EditText) findViewById(R.id.et_country_code);

bt_login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String mobile_no = et_mobile_no.getText().toString();
String country_code = et_country_code.getText().toString();
String mobileNumber = country_code+mobile_no;
mUser.setMobile(mobileNumber);

createNewUser(mobileNumber);
}
});
}
private void phoneAuth() {
mAuth= FirebaseAuth.getInstance();

mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
@Override
public void onVerificationCompleted(PhoneAuthCredential credential) {
helper.display( "Verification complete" );
String sms_code=credential.getSmsCode();
PhoneAuthCredential credentials = credential;

}

@Override
public void onVerificationFailed(FirebaseException e) {
helper.display(" Verification Failed");
if (e instanceof FirebaseAuthInvalidCredentialsException) {
helper.display("Invalid phone number.");
} else if (e instanceof FirebaseTooManyRequestsException) {
helper.display( "Quota exceeded");
}
e.printStackTrace();
helper.hideDialog();
}

@Override
public void onCodeSent(String verificationId,
PhoneAuthProvider.ForceResendingToken token) {
helper.display( "Verification code send");
mUser.setVerificationId(verificationId);

Intent intent = new Intent(MainActivity.this, VerifyOtp.class);
intent.putExtra("user_details", mUser);
intent.putExtra("user_token", token);
startActivity(intent);
helper.hideDialog();


}

@Override
public void onCodeAutoRetrievalTimeOut(String s) {
helper.hideDialog();
super.onCodeAutoRetrievalTimeOut(s);
}
};

}
void createNewUser(String phoneNumber){

PhoneAuthProvider.getInstance().verifyPhoneNumber(
phoneNumber, // Phone number to verify
60, // Timeout duration
TimeUnit.SECONDS, // Unit of timeout
this, // Activity (for callback binding)
mCallbacks); // OnVerificationStateChangedCallbacks

}
}

Now, Verify the opt process in VerifyOtp class.

package com.example.sampleproject;

import android.content.Intent;
import android.os.Bundle;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseAuthInvalidCredentialsException;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.PhoneAuthCredential;
import com.google.firebase.auth.PhoneAuthProvider;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import java.io.Serializable;

public class VerifyOtp extends AppCompatActivity {

private String TAG = "VerifyOtp";
private UserModel mUserModel;
private FirebaseAuth mAuth;
private Helper helper;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_data);
mAuth= FirebaseAuth.getInstance();
helper = new Helper(this);
Button bt_submit = (Button)findViewById(R.id.bt_submit);
final EditText et_otp = (EditText)findViewById(R.id.et_otp);
Intent intent = getIntent();

if (intent != null) {

Serializable userSerializable = intent.getSerializableExtra("user_details");

mUserModel = (UserModel) userSerializable;
if(mUserModel!=null) {

}else {

}
}
bt_submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String otp = et_otp.getText().toString();

PhoneAuthCredential credential = PhoneAuthProvider.getCredential(mUserModel.getVerificationId(), otp.trim());
signInWithPhoneAuthCredential(credential);
}
});
}

private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
helper.display("Sign in successfully");
final FirebaseUser firebase_user = task.getResult().getUser();
Log.d(TAG, "onComplete: "+firebase_user.getPhoneNumber());
} else {
helper.hideDialog();
helper. display( "Unable to sign in");
if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
helper. display("Invalid code");
}
}
}
});
}

}

You can use other sign in methods available in Firebase Authentication.

Also you can download the code from here.

Tagged : / /

Add Android app to Firebase Crashlytics

On How to Add Android app to Firebase Crashlytics. You have to follow the below steps. First you need to understand the importance of Crashlytics. Suppose you have a large number of active users who are using you’r application so if any error occurs you need the source of that error and debug accordingly both in development and production. So Don’t worry sit tight Firebase is there for you for debugging.

What is Firebase Crashlytics?

Firebase Crashlytics is a lightweight, realtime crash reporter that helps you track, prioritize, and fix stability issues that erode your app quality. Crashlytics saves you troubleshooting time by intelligently grouping crashes and highlighting the circumstances that lead up to them.

Add Android app to Firebase Crashlytics

  1. If not done in previous app you can go through this Connect your Android app to Firebase Console.
  2. Click on Crashlytics under Quality in Firebase console.
  3. Click this app is new to Crashlytics .

Add Crashlytics SDK

  1. In your project bild.gradle add
buildscript {
    repositories {

        // Add Google's Maven repository.
        google()

        maven {
           url 'https://maven.fabric.io/public'
        }

    }

    dependencies {
        // ...

        // Add the Google Services plugin (check for v3.1.2 or higher).
        classpath 'com.google.gms:google-services:4.3.3'

        // Add the Fabric Crashlytics plugin.
        classpath 'io.fabric.tools:gradle:1.31.2'


    }
}


allprojects {
    // ...

    repositories {

       // Check that Google's Maven repository is included (if not, add it).
       google()


       // ...
    }
}




2. Add your app level build.gradle.

apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'
// Add the Fabric plugin.
apply plugin: 'io.fabric'


dependencies {
    // ...

    // (Recommended) Add the Google Analytics dependency.
    implementation 'com.google.firebase:firebase-analytics:17.2.3'

    // Add the Firebase Crashlytics dependency.
    implementation 'com.crashlytics.sdk.android:crashlytics:2.10.1'

}

3. Change min Sdk version to 16 in app level build.gradle.

Add an error to report

add this code in MainActiviety.

int[] error = new int[-1];// add an error to listen

Github

You can get the repository from here.

Tagged : / / / / / / /

Connect your Android App to Firebase Database

On how to Connect your Android App to Firebase Database just follow the below steps.

Installation & Setup

1. But first you have to setup a Firebase project and follow the screen instructions firebase console.

2.Then Navigate to database section and create one and click on create database > test mode to access > enable.

3.Go to project Overview > Project settings > General > click on android icon in your apps.

4.Register your app and download google-services.json and paste it inside project > app.

5. Then in Project-level build.gradle add the following code.

buildscript {
  repositories {
    // Check that you have the following line (if not, add it):
    google()  // Google’s Maven repository
  }
  dependencies {
    …
    // Add this line
    classpath ‘com.google.gms:google-services:4.3.3’
  }
}

allprojects {
  …
  repositories {
    // Check that you have the following line (if not, add it):
    google()  // Google’s Maven repository
    …
  }
}

6. In App-level build.gradle add.

apply plugin: ‘com.android.application’
// Add this line
apply plugin: ‘com.google.gms.google-services’

dependencies {
  // add the Firebase SDK for Google Analytics
  implementation ‘com.google.firebase:firebase-analytics:17.2.2’
  // add SDKs for any other desired Firebase products
  // https://firebase.google.com/docs/android/setup#available-libraries
}

7. now click on sync now in the Android Studio.

Now, Run your project for Connect your Android App to Firebase Database.

8. copy this refrence of code to onCreate of MainActivity class .

FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("message");

myRef.setValue("Hello, World!");

Now, run the app to print the hello world in your console.

You can access the Github code from here.

Tagged : / / / /