RecyclerView with Firebase Android Studio Tutorial

In this “RecyclerView with Firebase Android Studio Tutorial”, you will learn everything you need to know about RecyclerViews and but also about how to use different ViewTypes and how to customize your list items using XML. RecyclerViews in Android, are one of the most interesting concepts to become a master in Android. There’s a lot of different examples and implementations across the internet. Frist of all, we need to know what is RecylerView means. In here we are going to display a list view that is already in firebase database. So first of all, you need to connect this project to the firebase. (Click here refer connecting to the firebase).


What is RecyclerView in android?

In shortly we can say, RecyclerView is the ViewGroup that contains the views corresponding to your data. It means a flexible view for providing a limited window into a large data set.

It is essentially a ViewGroup of containers called ViewHolders which populate a particular item. That is why we use RecylerView. RecyclerView is an extensive Android class to provide a flexible UI. A great benefit of using RecyclerViews is that you’re able to efficiently reuse views instead of managing items that aren’t even visible to a user.

So let’s get into code.


Single Layout File design – First step to RecyclerView with Firebase Android Studio Tutorial

In your Layout folder, right click and create a new layout resource file. I am going to called it as “singale_restaurant”. Because In this Android Tutorial, I am going to design and implement a Restaurant page with Restaurant List. Refer the below image. This will be our “single_restaurant.xml” file.

Follow the below code.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:paddingLeft="20dp"
    android:paddingRight="20dp"
    android:paddingTop="10dp"
    android:layout_height="120dp">

    <androidx.cardview.widget.CardView
        android:id="@+id/main_blog_post"
        android:layout_width="match_parent"
        app:cardCornerRadius="9dp"
        android:layout_height="100dp">

        <LinearLayout
            android:id="@+id/single_item"
            android:layout_width="match_parent"
            android:layout_height="100dp"
            android:background="@drawable/rounded_border_main"
            android:orientation="vertical">
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="horizontal">

                <ImageView
                    android:id="@+id/place_image"
                    android:layout_width="150dp"
                    android:padding="2dp"
                    android:layout_height="100dp"/>

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="100dp"
                    android:orientation="vertical">

                    <TextView
                        android:id="@+id/restaurant_name"
                        android:layout_marginTop="10dp"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_marginLeft="10dp"
                        android:text="Name"
                        android:textStyle="bold"
                        android:textSize="17dp"
                        android:textColor="#04095E"/>

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:orientation="horizontal">
                        <TextView
                            android:id="@+id/address"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_marginLeft="10dp"
                            android:text="District"
                            android:textColor="#F94001"
                            android:textSize="15dp" />
                    </LinearLayout>

                    <TextView
                        android:id="@+id/select"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_marginTop="5dp"
                        android:padding="5dp"
                        android:gravity="center"
                        android:textColor="#04095E"
                        android:background="#e9f5f8"
                        android:textStyle="bold"
                        android:layout_marginLeft="10dp"
                        android:layout_marginRight="15dp"
                        android:text="Select"
                        android:textSize="15dp" />

                </LinearLayout>
            </LinearLayout>
        </LinearLayout>
    </androidx.cardview.widget.CardView>

</LinearLayout>

In here we have a image that will represent the restaurant image, Restaurant Name TextView, another TextView to display the district and a button to go that single Restaurant page. The Button action will implement in the next tutorial. Let’s design and code for create a List view in RecyclerView.


RecyclerView Adapter in Android

Okay. Then we need to design a page to display this Listview. To do that create a new activity. I am going to call this as “AllRestaurantsActivity”.

Next go to “activty_all_restaurant.xml” file. Then implement the RecyclerView. Like this.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".Restaurants.AllRestaurantsActivity">

                <RelativeLayout
                    android:id="@+id/restaurantList"
                    android:layout_below="@+id/mainHead"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content">

                    <androidx.recyclerview.widget.RecyclerView
                        android:id="@+id/places_list"
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        android:layout_marginTop="30dp"
                        android:paddingBottom="60dp"
                        app:layout_constraintBottom_toBottomOf="parent"
                        app:layout_constraintEnd_toEndOf="parent"
                        app:layout_constraintStart_toStartOf="parent"
                        app:layout_constraintTop_toTopOf="parent" />
                </RelativeLayout>

</LinearLayout>

Then before going to “AllRestaurantsActivity.java” file, we need to create an Adapter Java class to handle this recyclerview. So create a Java class to implement the code. I am going to call this as “RestaurantAdapter.java”.

Here is the full code.

public class RestaurantAdapter extends RecyclerView.Adapter<RestaurantAdapter.myViewHolder> {
    List<Restaurants> datalist;


    public RestaurantAdapter(ArrayList<Restaurants> datalist) {
        this.datalist = datalist;

    }

    @NonNull
    @Override
    public myViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.single_restaurant, parent, false);
        return new myViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull myViewHolder holder, int position) {
        holder.restaurant_name.setText( datalist.get(position).getRestaurant_name() );
        holder.address.setText(datalist.get(position).getAddress());
        Picasso.get().load(datalist.get(position).getImage_url()).into(holder.place_image);
    }

    @Override
    public int getItemCount() {
        return datalist.size();
    }

    class myViewHolder extends RecyclerView.ViewHolder{

        TextView restaurant_name, address, select;
        ImageView place_image;

        public myViewHolder(@NonNull View itemView) {
            super(itemView);

            restaurant_name = itemView.findViewById(R.id.restaurant_name);
            address = itemView.findViewById(R.id.address);
            place_image = itemView.findViewById(R.id.place_image);
            select = itemView.findViewById(R.id.select);

            select.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                }
            });
        }
    }

}

Let’s see one by one. First of all, we declare “RecyclerView.Adapter<RestaurantAdapter.myViewHolder>” as extends. This means, we are calling “RecyclerView.Adapter” for here.

Then we declare an array List called “List<Restaurants> datalist;”. we used this to store firebase data.

  public RestaurantAdapter(ArrayList<Restaurants> datalist) {
        this.datalist = datalist;

  }

This is the constructor. “myViewHolder onCreateViewHolder” and “onBindViewHolder” methods are coming from when we extends the RecyclerView.Adapter<RestaurantAdapter.myViewHolder>.

 @NonNull
    @Override
    public myViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.single_restaurant, parent, false);
        return new myViewHolder(view);
    }

This method is use for connect the single xml file. As you can see we connect the single file using “View”.

    @Override
    public void onBindViewHolder(@NonNull myViewHolder holder, int position) {
        holder.restaurant_name.setText( datalist.get(position).getRestaurant_name() );
        holder.address.setText(datalist.get(position).getAddress());
        Picasso.get().load(datalist.get(position).getImage_url()).into(holder.place_image);
    }

In here, we declare the texts and images to that my holder. It means above “myViewHolder onCreateViewHolder” is like a holder. we assign our texts and images to that holder.

Finally, in the “myViewHolder” class we define our holder texts and images to our actual TextViews and ImagesViews.


Get back to code…

In our “AllRestaurantsActivity.java” file, we need to declare some variables. Like this.

private RecyclerView places_list;
private FirebaseFirestore db;
RestaurantAdapter adapter;
ArrayList<Restaurants> datalist;

After that inside the “onCreate()” method, you can declare those variables as well. Like this.

db = FirebaseFirestore.getInstance();
places_list = findViewById(R.id.places_list);
places_list.setLayoutManager(new LinearLayoutManager(this));
datalist = new ArrayList<>();
adapter = new RestaurantAdapter(datalist);
places_list.setAdapter(adapter);

After that, you can use this below code to get List view Items.

db.collection("Restaurants").get()
                .addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
                    @Override
                    public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
                        List<DocumentSnapshot> list = queryDocumentSnapshots.getDocuments();
                        for (DocumentSnapshot d:list){
                            Restaurants obj = d.toObject(Restaurants.class);
                            datalist.add(obj);
                        }

                        adapter.notifyDataSetChanged();
                    }
                });

In here, “Restaurants” means my collection name in the firebase. Replace with yours. Then run your application you can see you List view.


Thank you. Make sure to leave a comment.

If you are a newbie to Android. Follow and refer articles. Click below link to get started.

Other articles from different categories.

guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x