我正在尝试在firebase实时数据库中添加一些与用户数据分开的联系人数据。这是我的树结构:我想要做的是,获取用户的name
值(例如UID-1
)并在Contact
子项中,创建同一用户的新子项并写入name
值以及另外两个价值观(contatcMethod
和phoneValue
)。
这是我的代码到目前为止(我有一个RadioGroup
为contactMethod
):
public class ContactDetails extends AppCompatActivity {
RadioGroup radioGroup;
RadioButton radioButton;
private EditText phoneNumber;
private FirebaseAuth mAuth;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
mAuth = FirebaseAuth.getInstance();
radioGroup = findViewById(R.id.radioGroup);
phoneNumber = findViewById(R.id.phoneNumber);
Button submit = findViewById(R.id.submit);
submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int radioId = radioGroup.getCheckedRadioButtonId();
radioButton = findViewById(radioId);
contact();
}
});
}
private void contact() {
FirebaseUser user = mAuth.getCurrentUser();
String userID = user.getUid();
final String phoneValue = phoneNumber.getText().toString().trim();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Users");
ref.child(userID).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
final String name = dataSnapshot.child("name").getValue().toString();
UserContact userContact = new UserContact(
contactMethod,
phoneValue,
name
);
FirebaseDatabase.getInstance().getReference("Contact")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.setValue(userContact).addOnCompleteListener(new OnCompleteListener < Void > () {
@Override
public void onComplete(@NonNull Task < Void > task) {
if (task.isSuccessful()) {
Toast.makeText(ContactDetails.this, "Saved Successfully", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(ContactDetails.this, "Not successful", Toast.LENGTH_LONG).show();
}
}
});
}
});
}
}
而我的UserContact
java是:
package com.rimikri.smartpedi;
public class UserContact {
public String contactMethod, phoneValue, name;
public UserContact() {
}
public UserContact(String contactMethod, String phoneValue, String name) {
this.contactMethod = contactMethod;
this.phoneValue = phoneValue;
this.name = name;
}
}
但是我没有成功用这段代码在数据库中写入任何数据。它正在回归“不成功”的吐司。我非常感谢能够了解我做错了什么。
我得到的错误是:
DatabaseError:权限被拒绝
似乎它可能是一个权限问题,因为否则,代码应该工作。请尝试以下更新数据库读写权限。
{
"rules": {
"Users": {
"$uid": {
".read": "$uid === auth.uid",
".write": "$uid === auth.uid"
}
},
"Contact": {
"$uid": {
".read": "$uid === auth.uid",
".write": "$uid === auth.uid"
}
}
}
}