Wazy
Wazy

Reputation: 494

Firestore iterating though a document to find null fields

I am implementing a feature into my app that allows users to view there ongoing discussions about a post. I want the user to only be able to have 5 active discussions.(When the discussion is being created i want to be able to check the users document to see if they have exceeded the maximum allowed discussions This is what i am working with

currentDocument.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {

    if (task.isSuccessful()) {
        DocumentSnapshot document = task.getResult();
            if (document.exists()) {

                if (document.get("PostID 1") == null) {

                    //No discussion post in this field

                } if (document.get("PostID 2") == null){

                   //No discussion post in this field

                }
            }
        }
    }
});

for this to work i would have to create an if statement for every document field this seems like poor programming practice to me. Is there a better way to go about this or should i tackle the problem a different way all suggestions welcome!

document:

enter image description here

Update:

Getting close to my solution but still stuck

I get my document with

currentDocument.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {

}

I get the document data and store it

if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();

Map test = document.getData(); }

And i itterate through it

for (Object entry : test.entrySet() ){

Log.w(TAG, "Key = " + entry.toString()); }

up to this point i am good where i am now stuck is i want to have an if statement to determine if the value is null or not this is what i am working with

for (Object entry : test.entrySet() ){

        Log.w(TAG, "Key = " + entry.toString());

    if (entry.toString().contains(null)){

        Log.w(TAG, entry.toString() + " is equal to null");

    }

}

it throws the error

java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.String java.lang.CharSequence.toString()' on a null object reference

I believe that I am not correctly reading the data in the if statement

Upvotes: 0

Views: 77

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317692

When you have a DocumentSnapshot, you can call getData() on it to get a Map of all the fields and values. Then you just iterate it as you would any other Java Map using its entrySet().

Upvotes: 2

Related Questions