Android Studio firebase数据库在添加新值之前等待读取

时间:2022-01-07 08:19:16

I have a database in which I store users and I want to check if a user exists before adding a new one so I don't overwrite.

我有一个存储用户的数据库,我想在添加新用户之前检查用户是否存在,这样就不会覆盖。

I have a function that goes through database records and returns a boolean value if it finds or doesn't find the user.

我有一个函数,它遍历数据库记录,如果找到或没有找到用户,则返回一个布尔值。

public boolean checkUserExists(final String emailAddress, final String emailDomain){
    DatabaseReference myRef = database.getReference("Users");

    myRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot mydata : dataSnapshot.getChildren()){
                User user = mydata.getValue(User.class);

                if (user.getEmailAddress().equals(emailAddress) &&
                        user.getEmailDomain().equals(emailDomain)){
                    userExists = true;
                    break;
                }
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

    return userExists;
}

The way I am currently trying to do the check is like this:

我目前的检查方式是这样的:

if (!(registerRepo.checkUserExists(emailAddress, emailDomain))){
                User user = new User(firsName, lastName, emailAddress, emailDomain);
                registerRepo.writeUser(user);
            } else {
                Toast toast = Toast.makeText(getBaseContext(), "User exists", Toast.LENGTH_SHORT);
                toast.show();
            }

The problem is that it doesn't wait for the read and goes ahead and creates a new record (I'm using push so it creates the same record under a new push ID). I've seen that firebase has such a thing called transaction handler and I think that is what I need to use but the documentation didn't help me and I've looked at others asking sort-of the same question here but couldn't figure out a solution so please, if you can explain how to do it and not redirect me to other question I'd be grateful.

问题是,它不会等待读取并继续创建一个新记录(我使用push,所以它在新的push ID下创建相同的记录)。我见过,重火力点这种事叫事务处理程序,我想这就是我需要使用但文档没有帮助我,我看过别人再三问相同的问题但不能找出一个解决方案请,如果你能解释一下怎么做,而不是重定向我另一个问题我很感激。

2 个解决方案

#1


1  

Firebase requests are asynchronous.

重火力点请求是异步的。

So you need to add a callback in your checkUserExists if you want to do some code after getting the result from database.

因此,如果您希望在从数据库中获取结果后进行一些代码,则需要在checkUserExists中添加回调。

For example :

例如:

public interface OnCheckUserExist {
    void exist();
    void notExist();
}

registerRepo.checkUserExists(emailAddress, emailDomain, new OnCheckUserExist(){
   @Override
   public void exist(){
       Toast toast = Toast.makeText(getBaseContext(), "User exists",Toast.LENGTH_SHORT);
       toast.show();
   }
   @Override
   public void notExist(){
       User user = new User(firsName, lastName, emailAddress, emailDomain);
       registerRepo.writeUser(user);
   }
})


public void checkUserExists(final String emailAddress, final String emailDomain, OnCheckUserExist onCheckUserExist){
    DatabaseReference myRef = database.getReference("Users");
    myRef.addValueEventListener(new ValueEventListener() {
        boolean userExist;

        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot mydata : dataSnapshot.getChildren()){
                User user = mydata.getValue(User.class);

                if (user.getEmailAddress().equals(emailAddress) &&
                        user.getEmailDomain().equals(emailDomain)){
                    onCheckUserExist.exist();
                    userExist = true;
                    break;
                }
            }
            if (!userExist){
              onCheckUserExist.notExist();
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
}

#2


0  

You need to put your code inside onDataChange like this

您需要将代码放在onDataChange中,如下所示

public boolean checkUserExists(final String emailAddress, final String emailDomain){
    DatabaseReference myRef = database.getReference("Users");

    myRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot mydata : dataSnapshot.getChildren()){
                User user = mydata.getValue(User.class);

                if (user.getEmailAddress().equals(emailAddress) &&
                        user.getEmailDomain().equals(emailDomain)){
                    userExists = true;
                    break;
                }
            }
            if (userExists) {
                User user = new User(firsName, lastName, emailAddress, emailDomain);
                registerRepo.writeUser(user);
            } else {
                Toast toast = Toast.makeText(getBaseContext(), "User exists", Toast.LENGTH_SHORT);
                toast.show();
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

    return userExists;
}

Though I would suggest you to refactor this one by creating separate functions. :)

尽管我建议你通过创建单独的函数来重构它。:)

#1


1  

Firebase requests are asynchronous.

重火力点请求是异步的。

So you need to add a callback in your checkUserExists if you want to do some code after getting the result from database.

因此,如果您希望在从数据库中获取结果后进行一些代码,则需要在checkUserExists中添加回调。

For example :

例如:

public interface OnCheckUserExist {
    void exist();
    void notExist();
}

registerRepo.checkUserExists(emailAddress, emailDomain, new OnCheckUserExist(){
   @Override
   public void exist(){
       Toast toast = Toast.makeText(getBaseContext(), "User exists",Toast.LENGTH_SHORT);
       toast.show();
   }
   @Override
   public void notExist(){
       User user = new User(firsName, lastName, emailAddress, emailDomain);
       registerRepo.writeUser(user);
   }
})


public void checkUserExists(final String emailAddress, final String emailDomain, OnCheckUserExist onCheckUserExist){
    DatabaseReference myRef = database.getReference("Users");
    myRef.addValueEventListener(new ValueEventListener() {
        boolean userExist;

        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot mydata : dataSnapshot.getChildren()){
                User user = mydata.getValue(User.class);

                if (user.getEmailAddress().equals(emailAddress) &&
                        user.getEmailDomain().equals(emailDomain)){
                    onCheckUserExist.exist();
                    userExist = true;
                    break;
                }
            }
            if (!userExist){
              onCheckUserExist.notExist();
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
}

#2


0  

You need to put your code inside onDataChange like this

您需要将代码放在onDataChange中,如下所示

public boolean checkUserExists(final String emailAddress, final String emailDomain){
    DatabaseReference myRef = database.getReference("Users");

    myRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot mydata : dataSnapshot.getChildren()){
                User user = mydata.getValue(User.class);

                if (user.getEmailAddress().equals(emailAddress) &&
                        user.getEmailDomain().equals(emailDomain)){
                    userExists = true;
                    break;
                }
            }
            if (userExists) {
                User user = new User(firsName, lastName, emailAddress, emailDomain);
                registerRepo.writeUser(user);
            } else {
                Toast toast = Toast.makeText(getBaseContext(), "User exists", Toast.LENGTH_SHORT);
                toast.show();
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

    return userExists;
}

Though I would suggest you to refactor this one by creating separate functions. :)

尽管我建议你通过创建单独的函数来重构它。:)