How can I change the value of a variable inside the method from anonymous inner class, to access this variable it must be a final
, but if the variable final can't change its value, how solve this problem using java?
This is My Code, I want to change the value of addFlag
.
public static boolean addUser(UserModle user){
Boolean addFlag ;
dbUser = FirebaseDatabase.getInstance().getReference("user");
Task task = dbUser.child(user.getId()).setValue(user);
task.addOnSuccessListener(new OnSuccessListener() {
@Override
public void onSuccess(Object o) {
addFlag = true;
}
});
task.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
}
});
return addFlag;
}
IMHO, the current implementation of the addUser
function is flawed. As per my understanding, you want to know if the user was added successfully to your firebase database based on the addFlag
value that is returned from this function.
The addFlag
will be updated once the Firebase database call will get back the data from the firebase realtime database. However, you are returning the flag immediately and hence you are not waiting for the result from your background network thread.
In order to achieve that, I would like to suggest an interface
based implementation. You might have an interface
as follows.
public interface FirebaseListener {
void onSuccess(boolean flag);
}
Then add an extra parameter in your addUser
function to pass that interface
from your Activity
or Fragment
where you are calling this function. Hence the function might look as follows.
// Change the return type to void, as we are not expecting anything from this function.
// Instead, we will wait for the success callback using the interface
public static void addUser(UserModle user, FirebaseListener listener) {
dbUser = FirebaseDatabase.getInstance().getReference("user");
Task task = dbUser.child(user.getId()).setValue(user);
task.addOnSuccessListener(new OnSuccessListener() {
@Override
public void onSuccess(Object o) {
listener.onSuccess(true);
}
});
task.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
listener.onSuccess(false);
}
});
}
Now implement the listener in your activity or fragment as follows.
public MyActivity extends AppCompatActivity implements FirebaseListener {
// ... Other functions of your activity
@Override
public void onSuccess(boolean flag) {
if (flag) {
// User add successful. Do something here
} else {
// User add not successful. Do something here
}
}
}
Now while calling the addUser
function, you should pass the callback listener along with it as follows.
addUser(user, this);
I hope that helps.
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.