1

So, I recently learn about firebase database, and now i'm able to insert a data. I have this script which is to store data to my 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

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 ?

Peter Haddad
  • 78,874
  • 25
  • 140
  • 134
YVS1102
  • 2,658
  • 5
  • 34
  • 63
  • why are you calling it on onCreate method in first place? use some event like button click or callback to insert data – Akshay Katariya Apr 25 '18 at 04:14
  • well, it just for a test. – YVS1102 Apr 25 '18 at 04:14
  • 1
    Possible duplicate of [Google firebase check if child exists](https://stackoverflow.com/questions/37397205/google-firebase-check-if-child-exists) – Leonardo Velozo Apr 25 '18 at 04:18
  • if you have putted this in onCreate() then whenever the Activity is created this data will be added to firebase. so if you are only testing this then its ok, but not recommended in real time projects – Hitesh Sarsava Apr 25 '18 at 04:43

3 Answers3

3

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) {

            }
        });
    }
Dhaval Solanki
  • 4,589
  • 1
  • 23
  • 39
2

First of all, you don't have to call it on the onCreate method. 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. 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. It will be easier for u to get the details too. Also, this will not create duplicates, since the email id is unique. In firebase it will look like this:

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) {

 }
 });
Jerin A Mathews
  • 8,572
  • 4
  • 26
  • 49
  • i get this error ` my@email.com. Firebase Database paths must not contain '.', '#', '$', '[', or ']'` – YVS1102 Apr 25 '18 at 06:19
1

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.

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.

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:

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. The getUid() will retrieve the user id from the firebase authentication which is unique for each user. Then you will be able to add it to the database.

Peter Haddad
  • 78,874
  • 25
  • 140
  • 134