skip to Main Content

I wanted to put a unique id every time when users signups into my apps. below is my code attached which is used to store data currently using vehicleNo:

FirebaseDatabase db = FirebaseDatabase.getInstance();
DatabaseReference root = db.getReference("Drivers");
DriverModel driverModel = new DriverModel(name,contact,email,licenseNo,vehicleNo,age,bloodGroup,uri.toString(),drowsinessImage,dateTime);
root.child(vehicleNo).setValue(driverModel);

3

Answers


  1. You can get your key by using getKey(). Refer here: https://firebase.google.com/docs/database/android/read-and-write#update_specific_fields

    final String key = root.push().getKey();
    

    Next, modify your model class DriverModel include the id. Example:

    public class DriverModel{
    
        //Your others attributes...
        private String id;
    
        //Do get set also...
    
    }
    

    Last, when you want to store data. You can do like this.

    FirebaseDatabase db = FirebaseDatabase.getInstance();
    DatabaseReference root = db.getReference("Drivers");
    final String key = root.push().getKey();
    DriverModel driverModel = new DriverModel(key, name,contact,email,licenseNo,vehicleNo,age,bloodGroup,uri.toString(),drowsinessImage,dateTime);
    root.child(vehicleNo).setValue(driverModel);
    
    Login or Signup to reply.
  2. There are no error messages, simply because you cannot see them. There is nothing in your code that handles errors. To solve this, you have to attach a listener to the setValue() operation, to see if something goes wrong. In code, it will be as simple as:

    root.child(vehicleNo).setValue(driverModel).addOnCompleteListener(new OnCompleteListener<Void>() {
        @Override
        public void onComplete(@NonNull Task<Void> task) {
            if (task.isSuccessful()) {
                Log.d("TAG", "Data successfully written.");
            } else {
                Log.d("TAG", task.getException().getMessage()); //Never ignore potential errors!
            }
        }
    });
    

    If you get an error message due to the fact that you have improper security rules, then go to your Firebase console and set them to allow the write operation.

    Login or Signup to reply.
  3. If the user is signed in with Firebase Authentication, you can get their UID with:

    String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
    

    Then you can save the data under their UID with:

    DriverModel driverModel = new DriverModel(name,contact,email,licenseNo,vehicleNo,age,bloodGroup,uri.toString(),drowsinessImage,dateTime);
    root.child(uid).setValue(driverModel);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search