How to Upload a Video in Firebase Database using Android Studio?
Last Updated :
11 Jul, 2021
Firebase is a mobile and web application development platform. It provides services that a web application or mobile application might require. Firebase provides secure file uploads and downloads for the Firebase application. This article explains how to build an Android application with the ability to select a video from the mobile gallery and upload the video to Firebase Storage.
Step by Step Implementation
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. Or open an existing project in which you want to add authentication and add the firebase to that android application.
Step 2. Add these dependencies in the build.gradle (Module:app) file
implementation 'com.google.firebase:firebase-storage:19.1.0'
implementation 'com.google.firebase:firebase-database:20.0.0'
Step 3: Working with the activity_main.xml file
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.
XML
<?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:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:id="@+id/uploadv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Upload Video" />
</LinearLayout>
Step 4: Working with the MainActivity.java file
Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.
Java
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.widget.Button;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.OnProgressListener;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import java.util.HashMap;
public class MainActivity extends AppCompatActivity {
Button uploadv;
ProgressDialog progressDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// initialise layout
uploadv = findViewById(R.id.uploadv);
uploadv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Code for showing progressDialog while uploading
progressDialog = new ProgressDialog(MainActivity.this);
choosevideo();
}
});
}
// choose a video from phone storage
private void choosevideo() {
Intent intent = new Intent();
intent.setType("video/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, 5);
}
Uri videouri;
// startActivityForResult is used to receive the result, which is the selected video.
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 5 && resultCode == RESULT_OK && data != null && data.getData() != null) {
videouri = data.getData();
progressDialog.setTitle("Uploading...");
progressDialog.show();
uploadvideo();
}
}
private String getfiletype(Uri videouri) {
ContentResolver r = getContentResolver();
// get the file type ,in this case its mp4
MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
return mimeTypeMap.getExtensionFromMimeType(r.getType(videouri));
}
private void uploadvideo() {
if (videouri != null) {
// save the selected video in Firebase storage
final StorageReference reference = FirebaseStorage.getInstance().getReference("Files/" + System.currentTimeMillis() + "." + getfiletype(videouri));
reference.putFile(videouri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Task<Uri> uriTask = taskSnapshot.getStorage().getDownloadUrl();
while (!uriTask.isSuccessful()) ;
// get the link of video
String downloadUri = uriTask.getResult().toString();
DatabaseReference reference1 = FirebaseDatabase.getInstance().getReference("Video");
HashMap<String, String> map = new HashMap<>();
map.put("videolink", downloadUri);
reference1.child("" + System.currentTimeMillis()).setValue(map);
// Video uploaded successfully
// Dismiss dialog
progressDialog.dismiss();
Toast.makeText(MainActivity.this, "Video Uploaded!!", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
// Error, Image not uploaded
progressDialog.dismiss();
Toast.makeText(MainActivity.this, "Failed " + e.getMessage(), Toast.LENGTH_SHORT).show();
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
// Progress Listener for loading
// percentage on the dialog box
@Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
// show the progress bar
double progress = (100.0 * taskSnapshot.getBytesTransferred() / taskSnapshot.getTotalByteCount());
progressDialog.setMessage("Uploaded " + (int) progress + "%");
}
});
}
}
}
Output:
Firebase Storage Image:
Realtime Database:
Similar Reads
How to Update Data in Firebase Firestore in Android? In the previous article, we have seen on How to Add Data to Firebase Firestore in Android, How to Read the data from Firebase Firestore in Android. Now we will see How to Update this added data inside our Firebase Firestore. Now we will move towards the implementation of this updating data in Androi
10 min read
Android: How to Upload an image on Firebase storage? Firebase is a mobile and web application development platform. It provides services that a web application or mobile application might require. Firebase provides secure file uploads and downloads for Firebase application. This article explains how to build an Android application with the ability to
6 min read
How to populate RecyclerView with Firebase data using FirebaseUI in Android Studio Firebase is one of the most popular online databases in use today and will be the same for at least a few years to come. Firebase offers a Realtime Database that can be used to store and retrieve data in real-time to all users. In this post, let's connect the Realtime Database with an Android applic
7 min read
How to Upload Android APK to Testers Group in Firebase Using GitHub Actions? Testing is always required whenever we build an app to ensure it functions properly in production. It might be time-consuming and inconvenient to send the application to the testers every time new code is merged into the codebase. So to solve this problem, CD pipelines can be used to deliver the sof
3 min read
How to Upload PDF Files in Firebase Storage in Android? Firebase is a mobile and web application development platform. It provides services that a web application or mobile application might require. Firebase provides secure file uploads and downloads for the Firebase application. This article explains how to build an Android application with the ability
3 min read
How to Save Data to the Firebase Realtime Database in Android? Firebase is one of the famous backend platforms which is used by so many developers to provide backend support to their applications and websites. It is the product of Google which provides services such as database, storage, user authentication, and many more. In this article, we will create a simp
7 min read
How to upload files in firebase storage using ReactJS ? Firebase Storage is a powerful cloud storage solution provided by Google's Firebase platform. It allows developers to store and retrieve user-generated content, such as images, videos, and other files, in a secure and scalable manner. In this article, we will explore how to upload files to Firebase
2 min read
How to Build a Simple TikTok Clone Android App using Firebase? TikTok is a mobile application that can be downloaded on smartphones and tablets. It is available on both iOS and Android operating systems and can be downloaded for free from the respective app stores. TikTok is a social media platform where users can view short video content i.e. 15 to 60 secs. A
5 min read
How to pre populate database in Android using SQLite Database Introduction : Often, there is a need to initiate an Android app with an already existing database. This is called prepopulating a database. In this article, we will see how to pre-populate database in Android using SQLite Database. The database used in this example can be downloaded as Demo Databas
7 min read
How to Update Data in API using Volley in Android? Prerequisite: JSON Parsing in Android using Volley LibraryHow to Post Data to API using Volley in Android? We have seen reading data from API as well as posting data to our database with the help of the API. In this article, we will take a look at updating our data in our API. We will be using the V
5 min read