【发布时间】:2026-02-20 10:25:02
【问题描述】:
我正在尝试将数据写入 firebase,这真的很神奇,并且在某种程度上让一切看起来都像魔术,但我很难理解它处理数据和安排数据的方式,我已经阅读了文档并且我仍然无法成功获得我想要的东西(或者可能只是感到迷失)。 我有一个客户端 java 类,它现在有两个参数,我想写 名字和姓氏
package com.example.android.bookkeepingapp;
import com.google.firebase.database.Exclude;
import java.util.HashMap;
import java.util.Map;
public class Client {
//client information
private static long clientId = 0;
private String firstName;
private String lastName;
private String companyName;
private String address;
private String email;
private String phoneNumber;
public Client()
{}
public Client(String firstName, String mLastName)
{
//take the last value and increase it by one
clientId = clientId + 1;
this.firstName = firstName;
this.lastName = getmLastName();
}
public Client(String companyName)
{
this.companyName = companyName;
}
public String getmAddress() {
return this.address;
}
public String getmCompanyName() {
return this.companyName;
}
public String getmEmail() {
return this.email;
}
public String getmFirstName() {
return this.firstName;
}
public String getmLastName() {
return this.lastName;
}
public static long getClientId() {
return clientId;
}
public String getmPhoneNumber() {
return this.phoneNumber;
}
public void setmAddress(String address) {
this.address = address;
}
public void setmCompanyName(String companyName) {
this.companyName = companyName;
}
public void setmEmail(String email) {
this.email = email;
}
public void setmFirstName(String firstName) {
this.firstName = firstName;
}
public void setmLastName(String lastName) {
this.lastName = lastName;
}
public void setmPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
/**
* Map will use for writing the items to the database.
* @return
*/
@Exclude
public Map<String, Object> toMap() {
HashMap<String, Object> result = new HashMap<>();
result.put("firstName", firstName);
result.put("lastName", lastName);
/*result.put("companyName" ,companyName);
result.put("address" ,address);
result.put("email" ,email);
result.put("phoneNumber" ,phoneNumber);*/
return result;
}
}
我想要实现的是在主数据库中有一个名为客户端的分支
mClientDatabaseReference = mFirebaseDatabase.getReference().child("client");
这是添加新用户时发生的情况
// create new client at /track-my-business/client/
final String key =FirebaseDatabase.getInstance().getReference().push().getKey();
// get user input and set it to result
// edit text
Client client = new Client(firstNameEditText.getText().toString(),
lastNameEditText.getText().toString());
Map<String, Object> clientValues = client.toMap();
Map<String, Object> childUpdates = new HashMap<>();
childUpdates.put(key, clientValues);
FirebaseDatabase.getInstance().getReference().updateChildren(childUpdates);
这就是我想要的
我希望客户端 firstName 和 lastName 都写在同一个键值内,当我执行我的代码时,只有 firsName 被成功写入。
【问题讨论】:
标签: java android firebase firebase-realtime-database