I use Firebase DB as DB for my Android app. I need to check if db contains an object with a name, which gives user. If yes, I save the ref to it and load datas, esle - show info about incorrect name of object.
As exemple I used: Firebase querying data
Code:
private void setListReferance(){
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(Config.ADDLIST);
// Set up the input
final EditText input = new EditText(this);
// Specify the type of input expected; this, for example, sets the input as a password, and will mask the text
input.setInputType(InputType.TYPE_CLASS_TEXT);
builder.setView(input);
// Set up the buttons
builder.setPositiveButton(Config.OK, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String listName = input.getText().toString();
boolean correctName = checkListName(shoplistsRef, listName);
if(correctName){
listRef = shoplistsRef.child(listName);
myAdapter.setItemsListRef(listRef);
myAdapter.notifyDataSetChanged();
firebaseUpdate();
}
else{
String messege = "Niepoprawna nazwa listy";
Toast.makeText(MainActivity.this,
messege, Toast.LENGTH_LONG).show();
}
}
});
builder.setNegativeButton(Config.CANCEL, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}
Method which check if db contains. For tests I added toasts.
private boolean checkListName(DatabaseReference ref, String listName){
boolean[] result = new boolean[1];
Query query = ref.child(listName);
query.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
Toast.makeText(MainActivity.this,
ref.toString(), Toast.LENGTH_LONG).show();
Toast.makeText(MainActivity.this,
dataSnapshot.getValue(String.class), Toast.LENGTH_LONG).show();
result[0] = true;
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
return result[0];
}
The problem is when I write correct name (DB has it) the first toast showed from else block setListReferance() (it should not be showed at all) and then two toasts from if (dataSnapshot.exists()){}
Why does it happend? I think there is a problem with sync and async methods but I don't know how to solve it.