-1
我有一個函數可以檢查一個節點是否可用。該功能如下Firebase:檢查一個節點是否存在
public class Utilities {
static boolean availability;
static FirebaseDatabase fireDb = FirebaseDatabase.getInstance();
static DatabaseReference dbRef1;
private static boolean checkAvailability(String ID) {
/**check in firebase if the generated ID exists. if it exists return false, else return true**/
final String id = ID;
availability = true;
dbRef1 = fireDb.getReference("xdsdads");
dbRef1.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
try {
if (dataSnapshot.hasChild(id) || dataSnapshot.hasChild("Room:" + id)) {
Log.d("key", "Key exists!");
availability = false;
} else {
availability = true;
}
} catch (Exception e) {
Log.d("Error", "error getting key" + e.toString());
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
Log.d("Availability","" + availability);
return availability;
}
public static String generateID() {
/**generates ID **/
String ID = "";
Random random = new Random();
for (int i = 0; i < 8; i++) {
if (i < 4) {
ID = ID + giveAlphabet(random.nextInt(26));
} else {
ID = ID + random.nextInt(9);
}
}
Log.d("ID",ID);
if (checkAvailability(ID)) {
return ID;
} else {
return generateID();
}
}
public static String giveAlphabet(int i) {
/**returns an alphabet from A-Z**/
String[] alphabet = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};
String output = "";
try {
if (i >= 0 && i < 26) {
output = alphabet[i];
} else {
throw new Exception("Value not between 0-26 cannot generate Alphabet");
}
} catch (Exception e) {
Log.d("Exception at Beacon", e.toString());
}
return output;
}
這裏是我的JSON
{
"PKWC1865" : "77.6709266,12.8541147",
"QKAR6584" : "79.6944701,11.1072002",
"Room:ANWE3226" : {
"FREESLOTS" : "2,3,4",
"USER1" : "BC:QKAR6584",
"USER2" : "NONE",
"USER3" : "NONE",
"USER4" : "NONE"
}
}
SAMPLEDB是我的根。我正在檢查參數ID是否存在於數據庫中。但是onDataChange方法永遠不會被調用。因此我無法檢查給定節點是否存在。
該方法將始終返回true。您應該創建一個回調接口並將其作爲參數傳遞給您的方法。 – Linxy
變量「可用性」是全局的, –
well generateID不會考慮您的ID是否存在,因爲它會立即返回true。 – Linxy