從 firebase 獲取值

  1. 建立類並新增匯入以解析資訊:
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.IgnoreExtraProperties;

//Declaration of firebase references
private DatabaseReference mDatabase;

//Declaration of firebase atributtes
public String uID;
public String username;
public String email;

@IgnoreExtraProperties
public class User {

    //Default constructor
    public User() {

        //Default constructor required for calls to DataSnapshot.getValue(User.class)
        mDatabase = FirebaseDatabase.getInstance().getReference();

        //...
    }

    //...
}
  1. addListenerForSingleValueEvent() 新增到我們的資料庫參考:
//Add new imports
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.ValueEventListener;

//...

public void getUser(String uID){

    //The uID it's unique id generated by firebase database
    mDatabase.child("users").child(uID).addListenerForSingleValueEvent(
            new ValueEventListener () {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                // ...
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                // Getting Post failed, log a message
            }
    });
}
  1. onDataChange() 活動中通過 firebase 資訊為我們的類充氣:
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            //Inflate class with dataSnapShot
            Users user = dataSnapshot.getValue(Users.class);

            //...
        }
  1. 最後,通常我們可以從 firebase 類獲得不同的屬性:
//User inflated
Users user = dataSnapshot.getValue(Users.class);

//Get information
this.uID = user.uID;
this.username = user.username;
this.email = user.email;

最佳做法

  1. firebase 支援 32 個不同的子級別,然後很容易編寫錯誤的引用,以轉義這個建立最終的私有引用:
//Declaration of firebase references
//...
final private DatabaseReference userRef = mDatabase.child("users").child("premium").child("normal").getRef();

//...

public void getUser(String uID){

    //Call our reference
    userRef.child(uID).addListenerForSingleValueEvent(
        new ValueEventListener () {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                // ...
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                // Getting Post failed, log a message
            }
    });
}
  1. 當使用者無法通過資料庫規則訪問此引用時,將呼叫 onCancelled() 事件。如果需要,新增相關程式碼來控制此異常。

有關更多資訊,請訪問官方文件