Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make an ArrayList from Firebase Data

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:

FirebaseData

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 -- "[]"

like image 263
Mukai Selekwa Avatar asked Feb 05 '23 10:02

Mukai Selekwa


2 Answers

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());
        }
   }
like image 112
Saurabh Padwekar Avatar answered Feb 08 '23 15:02

Saurabh Padwekar


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

like image 29
Hardik Senghani Avatar answered Feb 08 '23 15:02

Hardik Senghani