0

trying to get my Recyclerview to display data from firestore but it crashes my app and I have no idea why. Gone through multiple tutorials but to no avail, I followed the tutorial step by step and not too sure why the tutorials can work but mine does not. Any help will be appreciated.

build gradle

plugins {
    id 'com.android.application'
    id 'com.google.gms.google-services'
}

android {
    compileSdkVersion 30
    buildToolsVersion "30.0.3"

    defaultConfig {
        applicationId "com.example.orbital"
        minSdkVersion 21
        targetSdkVersion 30
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner'
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

dependencies {
    implementation 'com.google.android.material:material:1.3.0'
    implementation 'androidx.appcompat:appcompat:1.3.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
    implementation 'androidx.cardview:cardview:1.0.0'
    implementation 'com.google.firebase:firebase-auth:21.0.1'
    implementation 'com.google.firebase:firebase-firestore:23.0.1'
    implementation 'com.google.firebase:firebase-database:20.0.0'
    implementation 'com.google.firebase:firebase-storage:20.0.0'
    implementation 'com.airbnb.android:lottie:3.4.1'
    implementation 'com.firebaseui:firebase-ui-firestore:7.2.0'
    implementation 'androidx.recyclerview:recyclerview:1.0.0'

    testImplementation 'junit:junit:4.+'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    androidTestImplementation 'androidx.test.ext:junit:1.1.2'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'


}

Chat Fragment which retrieves data from firestore

package com.example.orbital;

import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

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


import com.firebase.ui.firestore.FirestoreRecyclerAdapter;
import com.firebase.ui.firestore.FirestoreRecyclerOptions;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.FirebaseFirestoreException;
import com.google.firebase.firestore.Query;


public class chatFragment extends Fragment {

    private FirebaseFirestore firebaseFirestore;
    LinearLayoutManager linearLayoutManager;
    private FirebaseAuth firebaseAuth;

    FirestoreRecyclerAdapter<UserModel, NoteViewHolder> chatAdapter;
    RecyclerView mRecyclerView;




    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable  ViewGroup container, @Nullable  Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.chatfragment,container,false);

        firebaseAuth = FirebaseAuth.getInstance();
        firebaseFirestore = FirebaseFirestore.getInstance();
        mRecyclerView = v.findViewById(R.id.recyclerView);

        Query query = firebaseFirestore.collection("Users");
        FirestoreRecyclerOptions<UserModel> allusername = new FirestoreRecyclerOptions.Builder<UserModel>()
                .setQuery(query,UserModel.class)
                .build();

        chatAdapter = new FirestoreRecyclerAdapter<UserModel, NoteViewHolder>(allusername) {
            @Override
            public void onError(FirebaseFirestoreException e) {
                // Called when there is an error getting a query snapshot. You may want to update
                // your UI to display an error message to the user.
                // ...


            }

            @Override
            protected void onBindViewHolder(@NonNull NoteViewHolder noteViewHolder, int i, @NonNull UserModel userModel) {



                noteViewHolder.particularusername.setText(userModel.getName());
                //fetch image
                /*if(UserModel.getStatus().equals("Online"))
                {
                    holder.statusofuser.setText(model.getStatus());
                    holder.statusofuser.setTextColor(Color.GREEN);
                }
                else
                {
                    holder.statusofuser.setText(model.getStatus());
                }*/

                noteViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Toast.makeText(getActivity(),"Chat Clicked",Toast.LENGTH_SHORT).show();
                    }
                });

            }

            @NonNull
            @Override
            public NoteViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

                View view=LayoutInflater.from(parent.getContext()).inflate(R.layout.chatview_layout,parent,false);
                return new NoteViewHolder(view);
            }
        };

        //mRecyclerView.setHasFixedSize(true);
        linearLayoutManager=new LinearLayoutManager(getContext());
        linearLayoutManager.setOrientation(RecyclerView.VERTICAL);
        mRecyclerView.setLayoutManager(linearLayoutManager);
        mRecyclerView.setAdapter(chatAdapter);


       return v;









    }


    public class NoteViewHolder extends RecyclerView.ViewHolder
    {
        //suppose to add on image
        private TextView particularusername;
        //private TextView statusofuser;

        public NoteViewHolder(@NonNull View itemView) {
            super(itemView);
            particularusername=itemView.findViewById(R.id.nameofuser);
            //statusofuser=itemView.findViewById(R.id.statusofuser);




        }

    }

    @Override
    public void onStart() {
        super.onStart();
        chatAdapter.startListening();
    }

    @Override
    public void onStop() {
        super.onStop();

        chatAdapter.stopListening();
    }


}

chatviewlayout (XML)

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/white">


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

    </androidx.recyclerview.widget.RecyclerView>



</RelativeLayout>

chatfragment (XML)

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="90dp"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:background="@color/smokyWhite">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:paddingTop="10dp"
        android:paddingBottom="-5dp">




        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Name Display Here"
            android:layout_toRightOf="@id/cardviewofuser"
            android:layout_marginTop="15dp"
            android:layout_marginLeft="15dp"
            android:textSize="20sp"
            android:id="@+id/nameofuser"
            android:textStyle="bold"
            android:textColor="#0b0b0b">

        </TextView>


        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Display Status here"
            android:textSize="12sp"
            android:layout_marginLeft="15dp"
            android:layout_marginTop="3dp"
            android:layout_toRightOf="@id/cardviewofuser"
            android:id="@+id/statusofuser"
            android:layout_below="@id/nameofuser"
            android:textColor="#6a6a6a">

        </TextView>




        <androidx.cardview.widget.CardView
            android:layout_width="55dp"
            android:layout_height="55dp"
            android:layout_marginBottom="20dp"
            android:layout_alignParentLeft="true"
            android:layout_centerVertical="true"

            android:id="@+id/cardviewofuser"
            app:cardCornerRadius="55dp"
            >


            <ImageView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:src="@drawable/ic_launcher_background"
                android:id="@+id/imageviewofuser"
                android:scaleType="centerCrop">

            </ImageView>



        </androidx.cardview.widget.CardView>

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="0.1dp"
            android:layout_marginLeft="10dp"
            android:backgroundTint="#a6a6a6"
            android:background="#a6a6a6"
            android:layout_below="@id/cardviewofuser"
            android:layout_toRightOf="@id/cardviewofuser"
            android:layout_marginTop="-5dp" />





    </RelativeLayout>






</RelativeLayout>

UserModel

package com.example.orbital;

public class UserModel {
   String Name, Contact, Address, Gender;

    public UserModel(String Name, String Contact, String Address, String Gender) {
        this.Name = Name;
        this.Contact = Contact;
        this.Address = Address;
        this.Gender = Gender;
    }

    public UserModel() {
    }

    public String getName() {
        return Name;
    }

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

    public String getContact() {
        return Contact;
    }

    public void setContact(String Contact) {
        this.Contact = Contact;
    }

    public String getAddress() {
        return Address;
    }

    public void setAddress(String Address) {
        this.Address = Address;
    }

    public String getGender() {
        return Gender;
    }

    public void setGender(String Gender) {
        this.Gender = Gender;
    }
}

  • Can you post the stack trace on crashing? – codebod Jul 06 '21 at 18:19
  • what is that? cus when i build and run is fine until i went into the recyclerview part the app jus stop working – Falicia Ong Jul 06 '21 at 19:16
  • @FaliciaOng When the app crashes, the IDE generates an error log (E) , i.e. a stack trace. Try learning about stack trace : https://stackoverflow.com/questions/3988788/what-is-a-stack-trace-and-how-can-i-use-it-to-debug-my-application-errors – private static Jul 06 '21 at 21:00
  • 2021-07-07 13:13:09.086 22708-22708/com.example.orbital E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.orbital, PID: 22708 java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.recyclerview.widget.RecyclerView.setHasFixedSize(boolean)' on a null object reference at com.example.orbital.chatFragment.onCreateView(chatFragment.java:98) – Falicia Ong Jul 07 '21 at 05:14
  • this is what i got – Falicia Ong Jul 07 '21 at 05:14

1 Answers1

0

The problem in your code lies in the fact that you're using a different RecyclerView than the one you have in your layout file. In your chatfragment.XML file you have:

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

While in your code your are using:

mRecyclerView = v.findViewById(R.id.recyclerView);

See the difference? In the layout file, the id is set to recyclerview all letters lower case, while in the code is recyclerView, with W capital, hence that NullPointerException at this line:

mRecyclerView.setHasFixedSize(true);

To solve this, simply chnage the above line of code to:

mRecyclerView = v.findViewById(R.id.recyclerview);
Alex Mamo
  • 130,605
  • 17
  • 163
  • 193