Reputation: 2484
I'm really new to Java & Andoid, I used to code in Swift.
I'm currently coding the register activity, and more precisely, I'm coding a method to add user data in Cloud Firestore.
In swift I coded something like that:
func signupUser(firstname: String, lastname: String, onSuccess: @escaping () -> Void) {
REF_USERS.document(uid).setData([
"firstname": firstname,
// etc..
]) { (err) in
if let err = err {
print("Error adding document: \(err)")
} else {
// THE FUNCTION HERE
onSuccess()
}
}
}
I would like to have the same "onSuccess()" method in Android, but I don't know how to do it...
I searched but I didn't find anything ...
This is my code without the onSuccess():
public void addNewUser(String firstname, String lastname, String email, Integer gender, String uid, String profileImageUrl){
Map<String, Object> data = new HashMap<>();
data.put("firstname", firstname);
data.put("lastname", lastname);
data.put("email", email);
data.put("gender", gender);
data.put("boxId", "independent");
data.put("notificationsEnabled", true);
data.put("profileImageUrl", profileImageUrl);
mFirebaseFirestore.collection("users").add(data)
.addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
@Override
public void onSuccess(DocumentReference documentReference) {
Log.d(TAG, "DocumentSnapshot written with ID: " + documentReference.getId());
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.w(TAG, "Error adding document", e);
}
});
}
Upvotes: 1
Views: 3198
Reputation: 25261
This is called callback
in java.
First, you define the callback interface with desired functions and input.
public interface FooOnSuccessListener {
void iWantToPassOutAnInteger(int passItOut);
}
Next, in your addNewUser
method, passin this interface as imput and call it to pass your data
public void addNewUser(String someInput, final FooOnSuccessListener listener){
mFirebaseFirestore.collection("users").add(data).addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
@Override
public void onSuccess(DocumentReference documentReference) {
listener.iWantToPassOutAnInteger(FromYourFirebase.someInteger);
}
});
}
Finally, let's say your addNewUser
method comes from class Foo. You can then do something like:
Foo.addNewUser("some param", new FooOnSuccessListener() {
@Override
public void iWantToPassOutAnInteger(int passItOut) {
//Do something with param passItOut
}
});
Upvotes: 2