简体   繁体   中英

Firebase ensuring a record is not repeated

I have this code:

public static void insertvote(String userkey, String categ, String candId) {
            DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
            DatabaseReference totalVotesRef = rootRef.child("votes").child(categ).child(candId);
            Vote vote = new Vote(userkey);
            totalVotesRef.push().setValue(vote.getVoterEmail());
    }

It is supposed to insert votes into a firebase database, in a votes collections as below:

Firebase 数据库 The idea is to ensure a voter only votes once due to integrity by checking if their email exists in the votes. However, as you can see, a voter can vote twice. Is there a way I can make a function that checks whether the email exixts in the database, and if it does exist, tell the voter they cant vote twice? Thanks in advance.

You should use the Firebase Auth UID of the current user as the name of the child key.

String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
totalVotesRef.child(uid).setValue(vote.getVoterEmail());

I will give you an idea, think about it. If you use Shared Preferences, you can put every e-mail address with a boolean flag(True/False - Voted/not). Then, you can call the Shared Preferences and check the boolean value of the flag for every e-mail address. So, if it's true - don't allow him to vote.

Wish I helped :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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