I'd like to convert the following Realtime Database code to use Firebase:
private void setupFirebaseAuth(){
Log.d(TAG, "setupFirebaseAuth: setting up firebase auth.");
mAuth = FirebaseAuth.getInstance();
mFirebaseDatabase = FirebaseDatabase.getInstance();
myRef = mFirebaseDatabase.getReference();
mAuthListener = new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
myRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
//1st check: Make sure the username is not already in use
if(firebaseMethods.checkIfUsernameExists(username, dataSnapshot)){
append = myRef.push().getKey().substring(3,10);
Log.d(TAG, "onDataChange: username already exists. Appending random string to name: " + append);
}
username = username = append;
//add new user to the database
//add new user_account_settings to the database
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
} else {
// User is signed out
Log.d(TAG, "onAuthStateChanged:signed_out");
}
// ...
}
};
}
where the variables are defined as follows:
//firebase
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private FirebaseMethods firebaseMethods;
private FirebaseDatabase mFirebaseDatabase;
private DatabaseReference myRef;
I can reuse most of it, except when the database is defined like:
private FirebaseDatabase mFirebaseDatabase;
private DatabaseReference myRef;
It would be:
private FirebaseFirestore db;
What would correspond to the DatabaseReference for Firestore, because later on, I don't know how to adapt the myRef.addListenerForSingleValueEvent to Cloud Firestore
The closest equivalent to
addListenerForSingleValueEvent
in Cloud Firestore isget()
.The Firestore documentation on getting data contains this more complete example:
I recommend checking out the documentation and trying it. If you get stuck during a specific step of the conversion, show what you've tried.