Click here to Skip to main content
14,325,064 members
Rate this:
Please Sign up or sign in to vote.
See more:
So, I have this Pizza Ordering App with a Firebase Database where I want to populate a RecyclerView with data from the database.

Here is the database:


{
  "category" : {
    "01" : {
      "image" : "https://www.carusopizza.cz/185-large_default/prosciutto.jpg",
      "name" : "Pizza Prosciuto"
    },
    "02" : {
      "image" : "http://urgentpizza.ro/blog/wp-content/uploads/2014/06/pizza-diavola-urgentpizza1.jpg",
      "name" : "Pizza Diavolo"
    },
    "03" : {
      "image" : "https://www.carusopizza.cz/388/1047.jpg",
      "name" : "Pizza Funghi"
    }
  },
  "user" : {
    "12345" : {
      "name" : "Tiganu",
      "password" : "1234"
    }
  }
}


LoadMenu() Code (Recycler View)

private void LoadMenu(){
        Query query =  FirebaseDatabase.getInstance().getReference().child("category");
        FirebaseRecyclerOptions<Category> options = new FirebaseRecyclerOptions.Builder<Category>()
                .setQuery(query, new SnapshotParser<Category>() {
                    @NonNull
                    @Override
                    public Category parseSnapshot(@NonNull DataSnapshot snapshot) {
                        return new Category(snapshot.child("image").getValue().toString(), snapshot.child("name").getValue().toString());
                    }
                }).build();
        adapter = new FirebaseRecyclerAdapter<Category, MenuViewHolder>(options) {
            @Override
            protected void onBindViewHolder(@NonNull MenuViewHolder holder, int position, @NonNull Category model) {
                holder.menuName.setText(model.getName());
                Picasso.with(getBaseContext()).load(model.getImage()).into(holder.imageView);
                final Category clickItem = model;
                holder.setItemClickListener(new ItemClickListener() {
                    @Override
                    public void onClick(View view, int position, boolean isLongClick) {
                        Toast.makeText(HomeActivity.this, "" + clickItem.getName(), Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @NonNull
            @Override
            public MenuViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
                View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.activity_home, viewGroup, false);
                return new MenuViewHolder(view);
            }
        };
        recyclerView.setAdapter(adapter);
    }


Category class

package com.example.pizzaapp;

public class Category {
    private String image;
    private String name;
    public Category(){

    }
    public Category(String image, String name){
        this.image = image;
        this.name = name;
    }
    public String getName(){
        return name;
    }
    public String getImage(){
        return image;
    }
    public void setName(String name){
        this.name = name;
    }
    public void setImage(String image){
        this.image = image;
    }
}



MenuViewHolder Class

package com.example.pizzaapp;

import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

public class MenuViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
    public TextView menuName;
    public ImageView imageView;
    private ItemClickListener itemClickListener;
    public MenuViewHolder(View itemView){
        super(itemView);
        menuName = (TextView)itemView.findViewById(R.id.menu_name);
        imageView = (ImageView)itemView.findViewById(R.id.menu_image);
        itemView.setOnClickListener(this);
    }
    public void setItemClickListener(ItemClickListener itemClickListener){
        this.itemClickListener = itemClickListener;
    }
    @Override
    public void onClick(View view){
        itemClickListener.onClick(view, getAdapterPosition(), false);
    }
    public TextView getMenuName(){
        return menuName;
    }
    public ImageView getImageView(){
        return imageView;
    }
    public void setMenuName(TextView view){
        menuName = view;
    }
    public void setImageView(ImageView view){
        imageView = view;
    }
}


The problem is I am keep getting this error

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
        at com.example.pizzaapp.HomeActivity$2.onBindViewHolder(HomeActivity.java:58)
        at com.example.pizzaapp.HomeActivity$2.onBindViewHolder(HomeActivity.java:55)



in the LoadMenu() function and I don't know why The data from the user root is read correctly and the data from category is not. I think it is a problem with the query.

Line 55:

adapter = new FirebaseRecyclerAdapter<Category, MenuViewHolder>(options) {


Line 58:

holder.menuName.setText(model.getName());


Also ContentHome.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context=".HomeActivity"
    tools:showIn="@layout/app_bar_home">
    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_menu"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scrollbars="vertical">

    </android.support.v7.widget.RecyclerView>
</android.support.constraint.ConstraintLayout>


What I have tried:

I've tried to search on the internet and it seems my database is returning a null value and I don't understand why because my user database is working correctly
Posted
Updated 9-May-19 12:06pm
Rate this:
Please Sign up or sign in to vote.

Solution 1

Quote:
it seems my database is returning a null value and I don't understand why because my user database is working correctly

Don't guess, make sure instead, use the debugger and check variables and return values, you will see exactly when there is a null return value.
We can(t do this checking because we don't have the database.

Your code do not behave the way you expect, or you don't understand why !

There is an almost universal solution: Run your code on debugger step by step, inspect variables.
The debugger is here to show you what your code is doing and your task is to compare with what it should do.
There is no magic in the debugger, it don't know what your code is supposed to do, it don't find bugs, it just help you to by showing you what is going on. When the code don't do what is expected, you are close to a bug.
To see what your code is doing: Just set a breakpoint and see your code performing, the debugger allow you to execute lines 1 by 1 and to inspect variables as it execute.

Debugger - Wikipedia, the free encyclopedia[^]

Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]
Basic Debugging with Visual Studio 2010 - YouTube[^]

http://docs.oracle.com/javase/7/docs/technotes/tools/windows/jdb.html[^]
https://www.jetbrains.com/idea/help/debugging-your-first-java-application.html[^]

The debugger is here to only show you what your code is doing and your task is to compare with what it should do.
   
Rate this:
Please Sign up or sign in to vote.

Solution 2

The error message itself tells the complete solution for this problem of yours.
holder.menuName.setText(model.getName());
The menuName field of your view holder is null, perhaps you forgot to set it to an instance, or maybe you set it to another null variable, either way, the field is null thus you cannot call the setText(String) function on it.

There is no other solution to this problem, other than checking your resource file and verifying that you are using the correct ID for the view. Also verify that the layout has been inflated and that your list has the views that you are trying to check. One more thing, check here,
public MenuViewHolder(View itemView){
    super(itemView);
    menuName = (TextView)itemView.findViewById(R.id.menu_name);
    imageView = (ImageView)itemView.findViewById(R.id.menu_image);
    itemView.setOnClickListener(this);
}

Apply a normal if...else block, or a debugger here to see what is being passed as the itemView, because it might be that it is not container the R.id.menu_name; I doubt the same for imageView too! Also, looking at your resource file, where exactly is the resource with the ID menu_name?
(TextView)itemView.findViewById(R.id.menu_name);
Also try to share the layout file where all this is setup. Maybe the error is somewhere there. This is the major reason why you are seeing this bug, as this element does not exist in the view hierarchy.

Create a List with RecyclerView  |  Android Developers[^]
   
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100