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 for Android
  • Android Studio
  • Android Kotlin
  • Kotlin
  • Flutter
  • Dart
  • Android Project
  • Android Interview
Open In App
Next Article:
How to Use Firebase Cloud Messaging (FCM) in Android?
Next article icon

How to Use Firebase ML Kit Smart Replies in Android?

Last Updated : 21 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

We have seen using chatbots in Android for replying to the most common questions from the users. In this article, we will take a look at the implementation of Firebase ML Kit smart replies in Android. Firebase ML Kit smart replies are used to provide smart replies to the questions asked by the users using the Firebase ML Kit. 

What we are going to build in this article? 

We will be building a simple application in which we will be making a chatting-like interface in which the user will post his query in the chat box and according to the user’s query we will get to see the message from Firebase ML Kit.

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.

Step 2: Connect your app to Firebase and add

Navigate to Tools on the top bar. After that click on Firebase. A new window will open on the right side. Inside that window click on Firebase ML and then click on Use Firebase ML kit in Android. You can see the option below screenshot.

firebase-ml-kit


After clicking on this option on the next screen click on Connect to Firebase option to connect your app to Firebase. After the setup is completed, click on Add Firebase ML to you app and add all the dependencies.


Step 3: Adding dependency for language translation and add View Binding support

Navigate to the Gradle Scripts > build.gradle.kts(Module:app) and add the below dependency in the dependencies section.   

dependencies {
...
implementation ("com.google.firebase:firebase-ml-natural-language-smart-reply-model:20.0.8")
}

And in the same add the following code anywhere under android tag

buildFeatures {
viewBinding = true
}

Now sync your project and let’s move towards the implementation of Firebase ML Kit smart replies.


Step 4: Working with the MainActivity and it’s layout file

Navigate to the MainActivity and activity_main.xml and make the following changes.

MainActivity.java
package org.geeksforgeeks.demo;  import android.os.Bundle; import android.view.View; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import com.google.firebase.ml.naturallanguage.FirebaseNaturalLanguage; import com.google.firebase.ml.naturallanguage.smartreply.FirebaseTextMessage; import com.google.firebase.ml.naturallanguage.smartreply.SmartReply; import com.google.firebase.ml.naturallanguage.smartreply.SmartReplySuggestionResult; import org.geeksforgeeks.demo.databinding.ActivityMainBinding; import java.util.ArrayList; import java.util.List;  public class MainActivity extends AppCompatActivity {      private List<FirebaseTextMessage> messageList;     private ArrayList<MessageModel> messageModelArrayList;     private Adapter adapter;      private ActivityMainBinding binding;      @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         binding = ActivityMainBinding.inflate(getLayoutInflater());         setContentView(binding.getRoot());          messageList = new ArrayList<>();         messageModelArrayList = new ArrayList<>();         adapter = new Adapter(this, messageModelArrayList);          LinearLayoutManager manager = new LinearLayoutManager(this);         binding.recyclerView.setLayoutManager(manager);         binding.recyclerView.setAdapter(adapter);          binding.sendButton.setOnClickListener(new View.OnClickListener() {             @Override             public void onClick(View v) {                 String message = binding.messageEditText.getText().toString();                 if (message.isEmpty()) {                     Toast.makeText(MainActivity.this, "Please enter your message..", Toast.LENGTH_SHORT).show();                     return;                 }                 sendMessage(message);                 binding.messageEditText.setText("");             }         });     }      private void sendMessage(String userMessage) {                  // Create a FirebaseTextMessage         FirebaseTextMessage message = FirebaseTextMessage.createForRemoteUser(                 userMessage, System.currentTimeMillis(), "uid");          messageList.add(message);                  // 0 -> user message         messageModelArrayList.add(new MessageModel(userMessage, 0));                   adapter.notifyDataSetChanged();          // Firebase Smart Reply         SmartReply smartReply = FirebaseNaturalLanguage.getInstance().getSmartReply();          smartReply.suggestReplies(messageList)                 .addOnSuccessListener(smartReplySuggestionResult -> {                     if (smartReplySuggestionResult.getStatus() == SmartReplySuggestionResult.STATUS_NOT_SUPPORTED_LANGUAGE) {                         Toast.makeText(MainActivity.this, "Language not supported..", Toast.LENGTH_SHORT).show();                     } else if (smartReplySuggestionResult.getStatus() == SmartReplySuggestionResult.STATUS_SUCCESS) {                         if (!smartReplySuggestionResult.getSuggestions().isEmpty()) {                             messageModelArrayList.add(new MessageModel(smartReplySuggestionResult.getSuggestions().get(0).getText(), 1));                             adapter.notifyDataSetChanged();                         }                     }                 })                 .addOnFailureListener(e ->                      Toast.makeText(MainActivity.this, "Fail to get data: " + e.getMessage(), Toast.LENGTH_SHORT).show());     } } 
MainActivity.kt
package org.geeksforgeeks.demo  import android.os.Bundle import android.view.View import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.LinearLayoutManager import com.google.firebase.ml.naturallanguage.FirebaseNaturalLanguage import com.google.firebase.ml.naturallanguage.smartreply.FirebaseTextMessage import com.google.firebase.ml.naturallanguage.smartreply.SmartReplySuggestionResult import org.geeksforgeeks.demo.databinding.ActivityMainBinding  class MainActivity : AppCompatActivity() {     private var messageList: MutableList<FirebaseTextMessage>? = null     private var messageModelArrayList: ArrayList<MessageModel>? = null     private var adapter: Adapter? = null      private val binding: ActivityMainBinding by lazy {         ActivityMainBinding.inflate(layoutInflater)     }      override fun onCreate(savedInstanceState: Bundle?) {         super.onCreate(savedInstanceState)         setContentView(binding.root)          messageList = ArrayList()         messageModelArrayList = ArrayList()         adapter = Adapter(this, messageModelArrayList!!)         val manager = LinearLayoutManager(this)         binding.recyclerView.setLayoutManager(manager)         binding.recyclerView.setAdapter(adapter)          binding.sendButton.setOnClickListener(View.OnClickListener {             val message = binding.messageEditText.text.toString()             if (message.isEmpty()) {                 Toast.makeText(this, "Please enter your message..", Toast.LENGTH_SHORT)                     .show()                 return@OnClickListener             }              sendMessage(message)             binding.messageEditText.setText("")         })     }      private fun sendMessage(userMessage: String) {                  // pass user input to firebase as message         val message = FirebaseTextMessage.createForRemoteUser(             binding.messageEditText.text.toString(),             System.currentTimeMillis(),             "uid"         )         messageList!!.add(message)          // 0-> user message         // 1-> Firebase message         messageModelArrayList!!.add(MessageModel(userMessage, 0))          adapter!!.notifyDataSetChanged()          // Firebase smart reply instance         val smartReply = FirebaseNaturalLanguage.getInstance().smartReply          // suggest reply for user message         smartReply.suggestReplies(messageList!!)             .addOnSuccessListener { smartReplySuggestionResult ->                                  // checking if the language is not supported                 if (smartReplySuggestionResult.status == SmartReplySuggestionResult.STATUS_NOT_SUPPORTED_LANGUAGE) {                     Toast.makeText(this, "Language not supported..", Toast.LENGTH_SHORT).show()                 } else if (smartReplySuggestionResult.status == SmartReplySuggestionResult.STATUS_SUCCESS) {                     messageModelArrayList!!.add(                         MessageModel(smartReplySuggestionResult.suggestions[0].text, 1)                     )                     adapter!!.notifyDataSetChanged()                 }             }             .addOnFailureListener { e -> // inside on failure method we are displaying a toast message                 Toast.makeText(this, "Fail to get data.." + e.message, Toast.LENGTH_SHORT).show()             }     } } 
activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout      xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:app="http://schemas.android.com/apk/res-auto"     xmlns:tools="http://schemas.android.com/tools"     android:layout_width="match_parent"     android:layout_height="match_parent"     tools:context=".MainActivity">      <!--recycler view for displaying our chat messages-->     <androidx.recyclerview.widget.RecyclerView         android:id="@+id/recyclerView"         android:layout_width="match_parent"         android:layout_height="0dp"         tools:listitem="@layout/msg_rv_item"         app:layout_constraintBottom_toTopOf="@+id/messageLayout"         app:layout_constraintEnd_toEndOf="parent"         app:layout_constraintStart_toStartOf="parent"         app:layout_constraintTop_toTopOf="parent" />      <LinearLayout         android:id="@+id/messageLayout"         android:layout_width="match_parent"         android:layout_height="80dp"         android:orientation="horizontal"         android:gravity="center"         android:weightSum="5"         app:layout_constraintBottom_toBottomOf="parent"         app:layout_constraintEnd_toEndOf="parent"         app:layout_constraintStart_toStartOf="parent">          <!--edit text for entering user message-->         <EditText             android:id="@+id/messageEditText"             android:layout_width="0dp"             android:layout_height="wrap_content"             style="@style/Widget.Material3.TextInputEditText.OutlinedBox"             android:hint="Write your message here..."             android:layout_weight="4"             android:importantForAutofill="no"             android:inputType="textShortMessage" />          <!--fab for sending message-->         <com.google.android.material.floatingactionbutton.FloatingActionButton             android:id="@+id/sendButton"             android:layout_width="0dp"             android:layout_height="wrap_content"             android:layout_weight="1"             android:importantForAccessibility="no"             android:src="@android:drawable/sym_action_chat"             app:tint="@color/white"             app:backgroundTint="@color/colorPrimary" />     </LinearLayout>  </androidx.constraintlayout.widget.ConstraintLayout> 


Step 5: Creating a modal class for storing our data

As we are displaying all our data in our RecyclerView. So we have to store this data in a modal class. For creating a modal class, Navigate to the app > java > your app’s package name > Right-click on it > New > Java/Kotlin class and name it as ChatMsgModal and add the below code to it. Comments are added inside the code to understand the code in more detail.

MessageModel.java
package org.geeksforgeeks.demo;  public class MessageModel {     private String message;     private int type;      public MessageModel(String message, int type) {         this.message = message;         this.type = type;     }      public String getMessage() {         return message;     }      public void setMessage(String message) {         this.message = message;     }      public int getType() {         return type;     }      public void setType(int type) {         this.type = type;     } } 
MessageModel.kt
package org.geeksforgeeks.demo  class MessageModel(     var message: String, var type: Int ) 


Step 6: Creating a layout file and Adapter for each item of the message 

Navigate to the app > res > layout, Right-click on it, New > layout resource file and name it as msg_rv_item. Then, navigate to the app > kotlin+java > {package-name}, Right-click on it, New > Java/Kotlin class and name it as Adapter.

Adapter.java
package org.geeksforgeeks.demo;  import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.cardview.widget.CardView; import androidx.core.content.ContextCompat; import androidx.recyclerview.widget.RecyclerView; import java.util.ArrayList;  public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder> {     private final Context context;     private final ArrayList<MessageModel> messageModelArrayList;      public Adapter(Context context, ArrayList<MessageModel> messageModelArrayList) {         this.context = context;         this.messageModelArrayList = messageModelArrayList;     }      public static class ViewHolder extends RecyclerView.ViewHolder {         TextView msgTV;         CardView msgCV;          public ViewHolder(@NonNull View itemView) {             super(itemView);             msgTV = itemView.findViewById(R.id.idTVMessage);             msgCV = itemView.findViewById(R.id.idCVMessage);         }     }      @NonNull     @Override     public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {         View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.msg_rv_item, parent, false);         return new ViewHolder(view);     }      @Override     public void onBindViewHolder(@NonNull ViewHolder holder, int position) {         MessageModel modal = messageModelArrayList.get(position);          holder.msgTV.setText(modal.getMessage());          if (modal.getType() == 1) {             holder.msgCV.setCardBackgroundColor(ContextCompat.getColor(context, R.color.colorPrimaryDark));             holder.msgTV.setTextColor(ContextCompat.getColor(context, R.color.white));         }     }      @Override     public int getItemCount() {         return messageModelArrayList.size();     } } 
Adapter.kt
package org.geeksforgeeks.demo  import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.cardview.widget.CardView import androidx.recyclerview.widget.RecyclerView  class Adapter (     private val context: Context,     private val messageModelArrayList: ArrayList<MessageModel> ) : RecyclerView.Adapter<Adapter.ViewHolder>() {      inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {         val msgTV: TextView = itemView.findViewById(R.id.idTVMessage)         val msgCV: CardView = itemView.findViewById(R.id.idCVMessage)     }      override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {         val view = LayoutInflater.from(parent.context).inflate(R.layout.msg_rv_item, parent, false)         return ViewHolder(view)     }      override fun getItemCount(): Int = messageModelArrayList.size      override fun onBindViewHolder(holder: ViewHolder, position: Int) {         val modal = messageModelArrayList[position]         if (modal.type == 0) {             holder.msgTV.text = modal.message         } else {             holder.msgTV.text = modal.message             holder.msgCV.setCardBackgroundColor(context.resources.getColor(R.color.colorPrimaryDark))             holder.msgTV.setTextColor(context.resources.getColor(R.color.white))         }     } } 
msg_rv_item.xml
<?xml version="1.0" encoding="utf-8"?> <androidx.cardview.widget.CardView     xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:app="http://schemas.android.com/apk/res-auto"     android:id="@+id/idCVMessage"     android:layout_width="match_parent"     android:layout_height="wrap_content"     android:layout_margin="5dp"     app:cardCornerRadius="8dp"     app:cardElevation="5dp">      <!--text view for displaying our message-->     <TextView         android:id="@+id/idTVMessage"         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:layout_margin="4dp"         android:padding="5dp"         android:text="Message"         android:textColor="@color/black" />  </androidx.cardview.widget.CardView> 

Output:

Note: You will get a certain delay in reply from Firebase for the first time. Also, the response from Firebase will not be accurate as this response are send from the Firebase ML kit model. 



Next Article
How to Use Firebase Cloud Messaging (FCM) in Android?

C

chaitanyamunje
Improve
Article Tags :
  • Android
  • Technical Scripter
  • Android Projects
  • Technical Scripter 2020

Similar Reads

  • How to Label Image in Android using Firebase ML Kit?
    We have seen many apps in Android in which we will detect the object present in the image whether it may be any object. In this article, we will take a look at the implementation of image labeling in Android using Firebase ML Kit.  What we are going to build in this article?  We will be building a s
    9 min read
  • How to Use Firebase Cloud Messaging (FCM) in Android?
    Firebase Cloud Messaging (FCM) is a service provided by Google that allows developers to send push notifications to Android, iOS, and web devices. FCM uses Google Cloud Messaging (GCM) as the underlying technology for sending and receiving messages but offers additional features such as the ability
    3 min read
  • How to Use Test Lab Console in Firebase?
    With the help of Firebase Test Lab, a cloud-based app testing infrastructure, you can test your app across a variety of platforms and setups to better understand how it will function when used by actual users. For those who are unfamiliar, Firebase Test Lab is a platform for testing apps on the clou
    4 min read
  • How to Retrieve Image from Firebase in Realtime in Android?
    When we are creating an android app then instead of inserting an image manually we want to get that from the internet and using this process the app size will become less. So, using firebase we can do this. We can create our storage bucket and we can insert our image there and get it directly into o
    4 min read
  • How to Create Language Translator in Android using Firebase ML Kit?
    In the previous article, we have seen using Language detector in Android using Firebase ML kit. In this article, we will take a look at the implementation of Language translator in Android using Firebase ML Kit in Android. What we are going to build in this article? We will be building a simple appl
    5 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 Change Password of User in Android using Firebase?
    In many apps, we got a feature to login using our email and password. Sometimes it happens that we forget the password and most of the time there reset our password. Here we are going to implement the same feature to Reset our password using Firebase Authentication. You may refer to the following ar
    3 min read
  • How to Use A/B Testing Console in Firebase?
    By making it simple to execute, evaluate, and scale product and marketing experiments, Firebase A/B Testing, which is powered by Google Optimize, aids in the optimization of the app experience. It allows developers the ability to test adjustments to the app's user interface (UI), features, or engage
    6 min read
  • Text Detector in Android using Firebase ML Kit
    Nowadays many apps using Machine Learning inside their apps to make most of the tasks easier. We have seen many apps that detect text from any image. This image may include number plates, images, and many more. In this article, we will take a look at the implementation of Text Detector in Android us
    6 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
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