David Azar
David Azar

Reputation: 361

Flattening data in Firebase to reflect model in Android app

I'm trying out Firebase as my backend for a prototype app im creating.

As a mockup, im creating a fake game. The data is pretty simple:

Im currently structuring my data as follows:

levels:{
   easy:{ 
    easy-level-1-id:{
        total-mini-games:10,
        easy-level-1-id:String
     }
   },
   medium:{....},
   hard:{.....}
}
user-progress:{
   user-id:{
      levels:{
        easy-level-1-id:{
           user-completed:int
        }
       },
       mini-games:{
          mini-game-1:true
          mini-game-2:true
       }
   }
}

I have to access many places in order to check if a game has been completed, or how many games have been completed per level. All of this is in order to avoid nesting data, as the docs recommend.

Is it better to do it like this or is it better to store every available level under every user id in order to do less calls, but having much more repeated data ?

I know about the FirebaseRecyclerViewAdapter class provided by the Firebase team, but because it takes a DatabaseReference object as an argument for knowing where the data, it doesn't really apply here, because i fetch data from different structures when building the model for the lists.

mRef1.child(some_child).addValueEventListener(new ValueEventListener(){

     @Override
     public void onDataChange(DataSnapshot dataSnapshot){

          final Model model = dataSnapshot.getValue(Model.class);
          mRef2.child(some_other_child).addValueEventListener(new ValueEventListener(){

           @Override
           public void onDataChange(DataSnapshot dataSnapshot){

              //add more data into the model class
            .....
           }

           @Override
           public void onCancelled(DatabaseError databaseError){}


  });

  @Override
  public void onCancelled(DatabaseError databaseError){}

});

Any pointers as to how to work with more structured data ?

Upvotes: 2

Views: 329

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598728

FirebaseUI includes support for working with indexed data. It can load linked data from an index, such as in your mini-games node.

In your example that could work as:

keyRef = ref.child("user-progress").child(currentUser.getUid()).child("mini-games");
dataRef = ref.child("mini-games");
adapter = new FirebaseIndexRecyclerAdapter<Chat, MiniGameHolder>(
    MiniGame.class,
    android.R.layout.two_line_list_item,
    MiniGameHolder.class,
    keyRef, // The Firebase location containing the list of keys to be found in dataRef.
    dataRef) //The Firebase location to watch for data changes. Each key key found at keyRef's location represents a list item in the RecyclerView.

Upvotes: 4

Related Questions