Reputation: 11
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
Upvotes: 0
Views: 296
Reputation: 11
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. :)
Upvotes: 0
Reputation: 1121
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
}
);
Upvotes: 1