'Trying to show Recycler View in fragment of Navigation Drawer

I've created a Navigation Drawer in Android Studio, using the default Navigation Drawer Activity (Android Studio Bublebee 2021.1.1.1).

And I put a Recycler view in the fragment layout. After that I tried to get data from Firebase database, and put it in Recycler view, using Firebase UI. And since the default code is different, than in many tutorials and etc. I tried to find out how to do it myself. I did it in Fragment java file, from ui package folder.

Everything is working, no errors, no crashes, but the page is empty.

My Navigation Drawer Activity java file:

package com.example.project;

import android.os.Bundle;
import android.view.View;
import android.view.Menu;
import android.widget.TextView;

import com.example.project.classes.User;
import com.example.project.classes.product;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.navigation.NavigationView;

import androidx.annotation.NonNull;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.project.databinding.ActivityStoreBinding;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

public class Store extends AppCompatActivity {

    private AppBarConfiguration mAppBarConfiguration;
    private ActivityStoreBinding binding;

    private FirebaseUser user;
    private DatabaseReference dbReference;
    private String uID;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = ActivityStoreBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        setSupportActionBar(binding.appBarStore.toolbar);
        /*binding.appBarStore.fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });*/

        DrawerLayout drawer = binding.drawerLayout;
        NavigationView navigationView = binding.navView;

        View headerView = navigationView.getHeaderView(0);
        final TextView StoreNavUsername = headerView.findViewById(R.id.store_nav_header_username);

        user = FirebaseAuth.getInstance().getCurrentUser();
        dbReference = FirebaseDatabase.getInstance().getReference("Users");
        uID = user.getUid();

        dbReference.child(uID).addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                User userData = snapshot.getValue(User.class);

                if (userData != null){
                    String usernameData = userData.username;


                    StoreNavUsername.setText(usernameData);
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {

            }
        });


        // Passing each menu ID as a set of Ids because each
        // menu should be considered as top level destinations.
        mAppBarConfiguration = new AppBarConfiguration.Builder(
                R.id.nav_home, R.id.nav_cart, R.id.nav_orders, R.id.nav_categories)
                .setOpenableLayout(drawer)
                .build();
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_store);
        NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
        NavigationUI.setupWithNavController(navigationView, navController);

        // product


    }



    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.store, menu);
        return true;
    }

    @Override
    public boolean onSupportNavigateUp() {
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_store);
        return NavigationUI.navigateUp(navController, mAppBarConfiguration)
                || super.onSupportNavigateUp();
    }
}

Main XML file of the activity:

<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout 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:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="start">

    <include
        android:id="@+id/app_bar_store"
        layout="@layout/app_bar_store"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <com.google.android.material.navigation.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header_store"
        app:menu="@menu/activity_main_drawer" />
</androidx.drawerlayout.widget.DrawerLayout>

The fragment layout of the page with the Recycler View:

<?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=".ui.home.HomeFragment">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/store_recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>

The class of the item, needed to put into the Recycler View:

package com.example.project.classes;

public class product {
    private String name, price, producer, imageurl, category, productid, sellerid;

    public product() {
    }

    public product(String name, String price, String producer, String imageurl, String category, String productid, String sellerid) {
        this.name = name;
        this.price = price;
        this.producer = producer;
        this.imageurl = imageurl;
        this.category = category;
        this.productid = productid;
        this.sellerid = sellerid;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPrice() {
        return price;
    }

    public void setPrice(String price) {
        this.price = price;
    }

    public String getProducer() {
        return producer;
    }

    public void setProducer(String producer) {
        this.producer = producer;
    }

    public String getImageurl() {
        return imageurl;
    }

    public void setImageurl(String imageurl) {
        this.imageurl = imageurl;
    }

    public String getCategory() {
        return category;
    }

    public void setCategory(String category) {
        this.category = category;
    }

    public String getProductid() {
        return productid;
    }

    public void setProductid(String productid) {
        this.productid = productid;
    }

    public String getSellerid() {
        return sellerid;
    }

    public void setSellerid(String sellerid) {
        this.sellerid = sellerid;
    }
}

The layout of the single item, to put into Recycler View:

<?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"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:scrollbars="vertical">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="15dp"
        android:layout_marginBottom="5dp"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp">

        <ImageView
            android:id="@+id/product_image"
            android:layout_width="wrap_content"
            android:layout_height="200dp"/>

        <TextView
            android:id="@+id/product_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/product_image"
            android:layout_marginTop="5dp"
            android:textSize="20dp"
            android:textAlignment="center"
            android:textColor="@color/black"
            android:textStyle="bold"
            android:text="@string/product_name"
            />

        <TextView
            android:id="@+id/product_price"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/product_name"
            android:layout_marginTop="5dp"
            android:textSize="18dp"
            android:textAlignment="center"
            android:textColor="@color/black"
            android:textStyle="bold"
            android:text="@string/product_price"
            />

    </RelativeLayout>

</androidx.cardview.widget.CardView>

The Adapter:

package com.example.project;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.project.classes.product;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;

public class productAdapter extends FirebaseRecyclerAdapter<
        product, productAdapter.productViewholder> {

    public productAdapter(
            @NonNull FirebaseRecyclerOptions<product> options)
    {
        super(options);
    }

    @Override
    protected void onBindViewHolder(@NonNull productAdapter.productViewholder holder, int position, @NonNull product model) {
        holder.name.setText(model.getName());
        holder.price.setText(model.getPrice());
    }

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

    class productViewholder extends RecyclerView.ViewHolder {
        TextView name, price;

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

            name = itemView.findViewById(R.id.product_name);
            price = itemView.findViewById(R.id.product_price);
        }
    }
}

The Java file of the page fragment:

package com.example.project.ui.home;

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.project.classes.product;
import com.example.project.databinding.FragmentHomeBinding;
import com.example.project.productAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

public class HomeFragment extends Fragment {

    private FragmentHomeBinding binding;

    productAdapter adapter;

    DatabaseReference productDbReference;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        HomeViewModel homeViewModel =
                new ViewModelProvider(this).get(HomeViewModel.class);

        binding = FragmentHomeBinding.inflate(inflater, container, false);
        View root = binding.getRoot();

        /*final TextView textView = binding.textHome;
        homeViewModel.getText().observe(getViewLifecycleOwner(), textView::setText);*/

        return root;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        productDbReference = FirebaseDatabase.getInstance("https://health-mentor-12edb-default-rtdb.europe-west1.firebasedatabase.app/").getReference("Products");

        final RecyclerView StoreRecyclerView = binding.storeRecyclerView;
        StoreRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

        FirebaseRecyclerOptions<product> options = new FirebaseRecyclerOptions.Builder<product>()
                .setQuery(productDbReference, product.class)
                .build();

        adapter = new productAdapter(options);

        StoreRecyclerView.setAdapter(adapter);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }
}

I'm trying to put just the name and price, without the image, for now. But the page is just empty. I feel like, I got the data from database, but just didn't write, how it should put the data into the Recycler View.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source