简体   繁体   English

如何使用android检查firebase中是否存在值?

[英]How to check if value exists in firebase with android?

So, I recently learn about firebase database, and now i'm able to insert a data.所以,我最近了解了 firebase 数据库,现在我可以插入数据了。 I have this script which is to store data to my firebase .我有这个脚本,用于将数据存储到我的 firebase 。

mDatabase = FirebaseDatabase.getInstance().getReference("Biodata");
String userId = mDatabase.push().getKey();
Biodata bio = new Biodata("MyUser", "MyUser@email.com");
mDatabase.child(userId).setValue(bio);

The script above is in oncreate , so when i run the activty again and again the data will insert twice or more上面的脚本在oncreate ,所以当我一次又一次地运行活动时,数据将插入两次或更多次

and here is my firebase这是我的火力点

Biodata
-LAuyJho4kTnJt5WuCtJ 
    Email:  "MyUser@email.com" 
    Fullname:  "MyUser"

My bidata class我的双数据类

@IgnoreExtraProperties
public class Biodata {

    public String Fullname;
    public String Email;

    public Biodata() {
    }

    public Biodata(String Fullname, String Email) {
        this.Fullname = Fullname;
        this.Email = Email;
    }

}

So, how can i prevent my app to insert same data twice ?那么,如何防止我的应用程序两次插入相同的数据?

Please try below code may help you请尝试以下代码可能对您有所帮助

public void setData(){
        final DatabaseReference dbRef = FirebaseDatabase.getInstance().getReference();
        Query queryToGetData = dbRef.child("Biodata")
                .orderByChild("Email").equalTo("MyUser@email.com");
        queryToGetData.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                if(!dataSnapshot.exists()){
                    String userId = dbRef.child("Biodata").push().getKey();
                    Biodata bio = new Biodata("MyUser", "MyUser@email.com");
                    dbRef.child("Biodata").child(userId).setValue(bio);
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
    }

First of all, you don't have to call it on the onCreate method.首先,您不必在 onCreate 方法上调用它。 But theres another easy way for not creating duplicates.但是还有另一种不创建重复项的简单方法。 You have to create a random key for each user.您必须为每个用户创建一个随机密钥。 Like, say emails id is unique for all users.比如说,电子邮件 ID 对所有用户都是唯一的。 So所以

mDatabase = FirebaseDatabase.getInstance().getReference("Biodata");
Biodata bio = new Biodata("MyUser", "MyUser@email.com");
mDatabase.child("MyUser@email.com").setValue(bio);

In this way, the user's details are under their own email id.这样,用户的详细信息就在他们自己的电子邮件 ID 下。 It will be easier for u to get the details too.您也将更容易获得详细信息。 Also, this will not create duplicates, since the email id is unique.此外,这不会创建重复项,因为电子邮件 ID 是唯一的。 In firebase it will look like this:在 firebase 中,它看起来像这样:

Biodata
 MyUser@email.com
    Email:  "MyUser@email.com" 
    Fullname:  "MyUser"

So later if you want to get the users name, you just have to所以以后如果你想得到用户名,你只需要

DatabaseReference ref= mDatabase.child("MyUser@email.com");

 ref.addListenerForSingleValueEvent(new ValueEventListener() {
 @Override
 public void onDataChange(DataSnapshot dataSnapshot) {
    Biodata bio = dataSnapshot.getValue(Biodata .class);
    // and bio.getName() for getting the name
 }

 @Override
 public void onCancelled(DatabaseError databaseError) {

 }
 });

You should not add the email as a parent node or you will get an error.您不应将电子邮件添加为父节点,否则会出现错误。

First you are adding data twice, it is because you have this under onCreate() , it should be under a button or any event that can occur.首先你添加了两次数据,这是因为你在onCreate()下有这个,它应该在一个按钮或任何可能发生的事件下。

Second, you are generating a random id using push() so every time onCreate() is invoked new data will be added since push() is used to separate records.其次,您使用push()生成一个随机 ID,因此每次调用onCreate()都会添加新数据,因为push()用于分隔记录。

To prevent this problem, add the creation of a user under a button (example under a Sign up button).为防止出现此问题,请在按钮下添加用户创建(例如在注册按钮下)。

If you want to keep it under onCreate() then do the following:如果要将其保留在onCreate()下,请执行以下操作:

mDatabase = FirebaseDatabase.getInstance().getReference("User");
FirebaseUser user=FirebaseAuth.getInstance().getCurrentUser();
String userId=user.getUid();
Biodata bio = new Biodata("MyUser", "MyUser@email.com");
mDatabase.child(userId).setValue(bio);

The above will work if you use firebase authentication and also after login of the user.如果您使用 firebase 身份验证以及用户登录后,上述内容将起作用。 The getUid() will retrieve the user id from the firebase authentication which is unique for each user. getUid()将从每个用户唯一的getUid()身份验证中检索用户 ID。 Then you will be able to add it to the database.然后,您将能够将其添加到数据库中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM