Reputation: 131
I have a list that is being used by two separate classes. I need this list to be defined in one of my onDataChange methods however, and this is giving me some issues. At the top of my class I have my list defined as this:
public List<String> openGames;
I have that there so my RecyclerView class can use it. I then initialize my list in an onDataChange method like this
public void updateUI(final ListCallback callBack) {
FCGames.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
numGames = (int) dataSnapshot.getChildrenCount();
openGames = new ArrayList<>();
.
.
.
Those dots are there just to say there is more code, but I don't think it is necessary for this problem.
In MyRecyclerViewer class, this list is being used and when the Activity opens it tries to get the size of the list like this:
@Override
public int getItemCount() {
return mData.size();
}
But since the list is not defined until some things in my app occur, like the onDataChange method being called upon, this throws me an error:
Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
I know the cause of this is because the list is not defined before the size of the list is taken.
So what I have done to try to get around this is adding a null list size check when it takes the list size, and that does get rid of the error, but it makes my entire RecyclerViewer not function at all
Are there any work around for this?
Upvotes: 0
Views: 1221
Reputation: 191728
You should do public List<String> openGames = new ArrayList<>();
initialization in the field.
And setup the RecyclerView adapter outside of the Firebase call as well.
Within the Firebase Callback, do not make a new list. Rather use openGames.clear()
to empty it out before adding new data, which will preserve the list instance that the RecyclerView is using.
With that, you must still call notify methods of the adapter let the UI know data has changed, which is what i assume you are missing if the RecyclerView "doesn't work"
If you want to receive data changes as they happen in Firebase, you're using the wrong method
... the
addListenerForSingleValueEvent()
method ... triggers once and then does not trigger again.
You'll need to use addValueEventListener
Upvotes: 2
Reputation: 89
You have to validate if your List is not null in order to get the size of it.
@Override
public int getItemCount() {
return mData != null ? mData.size() : 0;
}
Upvotes: 0