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 : /