firebase realtime database code example

Example 1: firebase realtime database correct architecture

With this nested design, iterating through the data becomes problematic. For example, listing the titles of chat conversations requires the entire chats tree, including all members and messages, to be downloaded to the client.

Flatten data structures
If the data is instead split into separate paths, also called denormalization, it can be efficiently downloaded in separate calls, as it is needed. Consider this flattened structure:

{
  // Chats contains only meta info about each conversation
  // stored under the chats's unique ID
  "chats": {
    "one": {
      "title": "Historical Tech Pioneers",
      "lastMessage": "ghopper: Relay malfunction found. Cause: moth.",
      "timestamp": 1459361875666
    },
    "two": { ... },
    "three": { ... }
  },

  // Conversation members are easily accessible
  // and stored by chat conversation ID
  "members": {
    // we'll talk about indices like this below
    "one": {
      "ghopper": true,
      "alovelace": true,
      "eclarke": true
    },
    "two": { ... },
    "three": { ... }
  },

  // Messages are separate from data we may want to iterate quickly
  // but still easily paginated and queried, and organized by chat
  // conversation ID
  "messages": {
    "one": {
      "m1": {
        "name": "eclarke",
        "message": "The relay seems to be malfunctioning.",
        "timestamp": 1459361875337
      },
      "m2": { ... },
      "m3": { ... }
    },
    "two": { ... },
    "three": { ... }
  }
}

Example 2: firebase realtime database store array

The Firebase Database doesn't store arrays. It stores dictionaries/associate arrays. So the closest you can get is:

attendees: {
  0: "Bill Gates",
  1: "Larry Page",
  2: "James Tamplin"
}

Example 3: firebase realtime database read data

If you want to get a specific data using a phone number then you can use a Query like this

DatabaseReference database = FirebaseDatabase.getInstance().getReference();
DatabaseReference ref = database.child("profiles");

Query phoneQuery = ref.orderByChild(phoneNo).equalTo("+923336091371");
phoneQuery.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot singleSnapshot : dataSnapshot.getChildren()){
           user = singleSnapshot.getValue(User.class); 
        }
    }
    @Override
    public void onCancelled(DatabaseError databaseError) {
        Log.e(TAG, "onCancelled", databaseError.toException());
    }
});
I think this is the best method.

Example 4: firebase realtime database rules

10 Firebase Realtime Database Rule Templates

https://medium.com/@juliomacr/10-firebase-realtime-database-rule-templates-d4894a118a98

Tags:

Misc Example