Skip to main content

Firebase

Basic Reading Material from Source
https://firebase.google.com/docs/database/android/start/

Location of Data:

Reference represents a specific location in your Database.

You can reference the root or child location in your Database by calling firebase.database().ref()or firebase.database().ref("child/path").

Methods: 

1.child (path)
Gets a Reference for the location at the specified relative path.
The relative path can either be a simple child name (for example, "ada") or a deeper slash-separated path (for example, "ada/name/first").
returns non-null firebase.database.Reference, a child location
https://firebase.google.com/docs/reference/node/firebase.database.Reference

2. Push()

Generates a new child location using a unique key and returns its Reference
At the client side by chronological order. Server try to compensate by sending realtime to client before push. However, correction will only take effect if client has connect to Firebase. Hence the solution is to use ServerValue.TIMESTAMP .

https://firebase.googleblog.com/2015/02/the-2120-ways-to-ensure-unique_68.html

Write Data:
setvalue()
FirebaseDatabase database = FirebaseDatabase.getInstance().getReference("message").setValue("Hello, World!");


Update Data in Realtime:

addValueEventListener (2 methods, onDataChange and onCancelled).
From onDataChange, use dataSnapshot.getValue.
myRef.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        String value = dataSnapshot.getValue(String.class);
    }

    @Override
    public void onCancelled(DatabaseError error) {
        Log.w(TAG, "Failed to read value.", error.toException());
    }
});

How to save Data? (Check if input is not null, using push().getkey() to save to unique identifier)

From Video, data structure should be kept flat. To do so, 2 tables can be linked by the userid. Hence, when adding UserInformation, ID is included.

    String name = ename.getText().toString();
    String add = eaddress.getText().toString();

    if(!TextUtils.isEmpty(name))
    {
        String id = myRef.push().getKey();

        UserInformation userInformation = new UserInformation(name,add,id);
        myRef.child(id).setValue(userInformation);
        Toast.makeText(this,"User Added",Toast.LENGTH_LONG).show();
    }

    else{
        Toast.makeText(this,"Add a name",Toast.LENGTH_LONG).show();
    }

TextUtilis (class)

isEmpty():Returns true if the string is null or 0-length. https://developer.android.com/reference/android/text/TextUtils
TextUtils.isEmpty() Vs String.isEmpty()
TextUtils.isEmpty() return boolean value regardless of null/length is 0.  Whereas String.isEmpty() only return true if only length is 0, otherwise will result in nullpointerexception.


Do take note of the following from StackOverflow:

  1. If you are adding values in firebase database manually, the values will be in long data type; for example:
  1. If you are adding values by commands, the values will be saved in the database as string. 

Solution:

When you are getting the values from database, save the values in default data type. Then, when you want to reuse the value change it into the string by using the toString() method.

Read Data
Datasnapshot:
A DataSnapshot instance contains data from a Firebase Database location. Any time you read Database data, you receive the data as a DataSnapshot.
DataSnapshots are passed to the methods in listeners that you attach with addValueEventListener(ValueEventListener)addChildEventListener(ChildEventListener), or addListenerForSingleValueEvent(ValueEventListener).
They are efficiently-generated immutable copies of the data at a Firebase Database location. 
They can't be modified and will never change. To modify data at a location, use a DatabaseReference reference (e.g. with setValue(Object)).

public T getValue (Class<T> valueType

In short, getValue required a public constructor with no default argument and defined getter.
to use it, e.g. class name: message
Message m = snapshot.getValue(Message.class);
This method is used to marshall the data contained in this snapshot into a class of your choosing. The class must fit 2 simple constraints:
  1. The class must have a default constructor that takes no arguments
  2. The class must define public getters for the properties to be assigned. Properties without a public getter will be set to their default value when an instance is deserialized
Returns
An instance of the class passed in, populated with the data from this snapshot, or null if there is no data at this location.
     class Message {
         private String author;
         private String text;

         private Message() {}

         public Message(String author, String text) {
             this.author = author;
             this.text = text;
         }

         public String getAuthor() {
             return author;
         }

         public String getText() {
             return text;
         }
     }


     // Later
     Message m = snapshot.getValue(Message.class);
https://www.youtube.com/watch?v=2duc77R4Hqw
ValueEventListener
Classes implementing this interface can be used to receive events about data changes at a location. Attach the listener to a location user addValueEventListener(ValueEventListener).
https://firebase.google.com/docs/reference/android/com/google/firebase/database/ValueEventListener





Comments

Popular posts from this blog

Error when renaming java class nameAndroid Studio

Do you see these terms,"java.lang.ClassNotFoundException, DexPathList", somewhere along the whole chunk of error message, wherever you rename a file? Simple solution would be to clean build! But do make sure the following are rename accordingly too, 1. class name on Directory 2. class: public class MainActivity extends .... 3. Manifest: <activity android:name=".MainActivity"> 4. XML: tools:context=".MainActivity" https://www.facebook.com/Android-Noob-Reboot-1248769758470969/ https://stackoverflow.com/questions/40493946/refactoring-package-name-breaks-app-with-classnotfoundexception-due-to-not-findi

RecyclerView

Benefit of RecyclerView: 1. Standby the next element for display 2. Saves Viewholder scrolled offscreen. Viewholder does not  need to be created or have its view inflated; instead, the app just updates the view's contents to match the new item it was bound to. 3. Adapter use  RecyclerView.adapter.notifyItemChanged to update changed items by rebinding Main Objects 1. RecyclerView Object: Overall container for UI that you add to layout.   The  RecyclerView  creates only as many view holders as are needed to display the on-screen portion of the dynamic content, plus a few extra.  As the user scrolls through the list, the  RecyclerView  takes the off-screen views and rebinds them to the data which is scrolling onto the screen. 2. Adapter: manage Viewholder Object (create and bind to data, onBindViewHolder()   ) 3. Viewholder Object: view in the list. Display a single item with a view 4. LayoutManager: add Views to RecyclerView https://developer.android.com/guide/topic