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 文档