Display Firestore data in RecyclerView [Java]

I wanted to do something that would update the RecyclerView display every time the Firestore data was updated, but I had a hard time because there were no articles written in Japanese.

In this article, refer to Firebase UI for Cloud Firestore and use ** Firestore Recycler Adapter ** to create a chat app. I will make it.

If you haven't created a database in Firestore yet, please refer to Try Cloud Firestore.

Model of data to display

This is a model of the data that makes up the chat of the chat app.

Chat.java


public class Chat {
    private String mName;
    private String mMessage;
    private String mUid;
    private Date mTimestamp;

    public Chat() { } // Needed for Firebase

    public Chat(String name, String message, String uid) {
        mName = name;
        mMessage = message;
        mUid = uid;
    }

    public String getName() { return mName; }

    public void setName(String name) { mName = name; }

    public String getMessage() { return mMessage; }

    public void setMessage(String message) { mMessage = message; }

    public String getUid() { return mUid; }

    public void setUid(String uid) { mUid = uid; }

    @ServerTimestamp
    public Date getTimestamp() { return mTimestamp; }

    public void setTimestamp(Date timestamp) { mTimestamp = timestamp; }
}

Preparing the Firebase UI

First, import the Firebase UI for Cloud Firestore. This is to use the Firestore Recycler Adapter.

app/build.gradle


implementation "com.firebaseui:firebase-ui-firestore:6.2.1"

Creating a Query

Create a query for the "chats" collection.

MainActivity.java


Query query = FirebaseFirestore.getInstance()
        .collection("chats")
        .orderBy("timestamp")
        .limit(50); //Get the latest 50

Set of queries

I will put in the query created earlier. In Chat.class, put your own model class.

MainActivity.java


FirestoreRecyclerOptions<Chat> options = new FirestoreRecyclerOptions.Builder<Chat>()
        .setQuery(query, Chat.class)
        .build();

The above code will automatically put the data obtained by the query into the "Chat class", but if you want to put it yourself for some reason, please do as follows.

MainActivity.java



FirestoreRecyclerOptions<Chat> options = new FirestoreRecyclerOptions.Builder<Chat>()
        .setQuery(query, new SnapshotParser<Chat>() {
        @Override
        public Chat parseSnapshot(@NonNull DocumentSnapshot snapshot) {
            /*Write the process you want to do when taking a snapshot*/
            name = snapshot.getString("mName");
            message = snapshot.getString("mMessage");
            uid = snapshot.getString("mUid");
            Chat chat = new Chat(name,message,uid);
            return chat;
       }
       })
      .build();

Creating a ViewHolder

Create a class that inherits from RecyclerView.ViewHolder.

ChatHolder.java


public class ChatHolder extends RecyclerView.ViewHolder {

    public TextView messsageText;
    public TextView nameText;

    public ChatHolder(View itemView) {
        super(itemView);
        messsageText = itemView.findViewById(R.id.message_text);
        nameText = itemView.findViewById(R.id.name_text);
    }
    
   public void setMessage(String message){
       messsageText.setText(message);
   }
   
   public void setName(String name){
       nameText.setText(name);
   }
}

Create an adapter

Adapters are created by inheriting the Firestore Recycler Adapter.

MainActivity.java


FirestoreRecyclerAdapter adapter = new FirestoreRecyclerAdapter<Chat, ChatHolder>(options) {
    @Override
    public void onBindViewHolder(ChatHolder holder, int position, Chat model) 
    {
        //I will put an object of Chat class in ChatHolder
        holder.setMessage(model.getMessage());
        holder.setName(model.getName());
    }

    @Override
    public ChatHolder onCreateViewHolder(ViewGroup group, int i) {
        //Here we will create an instance of ViewHolder
        View view = LayoutInflater.from(group.getContext())
                .inflate(R.layout.message, group, false);

        return new ChatHolder(view);
    }
};

[Don't forget] Listener registration

It will not work without a listener. I was a little addicted here. .. ..

MainActivity.java


@Override
protected void onStart() {
    super.onStart();
    adapter.startListening();
}

@Override
protected void onStop() {
    super.onStop();
    adapter.stopListening();
}

that's all! Thank you for your hard work!

in conclusion

You should be able to go with this! Please let me know if you have any mistakes or questions! Let's do our best for Android development! If you like, please LGTM.

reference

Recommended Posts

Display Firestore data in RecyclerView [Java]
Importing Excel data in Java 2
Import Excel data in Java
Importing Excel data in Java 3
[For beginners] Minimum sample to display RecyclerView in Java
Create variable length binary data in Java
Display message dialog in java (personal memo)
Partization in Java
Changes in Java 11
Rock-paper-scissors in Java
Pi in Java
FizzBuzz in Java
How to display a web page in Java
Display text as ASCII art in Java (jfiglet)
Display GIS data in ElasticSearch in QGIS via GeoServer
Organized memo in the head (Java --Data type)
Display "Hello World" in the browser using Java
Display "Hello World" in the browser using Java
Set pop-up display for Java language in vim.
[java] sort in list
Read JSON in Java
Interpreter implementation in Java
Make Blackjack in Java
Rock-paper-scissors app in Java
Display PlantUML in MkDocs
NVL-ish guy in Java
Combine arrays in Java
"Hello World" in Java
Callable Interface in Java
Comments in Java source
Vectorize and image MNIST handwritten digit image data in Java
[Java] Data type ①-Basic type
Azure functions in java
Format XML in Java
Simple htmlspecialchars in Java
How to create a data URI (base64) in Java
Boyer-Moore implementation in Java
Hello World in Java
Use OpenCV in Java
webApi memorandum in java
Type determination in Java
Ping commands in Java
Various threads in java
Heapsort implementation (in java)
Zabbix API in Java
ASCII art in Java
Compare Lists in Java
POST JSON in Java
Express failure in Java
[Java] Main data types
Create JSON in Java
Date manipulation in Java 8
What's new in Java 8
Use PreparedStatement in Java
What's new in Java 9,10,11
Parallel execution in Java
Initializing HashMap in Java
Java basic data types
Java code sample to acquire and display DBLINK source and destination data in Oracle Database using DBLINK
Let's make a calculator application in Java ~ Display the application window
Get weather forecasts from Watson Weather Company Data in simple Java