Firebase/Firestore Spinner hack

2019-08-26 08:25发布

I'm trying to understand the connection between Firebase/Firestore and Android. I want a simple Spinner in my Android-app and got this not-so-logical-hack.

I got a Field, that is a String, that I want to loop through and put the value into an ArrayList. This ArrayList will then be set into a Spinner via an ArrayAdapter.

final ArrayList<String> list = new ArrayList<String>();
dbFoodName.collection("measures")
        .get()
        .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
            @Override
            public void onComplete(@NonNull Task<QuerySnapshot> task) {
                if (task.isSuccessful()) {
                    for (DocumentSnapshot document : task.getResult()) {
                        list.add(String.valueOf(document.getId()));
                    }
                } else {
                    Log.i("RunLog: ", "Error getting documents: ", task.getException());
                }
            }
        });

The content in the Spinner works. It looks just right. But when I choose a value, the app crashes.

Unless.

When I add a coded value at top:

list.add("Choose measurement"); 

Like this:

final ArrayList<String> list = new ArrayList<String>();
list.add("Choose measurement");
dbFoodName.collection("measures")
        .get()
        .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
            @Override
            public void onComplete(@NonNull Task<QuerySnapshot> task) {
                if (task.isSuccessful()) {
                    for (DocumentSnapshot document : task.getResult()) {
                        list.add(String.valueOf(document.getId()));
                    }
                } else {
                    Log.i("RunLog: ", "Error getting documents: ", task.getException());
                }
            }
        });

Then it all works just fine. AND I got an bonus of a nice headline. enter image description here

But why does it work? Is there anyone out there who can explain?

EDIT: I got a nullPointerException:

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

I found this great link about the topic: What is a NullPointerException, and how do I fix it?

0条回答
登录 后发表回答