Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Android Jetpack Compose - Create Dynamic WebView using Firebase Realtime Database
Next article icon

How to Create a Dynamic Video Player in Android with Firebase Realtime Database?

Last Updated : 22 Dec, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Most of the apps use the video player to display so many videos inside their application. So for playing the video the app plays the video from its video URL. But what if we want to update that video on a real-time basis. So, in that case, we have to update our database and then later on we have to update our APK. So this is not an efficient way to do it. In this article, we will take a look at the implementation of the dynamic video player in Android using Firebase Realtime Database.

What we are going to build in this article? 

We will be building a simple application in which we will be playing a video in an ExoPlayer and we will be loading a video inside our ExoPlayer from Firebase. Along with that, we will be able to change our video in runtime. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language.

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.

Step 2: Connect your app to Firebase  

After creating a new project. Navigate to the Tools option on the top bar. Inside that click on Firebase. After clicking on Firebase, you can get to see the right column mentioned below in the screenshot.  

Inside that column Navigate to Firebase Realtime Database. Click on that option and you will get to see two options on Connect app to Firebase and Add Firebase Realtime Database to your app. Click on Connect now option and your app will be connected to Firebase. After that click on the second option and now your App is connected to Firebase.  

After completing this process you will get to see the below screen.  

Now verify that your app is connected to Firebase or not. Go to your build.gradle file. Navigate to the app > Gradle Scripts > build.gradle (app) file and make sure that the below dependency is added in your dependencies section.  

implementation 'com.google.firebase:firebase-database:19.6.0'

After adding this dependency add the dependency of ExoPlayer in your Gradle file.  

Step 3: Add the dependency for ExoPlayer View in build.gradle file

Navigate to the app > Gradle Scripts > build.gradle (app) file and add below dependency in it. 

// dependency for exoplayer

implementation 'com.google.android.exoplayer:exoplayer:r2.4.0'

// for core support in exoplayer.

implementation 'com.google.android.exoplayer:exoplayer-core:r2.4.0'

// for adding dash support in our exoplayer.

implementation 'com.google.android.exoplayer:exoplayer-dash:r2.4.0'

// for adding hls support in exoplayer.

implementation 'com.google.android.exoplayer:exoplayer-hls:r2.4.0'

// for smooth streaming of video in our exoplayer.

implementation 'com.google.android.exoplayer:exoplayer-smoothstreaming:r2.4.0'

// for generating default ui of exoplayer

implementation 'com.google.android.exoplayer:exoplayer-ui:r2.4.0'

After adding this dependency sync your project. Now we will move towards our XML part.  

Step 4: Adding permission for the Internet  

As we are loading our video from the internet so we have to add permissions for the Internet in the Manifest file. Navigate to the app > AndroidManifest.xml file and add the below permissions in it.  

XML
<!--Permissions for internet--> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 

  

Step 5: Working with the activity_main.xml file

Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file.

XML
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout      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:orientation="vertical"     tools:context=".MainActivity">      <!--Widget for exoplayer view-->     <com.google.android.exoplayer2.ui.SimpleExoPlayerView         android:id="@+id/idExoPlayerView"         android:layout_width="match_parent"         android:layout_height="500dp" />  </RelativeLayout> 

Step 6: 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.net.Uri; import android.os.Bundle; import android.util.Log; import android.widget.Toast;  import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity;  import com.google.android.exoplayer2.ExoPlayerFactory; import com.google.android.exoplayer2.SimpleExoPlayer; import com.google.android.exoplayer2.extractor.DefaultExtractorsFactory; import com.google.android.exoplayer2.extractor.ExtractorsFactory; import com.google.android.exoplayer2.source.ExtractorMediaSource; import com.google.android.exoplayer2.source.MediaSource; import com.google.android.exoplayer2.trackselection.AdaptiveTrackSelection; import com.google.android.exoplayer2.trackselection.DefaultTrackSelector; import com.google.android.exoplayer2.trackselection.TrackSelector; import com.google.android.exoplayer2.ui.SimpleExoPlayerView; import com.google.android.exoplayer2.upstream.BandwidthMeter; import com.google.android.exoplayer2.upstream.DefaultBandwidthMeter; import com.google.android.exoplayer2.upstream.DefaultHttpDataSourceFactory; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener;  public class MainActivity extends AppCompatActivity {      // creating a variable for our Firebase Database.     FirebaseDatabase firebaseDatabase;          // creating a variable for our Database      // Reference for Firebase.     DatabaseReference databaseReference;          // creating a variable for exoplayerview.     SimpleExoPlayerView exoPlayerView;          // creating a variable for exoplayer     SimpleExoPlayer exoPlayer;      @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_main);         exoPlayerView = findViewById(R.id.idExoPlayerView);                  // below line is used to get the          // instance of our Firebase database.         firebaseDatabase = FirebaseDatabase.getInstance();                  // below line is used to get reference for our database.         databaseReference = firebaseDatabase.getReference("url");         getVideoUrl();     }      private void getVideoUrl() {         // calling add value event listener method          // for getting the values from database.         databaseReference.addValueEventListener(new ValueEventListener() {             @Override             public void onDataChange(@NonNull DataSnapshot snapshot) {                 // this method is call to get the                  // realtime updates in the data.                 // this method is called when the                  // data is changed in our Firebase console.                 // below line is for getting the data                  // from snapshot of our database.                 String videoUrl = snapshot.getValue(String.class);                                  // after getting the value for our video url                  // we are passing that value to our                 // initialize exoplayer method to load our video                 initializeExoplayerView(videoUrl);             }              @Override             public void onCancelled(@NonNull DatabaseError error) {                 // calling on cancelled method when we receive                 // any error or we are not able to get the data.                 Toast.makeText(MainActivity.this, "Fail to get video url.", Toast.LENGTH_SHORT).show();             }         });     }      private void initializeExoplayerView(String videoURL) {         try {             // bandwidthmeter is used for getting default bandwidth             BandwidthMeter bandwidthMeter = new DefaultBandwidthMeter();             // track selector is used to navigate between video using a default seeker.             TrackSelector trackSelector = new DefaultTrackSelector(new AdaptiveTrackSelection.Factory(bandwidthMeter));                          // we are adding our track selector to exoplayer.             exoPlayer = ExoPlayerFactory.newSimpleInstance(this, trackSelector);                         // we are parsing a video url and              // parsing its video uri.             Uri videouri = Uri.parse(videoURL);                         // we are creating a variable for data source             // factory and setting its user agent as 'exoplayer_view'             DefaultHttpDataSourceFactory dataSourceFactory = new DefaultHttpDataSourceFactory("exoplayer_video");                          // we are creating a variable for extractor              // factory and setting it to default extractor factory.             ExtractorsFactory extractorsFactory = new DefaultExtractorsFactory();                          // we are creating a media source with above variables              // and passing our event handler as null,             MediaSource mediaSource = new ExtractorMediaSource(videouri, dataSourceFactory, extractorsFactory, null, null);                          // inside our exoplayer view              // we are setting our player             exoPlayerView.setPlayer(exoPlayer);                          // we are preparing our exoplayer              // with media source.             exoPlayer.prepare(mediaSource);                          // we are setting our exoplayer              // when it is ready.             exoPlayer.setPlayWhenReady(true);         } catch (Exception e) {             // below line is used for handling our errors.             Log.e("TAG", "Error : " + e.toString());         }     } } 

Step 7: Adding URL for Video in your Firebase Console 

For adding Video URL in Firebase Console. Browse for Firebase in your browser and Click on Go to Console option in the top right corner as shown in the below screenshot.  

 After clicking on Go to Console option you will get to see your project. Click on your project name from the available list of projects. 

After clicking on your project. Click on the Realtime Database option in the left window.  

After clicking on this option you will get to see the screen on the right side. On this page click on the Rules option which is present in the top bar. You will get to see the below screen.  

In this project, we are adding our rules as true for reading as well as write because we are not using any authentication to verify our user. So we are currently setting it to true to test our application. After changing your rules. Click on the publish button at the top right corner and your rules will be saved there. Now again come back to the Data tab. Now we will be adding our data to Firebase manually from Firebase itself.

Inside Firebase Realtime Database. Navigate to the Data tab. Inside this tab on the database section click on the "+" icon. After clicking on the "+" icon you will get to see two input fields which are the Name and Value fields. Inside the Name field, you have to add the reference for your video file which in our case is "url". And in our value field, we have to add the URL for our video file. After adding the value in this field. Click on the Add button and your data will be added to Firebase Console.  

After adding the URL for your video. Now run your app and see the output of the app below: 

Output:

You can change the URL of your video dynamically. 


Next Article
Android Jetpack Compose - Create Dynamic WebView using Firebase Realtime Database

C

chaitanyamunje
Improve
Article Tags :
  • Java
  • Technical Scripter
  • Android
  • Firebase
  • Technical Scripter 2020
  • Android Projects
Practice Tags :
  • Java

Similar Reads

  • How to Create a Dynamic Audio Player in Android with Firebase Realtime Database?
    Many online music player apps require so many songs, audio files inside their apps. So to handle so many files we have to either use any type of database and manage all these files. Storing files inside your application will not be a better approach. So in this article, we will take a look at implem
    7 min read
  • How to Create Dynamic PDF Viewer in Android with Firebase?
    If you are creating apps for students or for educational purposes then you need to add some PDF files for displaying some data inside our app. These PDF files are updated on regular basis. For loading this PDF from the server we prefer to use PDF Viewer which will load the PDF from the URL in Androi
    8 min read
  • How to Create Dynamic WebView in Android with Firebase?
    Converting a website into an application seems like a basic task to do on Android. With the help of WebView, we can show any webpage in our Android Application. We just have to implement the widget of WebView and add the URL inside the WebView which we have to load. So if you are looking for loading
    6 min read
  • Android Jetpack Compose - Create Dynamic WebView using Firebase Realtime Database
    Converting a website into an application seems like a basic task to do on Android. With the help of WebView, we can show any webpage in our Android Application. We just have to implement the widget of WebView and add the URL inside the WebView that we have to load. So if you are looking for loading
    8 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 Retrieve Data from the Firebase Realtime Database in Android?
    Firebase Realtime Database is the backend service which is provided by Google for handling backend tasks for your Android apps, IOS apps as well as your websites. It provides so many services such as storage, database, and many more. The feature for which Firebase is famous is for its Firebase Realt
    5 min read
  • How to Retrieve Data from Firebase Realtime Database in Android ListView?
    Firebase Realtime Database provides us a feature to give Real-time updates to your data inside your app within milli-seconds. With the help of Firebase, you can provide Real-time updates to your users. In this article, we will take a look at the implementation of the Firebase Realtime Database for o
    7 min read
  • Firebase RealTime Database with Operations in Android with Examples
    Firebase Realtime Database is a Cloud hosted database, i.e. it runs on a cloud and access to the user is provided as a service. It stores data in JSON (Javascript Object Notation) format, a format to store or transport data. All the users connected to it can get access to the data at Real Time. Feat
    6 min read
  • How to Retrieve PDF File From Firebase Realtime Database in Android?
    When we are creating an Android app then instead of inserting a pdf manually we want to fetch the pdf using the internet from Firebase. Firebase Realtime Database is the backend service that is provided by Google for handling backend tasks for your Android apps, IOS apps as well as your websites. It
    8 min read
  • How to Delete Data from Firebase Realtime Database in Android?
    In this article, we will see How to Delete added data inside our Firebase Realtime Database. So we will move towards the implementation of this deleting data in Android Firebase.   What we are going to build in this article?   We will be showing a simple AlertBox when the user long clicks on the ite
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences