Search code examples
androidfirebasefirebase-realtime-databasefirebaseui

Firebase UI - How to synchronize a ListView with complex data


I am writing an app for Android, in which there are events and users.

An event has many users, and an user has many events.

So I structured my database like this:

- events
    - <event_id>
        - ...
        - users
            - <user_id1>
            - <user_id2>
            - ...
- users
   - <user_id1>
        - <user_detail1>
        - <user_detail2>
        - ...
   - <user_id2>
        - <user_detail1>
        - <user_detail2>
        - ...

Now, I have an Activity with a ListView, and I successfully managed to show a list of all the events with FirebaseUI using a FirebaseListAdapter.

I have a second Activity in which I want to show event details, with another ListView showing the list of users for that event.

My question is: if I use a FirebaseListAdapter I can only show the user_id, how can I retrieve user details an show them in the ListView?

EDIT

To be more precise, I want the list of the users of a specific event to be linked to a ListView. I want to use a FirebaseListAdapter for that, so my code looks like this at the moment:

fireAdapter = new FirebaseListAdapter<String>(
                this,
                String.class,
                android.R.layout.simple_list_item_1,
                mRootRef.child("events").child("users") //here I have all user_id that I want to retrieve details for
        ) {
            @Override
            protected void populateView(View v, String model, int position) {
                //the string "model" will now have a user_id
                TextView userName = (TextView)v.findViewById(android.R.id.text1); //I want to populate this field

                String usernameString;

                //How do I get to retrieve the username from user_id into this variable?

                userName.setText(usernameString);
            }
        };

Solution

  • To get the user details, you can attach a listener to the user-id. The listener will be automatically called onChildAdded() or onChildChanged() methods. For your case, since you want the information only for the first time, you can retrieve all values with the snapshot that is returned in the function with the method dataSnapshot.getChildren() and to get the exact values use the function dataSnapShot.child('blah-blah').value()

    For the complete reference check out the Link.

    Your code might look something like this

    private DatabaseReference mDatabase;
    mDatabase = FirebaseDatabase.getInstance().getReference();
    mDatabase.child('users').child('user_id1').setChildListener(ListenerName);