简体   繁体   中英

Android spinner not showing Firebase Realtime Database data?

I have been having some trouble for quite some time stuck on this. I am wanting to make a spinner in android studio and use a firebase database. But I can't seem to get the spinner to display any of the database's data in the spinner. I have tried to follow some similar questions but I just run into the same problems. Since I am new to Firebase I am unsure how to actually create the indexes to pull from it.

Here is my current code:

    FirebaseDatabase database = FirebaseDatabase.getInstance();
    DatabaseReference fDatabaseRoot = database.getReference("locations");


    fDatabaseRoot.child("buildings").addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            final List<String> buildings = new ArrayList<>();

            for (DataSnapshot buildingSnapshot: dataSnapshot.getChildren()) {
                String buildingName = buildingSnapshot.child("buildingName").getValue(String.class);
                buildings.add(buildingName);
            }

            Spinner buildingSpinner = findViewById(R.id.spinner);
            ArrayAdapter<String> buildingAdapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_spinner_item, buildings);
            buildingAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            buildingSpinner.setAdapter(buildingAdapter);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });`

Here is how my database is setup: Firebase Spinner Database

Here is the FirebaseFirestore implementation for SnapshotListener . You can check the type of change in data ( ADDED , MODIFIED , REMOVED ) by DocumentChange class. You can check out the example here: https://firebase.google.com/docs/firestore/query-data/listen#view_changes_between_snapshots

FirebaseFirestore db= FirebaseFirestore.getInstance();
db.collection("locations").document("buildings").addSnapshotListener(new EventListener<QuerySnapshot>() {
        @Override
        public void onEvent(@Nullable QuerySnapshot snapshots,
                            @Nullable FirebaseFirestoreException e){
             //your action here
        }
);

Ok so using the Realtime Database I had to switch the Read and Write rules to true, completely forgot to do that.

Remember kids always do your homework. :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM