I have an ArrayList defined in my Android app for my MainActivity.
I've been running into difficulties trying to understand how to retrieve the interests of the user and add it to my array list.
Here's how my Firebase data is set up:
I understand that I must load the data asynchronously, but I'm confused as to how I should go about that.
here's my code for trying to add to the ArrayList:
public class MainActivity extends AppCompatActivity {
private DatabaseReference eventDatabase;
private DatabaseReference usersDatabase;
private FirebaseAuth mAuth;
private String currentUserID;
private ArrayList<String> userInterests = new ArrayList<String>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
eventDatabase = FirebaseDatabase.getInstance().getReference().child("Event");
usersDatabase = FirebaseDatabase.getInstance().getReference().child("Users");
mAuth = FirebaseAuth.getInstance();
currentUserID = mAuth.getCurrentUser().getUid();
usersDatabase.child(currentUserID).child("interests").addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot postSnapshot : dataSnapshot.getChildren()){
boolean isInterested = (Boolean)postSnapshot.getValue();
if (isInterested){
userInterests.add(postSnapshot.getKey());
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
System.out.println(userInterests);
I want the ArrayList to consist of the user's interests, if it is false in the database, it won't be added to the list. Example: [COMPETITION, CULTURE, EDUCATION...etc]
When it returns the list in the console, I just see an empty list -- "[]"
This is what you want.
usersDatabase.child(currentUserID).child("interests").addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot postSnapshot : dataSnapshot.getChildren()){
boolean isInterested = (Boolean)postSnapshot.getValue();
if (isInterested) {
userInterests.add(postSnapshot.getKey());
}
}
If you are using firebase with Android, then i would suggest you to use firebase-ui components, Firebase UI, it will be very helpful
Or Instead of trying to cast in Boolean, try with String and the convert it to Boolean
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With