0

I am implementing an application using FireBase, in this application I have to save user information with user enter unique id. How can I do that. Actually it saving the data with random generated value. But I want to add a user enter unique id.

   @Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);

    txtDetails = (TextView) findViewById(R.id.txt_user);
    inputName = (EditText) findViewById(R.id.name);
    inputEmail = (EditText) findViewById(R.id.email);
    btnSave = (Button) findViewById(R.id.btn_save);

    mFirebaseInstance = FirebaseDatabase.getInstance();

    // get reference to 'users' node
    mFirebaseDatabase = mFirebaseInstance.getReference("users");

    // store app title to 'app_title' node
    mFirebaseInstance.getReference("app_title").setValue("Realtime Database");

    // app_title change listener
    mFirebaseInstance.getReference("app_title").addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            Log.e(TAG, "App title updated");



            // update toolbar title

        }

        @Override
        public void onCancelled(DatabaseError error) {
            // Failed to read value
            Log.e(TAG, "Failed to read app title value.", error.toException());
        }
    });

    // Save / update the user
    btnSave.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            String name = inputName.getText().toString();
            String email = inputEmail.getText().toString();

            // Check for already existed userId
            if (TextUtils.isEmpty(userId)) {
                createUser(name, email);
            } else {
                createUser(name, email);
            }

        }
    });

    toggleButton();
}

// Changing button text
private void toggleButton() {
    if (TextUtils.isEmpty(userId)) {
        btnSave.setText("Save");
    } else {
        btnSave.setText("Save");
    }
}

/**
 * Creating new user node under 'users'
 */
private void createUser(String name, String email) {
    // TODO
    // In real apps this userId should be fetched
    // by implementing firebase auth
    if (TextUtils.isEmpty(userId)) {
        userId = mFirebaseDatabase.push().getKey();
    }

    User user = new User(name, email);

    mFirebaseDatabase.child(userId).push().setValue(user);

    addUserChangeListener();
}

/**
 * User data change listener
 */
private void addUserChangeListener() {
    // User data change listener
    mFirebaseDatabase.child(userId).addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            User user = dataSnapshot.getValue(User.class);

            // Check for null
            if (user == null) {
                Log.e(TAG, "User data is null!");
                return;
            }

            Log.e(TAG, "User data is changed!" + user.name + ", " + user.email);

            // Display newly updated name and email
            //     txtDetails.setText(user.name + ", " + user.email);

            // clear edit text
            inputEmail.setText("");
            inputName.setText("");

            toggleButton();
        }

        @Override
        public void onCancelled(DatabaseError error) {
            // Failed to read value
            Log.e(TAG, "Failed to read user", error.toException());
        }
    });
}

private void updateUser(String name, String email) {
    // updating the user via child nodes
    if (!TextUtils.isEmpty(name))
        mFirebaseDatabase.child(userId).child("name").setValue(name);

    if (!TextUtils.isEmpty(email))
        mFirebaseDatabase.child(userId).child("email").setValue(email);
}    
KENdi
  • 7,576
  • 2
  • 16
  • 31
  • yah i have tried –  May 25 '17 at 10:32
  • @shadygoneinsaneme why you down voted me. –  May 25 '17 at 10:33
  • @shadygoneinsane i have edited my code please see it. –  May 25 '17 at 10:38
  • great !! Now you want user to enter some unique value but how would the user possibly know if the id he entered is unique or not; so take any number from user and concat it with current timestamp - or think of anyother way to make an id unique . Hope you get the point :) – shadygoneinsane May 25 '17 at 10:41
  • check **[this](https://stackoverflow.com/a/41462470/5134647)** and **[this](https://stackoverflow.com/a/41531764/5134647)** – shadygoneinsane May 25 '17 at 10:43
  • @shadygoneinsane thank you very much.. –  May 25 '17 at 10:44

1 Answers1

0

To save user data under an unique identifier i suggest you using the email address in stead of pushing a new key or using the uid. The email address is unique and easy to use. But because Firebase does not accept . symbol in the key i suggest you encode the email address like this:

name@email.com -> name@email,com

As you see, i have changed the the dot symbol . with a coma ,. To achive this i recomand you using this methods:

static String encodeUserEmail(String userEmail) {
    return userEmail.replace(".", ",");
}

static String decodeUserEmail(String userEmail) {
    return userEmail.replace(",", ".");
}

Hope it helps.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193