Open In App

How to Change Android TextView Remotely Through Firebase?

Last Updated : 04 Jul, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

First Of all, let’s understand how we are going to do this first we will be using one feature of Firebase which is RemoteConfig, and with the help of that we are going to change the TextView. The basic principle of that you can change the text view of the app without pushing any update which is one of the main advantages of the Remote Config. To learn more about what remote config does you can refer to this How to Use Remote Config Console in Firebase.

Step-by-Step Implementation

Step 1: Create a New Project in Android Studio

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: Setting Up Firebase

First Create One New Project in Firebase and after successfully creating the project in firebase,in android studio at the top select  Click on Tools > Firebase.

Then at the left side of the Android Studio, many options will be displayed related to the Firebase then scroll and click on Remote Config. 

 

After That Connect your app to Firebase that you created and also click on Add the Remote Config SDK to your app to successfully add all the dependencies of the remote config.

 

Step 3: Now Go to Firebase Console and Your Project Dashboard That you created earlier After that click on Build and from the drop-down click on Remote Config.

After Selecting Remote config noe click on Remote config that will be displayed on top and click on the “Create Configuration” button. Next, enter the Parameter Name that will be utilized when retrieving the remote configuration and also for the default value. Finally, set the Data Type as String and in the default value section you can add the text and you can change it whenever you want to update the text view.

Step 4: Now Create an XML resource Directory with the Directory Name and Resource Type as XML only, If you already have one then don’t create one then just create one new XML resource file in the same folder that the XML file will be used for fetching we Set Our Remote Config Vlaue to in-app default, In this case, the XML resource file name is default_config.xml and add key as your parameter name that you created earlier and set value as default value
 

XML




<?xml version="1.0" encoding="utf-8"?>
<defaultsMap>
    <entry>
        <!-- Key Is Your Parameter Name that you created in Remote Config-->
        <key>textViewChange</key>
        <!-- Value will be Your Default Value of TextView
              When Remote Config set to in-app default-->
        <value>Welcome To Gfg App</value>
    </entry>
</defaultsMap>


Step 5: Now we have created one Simple MainActivity and also added a ScrollView outside Text view and added one default text view as “loading..”  and also added one progress bar.

activity_main.xml:

XML




<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/white"
    tools:context=".MainActivity">
  
    <LinearLayout
        android:id="@+id/toolbarLayout"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:elevation="4dp"
        android:orientation="horizontal"
        android:gravity="center_vertical">
  
        <TextView
            android:id="@+id/Title"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:text="Geeks For Geeks"
            android:textSize="25sp"
            android:textColor="#F6F6"
            android:layout_gravity="center_vertical"
            android:layout_weight="1"
            android:gravity="center" />
  
    </LinearLayout>
  
    <ScrollView
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginTop="8dp"
        app:layout_constraintTop_toBottomOf="@id/toolbarLayout"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        android:layout_gravity="center">
  
        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">
  
            <TextView
                android:id="@+id/longTextView"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Loading...."
                android:shadowColor="@color/black"
                android:textSize="14sp"
                android:textColor="@color/black"
                android:textStyle="bold"
                android:padding="16dp" />
  
            <ProgressBar
                android:id="@+id/progressBar"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center" />
  
        </FrameLayout>
    </ScrollView>
  
</androidx.constraintlayout.widget.ConstraintLayout>


MainActivity.java:

In This We are also monitoring the network changes when there is no internet and if the internet suddenly detected then automatically it will again start fetching.

Java




package com.example.gfgapp;
  
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkRequest;
import android.os.Bundle;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
  
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
  
import com.google.firebase.remoteconfig.FirebaseRemoteConfig;
import com.google.firebase.remoteconfig.FirebaseRemoteConfigSettings;
  
public class MainActivity extends AppCompatActivity {
  
    private FirebaseRemoteConfig mFirebaseRemoteConfig;
  
    private TextView longTextView;
    private ProgressBar progressBar;
  
    private final boolean isFetchingEnabled = true;
    private boolean isNetworkAvailable = false;
  
    private final ConnectivityManager.NetworkCallback networkCallback = new ConnectivityManager.NetworkCallback() {
        @Override
        public void onAvailable(@NonNull Network network) {
            // Network is available
            isNetworkAvailable = true;
            if (isFetchingEnabled) {
                // Fetching the remote 
                  // config if enabled
                fetchRemoteConfig(); 
            }
        }
  
        @Override
        public void onLost(@NonNull Network network) {
            // Network connection is lost
            isNetworkAvailable = false;
        }
    };
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        longTextView = findViewById(R.id.longTextView);
        progressBar = findViewById(R.id.progressBar);
  
        // Initializing Firebase Remote Config
        mFirebaseRemoteConfig = FirebaseRemoteConfig.getInstance();
        FirebaseRemoteConfigSettings configSettings = new FirebaseRemoteConfigSettings.Builder()
        // Setting The Minimum Time To Fetch the Remote Config Data From Server in Seconds
                .setMinimumFetchIntervalInSeconds(0)
                .build();
        mFirebaseRemoteConfig.setConfigSettingsAsync(configSettings);
        mFirebaseRemoteConfig.setDefaultsAsync(R.xml.default_config);
  
        fetchRemoteConfig(); // Fetching the initial remote config
        startMonitoringNetworkChanges(); // Starting monitoring network changes
    }
  
  
    @Override
    protected void onResume() {
        super.onResume();
        startMonitoringNetworkChanges(); // Resuming monitoring network changes
  
        if (isNetworkAvailable && isFetchingEnabled) {
              // Fetching remote config if network 
              // is available and fetching is enabled
            fetchRemoteConfig(); 
        }
    }
  
    @Override
    protected void onPause() {
        super.onPause();
          // Stoping monitoring network changes
          // when the activity is paused
        stopMonitoringNetworkChanges(); 
    }
  
    private void fetchRemoteConfig() {
        showProgressBar(); 
        mFirebaseRemoteConfig.fetchAndActivate().addOnCompleteListener(this, task -> {
            hideProgressBar(); 
            if (task.isSuccessful()) {
                  // Make Sure To Replace it with Your Parameter name
                  // In my case Paramater name of Remote Config is textViewChange
                String newTextView = mFirebaseRemoteConfig.getString("textViewChange");
                longTextView.setText(newTextView); // Updating the TextView with the fetched value
            } else {
                showInternetConnectionError(); // Showing error message if fetching fails
            }
        });
    }
  
    private void showProgressBar() {
          // Setting Visiblity Of Progress Bar To Visible
        runOnUiThread(() -> progressBar.setVisibility(View.VISIBLE));
    }
  
    private void hideProgressBar() {
          // Setting Visiblity Of Progress Bar To Gone
        runOnUiThread(() -> progressBar.setVisibility(View.GONE));
    }
  
    private void startMonitoringNetworkChanges() {
           // Registering network callback for monitoring changes
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkRequest networkRequest = new NetworkRequest.Builder().build();
        cm.registerNetworkCallback(networkRequest, networkCallback); 
    }
  
    private void stopMonitoringNetworkChanges() {
          // Unregistering network callback to stop monitoring
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        cm.unregisterNetworkCallback(networkCallback); // Unregister network callback to stop monitoring
    }
  
    private void showInternetConnectionError() {
        Toast.makeText(this, "Please check your internet connection", Toast.LENGTH_LONG).show();
    }
}


Note: Whenever You’re Changing and Updating the data Make Sure You Publish the changes also to edit the value of Remote Config data there is an option on the left side of the parameter name.

Output: We are Using Dummy Data To Display also in the video we have shown the value that is in the remote config and the value when set to in-app default.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads