I'm trying to update a variable each time i press my button from my Firestore database, but the problem is that whenever I start my application I get null at the first time, and when I hit the button for second time it works correctly.
it seems that my variable isn't initializing correctly at the first time that i press my button. I don't know exactly.
private String name;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.friendsystem_add);
//[Initializing UI Components]
emailToAdd = findViewById(R.id.friend_rq_name);
//[Getting variable]
Button send = findViewById(R.id.friend_rq_send);
send.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final String email = emailToAdd.getText().toString();
//check if user exists or not
doesExist(email);
}
Toast.makeText(AddFriend.this, name, Toast.LENGTH_SHORT).show();
and this is my method:
private void doesExist(String email) {
//sending our friend request to database
db.collection("Users")
//query
.whereEqualTo("email", email)
//getting results
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
//check if task is successfull
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
//getting target account name
name = document.getString("name");
}
}
}
});
}
Here is my full code: https://gist.github.com/arshiyanine/dc16f187d5bcaaaefddd8e38fd8f82c1 Thank you.