Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • 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
  • 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:
How to Display Dynamic AlertDialog in Android using Firebase Firestore?
Next article icon

How to Display Dynamic AlertDialog in Android using Firebase Firestore?

Last Updated : 08 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Dynamic AlertDialog is used in many different apps which are used to show different messages from dialog to the users. This type of dialog is also used for educating users with so many promotional banners. This type of alert dialog is generally dynamic and it displays images and texts which are dynamic in behavior and change after a certain interval. In this article, we will take a look at the implementation of the dynamic alert dialog box in Android. 

What we are going to build in this article? 

We will be building a simple alert dialog in Android. Inside that AlertDialog, we will be displaying our image and text from Firebase. The data inside our alert dialog can be changed according to our requirements. A sample GIF 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.


firestore4-copy


Inside that column Navigate to Firebase Cloud Firestore. Click on that option and you will get to see two options on Connect app to Firebase and Add Cloud Firestore 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 connecting your app to Firebase you will get to see the below screen.  

firestore5-copy


After that verify that dependency for the Firebase Firestore database has been added to our Gradle file. Navigate to the app > Gradle Scripts inside that file to check whether the below dependency is added or not. If the below dependency is not present in your build.gradle file. Add the below dependency in the dependencies section.

implementation ‘com.google.firebase:firebase-firestore:22.0.1’

After adding this dependency sync your project and now we are ready for creating our app. If you want to know more about connecting your app to Firebase. Refer to this article to get in detail about How to add Firebase to Android App.  

Step 3: Working with the AndroidManifest.xml file

For adding data to Firebase we should have to give permissions for accessing the internet. For adding these permissions navigate to the app > AndroidManifest.xml and Inside that file add the below permissions to it.  

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

Step 4: Working with the activity_main.xml file

As we are not displaying any UI inside our activity_main.xml file so we are not adding any UI component in our activity_main.xml because we are displaying the data in our custom layout file. 


Step 5: Creating a new layout file for our alert dialog

As we are displaying one image and text inside our alert dialog. So we will be building a custom layout for our Alert Dialog. For creating a new layout file four our custom dialog box. Navigate to the app > res > layout > Right-click on it > Click on New > layout resource file and name it as custom_pop_up_layout and add below code to it. 

XML
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout      xmlns:android="http://schemas.android.com/apk/res/android"     android:layout_width="match_parent"     android:layout_height="wrap_content"     android:layout_margin="30dp"     android:background="@color/purple_500">      <!--Image view inside our dialog box-->     <ImageView         android:id="@+id/idIVNotification"         android:layout_width="300dp"         android:layout_height="300dp"         android:layout_below="@id/idTVNotification"         android:layout_centerHorizontal="true"         android:layout_margin="20dp" />      <!--Text view inside our dialog box-->     <TextView         android:id="@+id/idTVNotification"         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:layout_margin="8dp"         android:text="Notification Message"         android:textAlignment="center"         android:textColor="@color/white"         android:textSize="18sp" />      </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.app.AlertDialog; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast;  import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity;  import com.google.firebase.firestore.DocumentReference; import com.google.firebase.firestore.DocumentSnapshot; import com.google.firebase.firestore.EventListener; import com.google.firebase.firestore.FirebaseFirestore; import com.google.firebase.firestore.FirebaseFirestoreException; import com.squareup.picasso.Picasso;  public class MainActivity extends AppCompatActivity {      // initializing the variable for firebase firestore.     FirebaseFirestore db = FirebaseFirestore.getInstance();      @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_main);                  // creating a variable for our alert dialog builder.         AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);                  // creating a layout inflater variable.         LayoutInflater inflater = getLayoutInflater();                  // below line is for inflating a custom pop up layout.         View dialoglayout = inflater.inflate(R.layout.custom_pop_up_layout, null);                  // initializing the textview and imageview from our dialog box.         TextView notificationTV = dialoglayout.findViewById(R.id.idTVNotification);         ImageView notificationIV = dialoglayout.findViewById(R.id.idIVNotification);          // creating a variable for document reference.         DocumentReference documentReference = db.collection("MyData").document("Data");                  // adding snapshot listener to our document reference.         documentReference.addSnapshotListener(new EventListener<DocumentSnapshot>() {             @Override             public void onEvent(@Nullable DocumentSnapshot value, @Nullable FirebaseFirestoreException error) {                 // inside the on event method.                 if (error != null) {                     // this method is called when error is not null                      // and we get any error                     // in this case we are displaying an error message.                     Toast.makeText(MainActivity.this, "Error found is " + error, Toast.LENGTH_SHORT).show();                     return;                 }                 if (value != null && value.exists()) {                     // if the value from firestore is not null then we are                     // getting our data and setting that data to our text view.                     // after getting the value from firebase firestore                     // we are setting it to our text view and image view.                     notificationTV.setText(value.getData().get("NotificationMessage").toString());                     Picasso.get().load(value.getData().get("NotificationImage").toString()).into(notificationIV);                 }             }         });                  // after setting the text to our text view.         // we are displaying our alert dialog.         builder.setView(dialoglayout);         builder.show();     } } 


Step 7: Adding the data to Firebase Firestore Console in Android

After adding this code go to this link to open Firebase. After clicking on this link you will get to see the below page and on this page Click on Go to Console option in the top right corner.  

firebasescreen-660x294
Step 7 | Adding the data to firebase firestore console in android


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 Firebase Firestore Database in the left window.  

firestore1-copy


After clicking on Create Database option you will get to see the below screen.  

firestore2-copy


Inside this screen, we have to select the Start in test mode option. We are using test mode because we are not setting authentication inside our app. So we are selecting Start in test mode. After selecting on test mode click on the Next option and you will get to see the below screen.  

firestore3-copy


Inside this screen, we just have to click on Enable button to enable our Firebase Firestore database. After completing this process we just have to run our application and add data inside Firebase Console. For adding the data click on the Start Collection option and add your collection Name as "MyData". After adding this we have to add our Document ID as "Data". Inside the fields section, we have to add our field name as "NotificationImage" for displaying our image in the notification and enter the corresponding value of it (URL for the image). And create another file and name the field as "NotificationMessage" to display the message inside our notification. Also, enter the corresponding value of it. At last click on the Save button.


OptimizedCapture1

After adding data the screen will look like the following. You can edit and delete those files.

dynamic-alert-dialog


Now run the app and see the output of the app below : 

Output:


Next Article
How to Display Dynamic AlertDialog in Android using Firebase Firestore?

C

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

Similar Reads

    How to Create Dynamic ListView in Android using Firebase Firestore?
    ListView is one of the most used UI components in Android which you can find across various apps. So we have seen listview in many different apps. In the previous article, we have seen implementing ListView in Android using Firebase Realtime Database. Now in this article, we will take a look at the
    9 min read
    How to Create Dynamic Intro Slider in Android using Firebase Firestore?
    We have seen creating a basic Intro Slider in Android which is used to inform our users regarding the features of our app and many more. In this article, we will take a look at the implementation of dynamic Intro Slider in our app with the help of Firebase. With the help of Firebase Firestore, we ca
    11 min read
    How to Create Dynamic Bottom Sheet Dialog in Android using Firebase Firestore?
    Bottom Sheet Dialog is one of the famous Material UI Component which is used to display data or notifications in it. We can display any type of data or any UI component in our Bottom Sheet Dialog. In this article, we will take a look at the implementation of dynamic Bottom Sheet Dialog in Android us
    7 min read
    How to Create Dynamic Horizontal RecyclerView in Android using Firebase Firestore?
    HorizontalRecyclerView is seen in many apps. It is generally used to display the categories in most apps and websites. This type of RecyclerView is seen in many E-commerce apps to indicate categories in the app. And this RecyclerView is also dynamic so that the admin can add or remove any item from
    9 min read
    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
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