androidfirebasefirebase-realtime-database

Store user data and allow users to add data from a public list


I'm making an app which allows users to get weatherdata from several sources at specific locations.

The problem I am facing is that pr. now when a user uses my app he/she will see all the location objects in the firebase database. (I'm planning to add login via firebase, login will be needed for this feature)

How can I easily store the users chosen locations in the app?

For example : I would like to have a List of Locations Y, Z, X and so on. (Each with their own set of data, updated by the users)

User A wants to see Location Y and Z, User B wants to see Location Y and X

How should I store a link to the locations that user A wants to see? and then be able to show those locations in a RecycleView.

Preferably I would also like that if user C joins he can add his own location or choose from a list of locations.


Solution

  • Since you are already using Firebase Database, store the User's preferenes on that. You can create a separate node for users, and store each user using the UID as the key (not necessary though) and the preferences or any other detail as the value. Something like this

    "root":{
      "users":{
        "UID1":{
          "locations":{
            "location1":true
            "location2":true
          }
        }
        "UID2":{
          "locations":{
            "location2":true
            "location3":true
          }
        }
        "UID3":{
          "locations":{
            "location4":true
            "location5":true
          }
        }
      }
    }
    

    Then you can get a reference to each user using

    FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
    DatabaseReference userRef = FirebaseDatabase.getInstance()
                       .getReference("users/" + user.getUid() + "/locations");
    

    You can pass this reference to a FirebaseRecyclerAdapter to get a populate a RecyclerView. However, if the data stored in each list item is small, say just a name and maybe a picture_url, then just store under each user. This may duplicate data but gets the data quickly, which is what a realtime database is supposed to do.