我是Google Cloud Firestore服务的新用户,但在保存部分数据时失败了:document=sampleData,collection=info
private DocumentReference mdocRef;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
mdocRef=FirebaseFirestore.getInstance().collection("sampleData").document("info"); ....}
保存方法:
private void saveInfo(){
String Name=nameText.getText().toString().trim();
String Phone=phoneText.getText().toString().trim();
String Dob=dobText.getText().toString().trim();
if(Name.isEmpty() || Phone.isEmpty() || Dob.isEmpty()){
Toast.makeText(this,"Please enter the information ",Toast.LENGTH_SHORT).show();return;
}
Map<String,Object> data=new HashMap<String, Object>();
data.put("name",Name);
data.put("phone",Phone);
data.put("dob",Dob);
Log.i("phone",Phone);
mdocRef.set(data).addOnCompleteListener(this, new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if(task.isSuccessful()){
Toast.makeText(getApplicationContext(),"Information has been saved! ",Toast.LENGTH_SHORT).show();return;
}
else{
Toast.makeText(getApplicationContext(),"Information couldn't be saved!,Try again! ",Toast.LENGTH_SHORT).show();return;
}
}
});
}
关于firestore的规则信息:
service cloud.firestore {
match /databases/{database}/documents {
match /sampleData/{anything=**}{
allow read,write: if true;
}
match /{document=**} {
allow read, write;
}
}
}
当用户输入数据和app调用saveInfo()然后调用task
时:
public void onComplete(@NonNull Task<Void> task) {
if(task.isSuccessful()){
Toast.makeText(getApplicationContext(),"Information has been saved! ",Toast.LENGTH_SHORT).show();return;
}
else{
Toast.makeText(getApplicationContext(),"Information couldn't be saved!,Try again! ",Toast.LENGTH_SHORT).show();return;
}
永远不会成功。
答案 0 :(得分:1)
以下是读/写firebase值的基本步骤:
private DatabaseReference mDatabase;
mDatabase = FirebaseDatabase.getInstance().getReference();
//for offline data save
FirebaseDatabase.getInstance().setPersistenceEnabled(true);
插入数据:实时数据库接受多种数据类型String,Long,Double,Boolean,Map,List来存储数据。您还可以使用自定义Java对象来存储数据,这在将模型类直接存储在数据库中时非常有用。
由于每个用户都需要一个唯一的Id,您可以通过调用push()方法生成一个,该方法创建一个具有唯一键的空节点。然后使用child()方法获取对“users”节点的引用。最后使用setValue()方法存储用户数据。
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference("users");
// Creating new user node, which returns the unique key value
// new user node would be /users/$userid/
String userId = mDatabase.push().getKey();
// creating user object
User user = new User("username", "user@abc.com");
// pushing user to 'users' node using the userId
mDatabase.child(userId).setValue(user);
这是用户模型:
@IgnoreExtraProperties
public class User {
public String name;
public String email;
// Default constructor required for calls to
// DataSnapshot.getValue(User.class)
public User() {
}
public User(String name, String email) {
this.name = name;
this.email = email;
}
}
我在Firebase中太新了,我试过保存用户的基本数据。希望它会对你有所帮助。