简体   繁体   中英

How to put UserDeatils using firebase unique uid in Firebase Realtime Database

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

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

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

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 .

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