1

I am adding username for my Chat App to Firebase Database successfully.

I implemented in activity:

FirebaseDatabase firedb = FirebaseDatabase.getInstance();

in createUser Method.

private void createUser(String uname){
    Map<String,Object> newUser = new HashMap<String, Object>();
    newUser.put("uname",uname);
    DatabaseReference dbref = firedb.getReference();
    dbref.child("Users").push().setValue(newUser);
}

When user click a button this method works. This method work correctly but I want to make uname primary key. I do not want to add a username if it is alerady exists.

Database Structure:

enter image description here

Rules:

{
  "rules": {
    ".read": true,
    ".write": true
  }
}

Finally, how to prevent duplicated uname ?

serkan stack
  • 155
  • 5
  • 15
  • 1
    See http://stackoverflow.com/questions/25294478/how-do-you-prevent-duplicate-user-properties-in-firebase – Frank van Puffelen Jan 23 '17 at 15:07
  • I am looking but it seems complex because I am newbie I could not understand. – serkan stack Jan 23 '17 at 15:18
  • I am good at SQL Database but why NoSQL is too complex? Nothing is understood easily, complex hard and feeled frusturted – serkan stack Jan 23 '17 at 15:33
  • 1
    The basic approach is as @AhmedAbidi answered. For more information see these answers [1](http://stackoverflow.com/q/29970681), [2](http://stackoverflow.com/q/35243492), [3](http://stackoverflow.com/q/37506003/), [4](http://stackoverflow.com/q/38442291) – Frank van Puffelen Jan 23 '17 at 15:34
  • If you're looking to learn NoSQL, I recommend starting with basics. Read [NoSQL data modeling](https://highlyscalable.wordpress.com/2012/03/01/nosql-data-modeling-techniques/) and view [Firebase for SQL developers](https://www.youtube.com/playlist?list=PLl-K7zZEsYLlP-k-RKFa7RyNPa9_wCH2s). – Frank van Puffelen Jan 23 '17 at 15:35

1 Answers1

1

You have to add a top level /uname/ Node. Your data will be like this for example :

{
  "Users" : {
    "user1" : {
      "uname" : "value1",
    },
    "user2" : {
      "uname" : "value2",
    },
    "user3" : {
      "uname" : "value3",
    },
  },
  "uname" : {
    "value1": "user1",
    "value2": "user2",
    "value3": "user3",
  }
}

Now you have to Enforce New Data Structure:

{
  "rules": {
    "users": {
        "uname": { 
          ".validate": "!root.child('uname').child(newData.val()).exists()"
      },
    }
  }
}
Ahmed Abidi
  • 1,047
  • 12
  • 24