How to Create Dynamic WebView in Android with Firebase? - GeeksforGeeks

15 Jan, 2021
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 a website into your app which can be changed dynamically without reformatting the code then this will become easier to update our WebView application dynamically according to our requirement. So in this article, we will take a look at implementing dynamic WebView in our application using Firebase in Android. 
In this article, we will be building a simple application in which we will be creating a simple WebView and we will load a URL for our WebView from Firebase Realtime Database. So if we want to change the URL for our WebView, we can easily change the URL of our WebView and it will be updated automatically inside our application. Note that we are going to implement this project using the Java language. 
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 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 file and make sure that the below dependency is added in your dependencies section.  
implementation ‘com.google.firebase:firebase-database:19.6.0’
If the above dependency is not added in your dependencies section. Add this dependency and sync your project. Now we will move towards the XML part of our app.  
Step 3: 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"    tools:context=".MainActivity">      <!--Web View for displaying our web pages-->    <WebView        android:id="@+id/idWebView"        android:layout_width="match_parent"        android:layout_height="match_parent" />      </RelativeLayout>
Step 4: Add internet permission in your AndroidManifest.xml file
Add the permission for the internet in the AndroidManifest.xml file. 
XML
<uses-permission android:name="android.permission.INTERNET" /><uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Step 5: 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.os.Bundle;import android.webkit.WebView;import android.webkit.WebViewClient;import android.widget.Toast;  import androidx.annotation.NonNull;import androidx.appcompat.app.AppCompatActivity;  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 our webview    private WebView webView;      @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);                  // initializing variable for web view.        webView = findViewById(R.id.idWebView);                  // 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");                  // calling method to initialize         // our web view.        initializeWebView();    }      private void initializeWebView() {          // 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 webUrl = snapshot.getValue(String.class);                                  // after getting the value for our webview url we are                // setting our value to our webview view in below line.                webView.loadUrl(webUrl);                webView.getSettings().setJavaScriptEnabled(true);                webView.setWebViewClient(new WebViewClient());            }              @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 URL.", Toast.LENGTH_SHORT).show();            }        });    }}
After adding this code to your app. Now go to Firebase and click on Go to console option which is on the top right corner.  
After clicking on this screen you will get to see the below screen with your all project inside that select your project.  
Inside that screen click n Realtime Database 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.
Step 6: Adding the WebView URL in Firebase Database Console  
Inside Firebase in the Data tab, you are getting to see the below screen. Hover your cursor on null and click on the “+” option on the right side and click on that option. After clicking on that option. Add the data as added in the below image. Make sure to add “url” in the Name field because we are setting our reference for Firebase as “url” in our code. So we have to set it to “url”. You can change your reference and also change it in the Database. Inside the value field, you have to add the URL of the web page which you want to load in your WebView. 
After adding the above data you will get to see the below screen. 
After adding this data run your app and see the output of the app. After running your app you can check the website url inside your Firebase Console and you can get to see the changes in your WebView. 
In the video, we are changing the website URL from Firebase and you can get to see changes in the app.
android
Technical Scripter 2020
Android
Java
Technical Scripter
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Resource Raw Folder in Android Studio
Flutter - Custom Bottom Navigation Bar
How to Read Data from SQLite Database in Android?
Flexbox-Layout in Android
How to Post Data to API using Retrofit in Android?
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Object Oriented Programming (OOPs) Concept in Java
Stream In Java