Firebase 實時資料庫如何設定資料

注意: 讓我們為示例設定一些匿名身份驗證

{
  "rules": {
    ".read": "auth != null",
    ".write": "auth != null"
  }
}

完成後,通過編輯資料庫地址來建立子項。例如:

https://your-project.firebaseio.com/https://your-project.firebaseio.com/chat

我們會將資料從 Android 裝置放到此位置。你不必建立資料庫結構(選項卡,欄位等),當你將 Java 物件傳送到 Firebase 時,它將自動建立!

建立一個 Java 物件,其中包含要傳送到資料庫的所有屬性:

public class ChatMessage {
    private String username;
    private String message;

    public ChatMessage(String username, String message) {
        this.username = username;
        this.message = message;
    }

    public ChatMessage() {} // you MUST have an empty constructor

    public String getUsername() {
        return username;
    }

    public String getMessage() {
        return message;
    }
}

然後在你的活動中:

if (FirebaseAuth.getInstance().getCurrentUser() == null) {
        FirebaseAuth.getInstance().signInAnonymously().addOnCompleteListener(new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {
                if (task.isComplete() && task.isSuccessful()){
                    FirebaseDatabase database = FirebaseDatabase.getInstance();
                    DatabaseReference reference = database.getReference("chat"); // reference is 'chat' because we created the database at /chat
                }
            }
        });
}

要傳送值:

ChatMessage msg = new ChatMessage("user1", "Hello World!");
reference.push().setValue(msg);

要接收資料庫中發生的更改:

reference.addChildEventListener(new ChildEventListener() {
    @Override
    public void onChildAdded(DataSnapshot dataSnapshot, String s) {
        ChatMessage msg = dataSnapshot.getValue(ChatMessage.class);
        Log.d(TAG, msg.getUsername()+" "+msg.getMessage());
    }

    public void onChildChanged(DataSnapshot dataSnapshot, String s) {}
    public void onChildRemoved(DataSnapshot dataSnapshot) {}
    public void onChildMoved(DataSnapshot dataSnapshot, String s) {}
    public void onCancelled(DatabaseError databaseError) {}
});

StackOverflow 文件