2016-09-22 43 views
-2

我有這樣的代碼:當我與孩子搜索在Firebase android中爲null?

String email = FirebaseAuth.getInstance().getCurrentUser().getEmail(); 
myRef = database.getReference("reserva/"); 
myRef.orderByChild("email").equalTo(email).addValueEventListener(new ValueEventListener() { 
    @Override 
    public void onDataChange(DataSnapshot dataSnapshot) { 

     String value = dataSnapshot.child("reserva/1/status").getValue(String.class); 
     String status; 
     TextView textview2 = (TextView) findViewById(R.id.TextView2); 
     if (value != null) { 
      status = dataSnapshot.getKey() + getString(R.string.statusreservafeita); 
      textview2.setText(status + value); 
     } else 
      textview2.setText(R.string.statusreservafail); 
    } 

    @Override 
    public void onCancelled(DatabaseError error) { 
     TextView textview2 = (TextView) findViewById(R.id.TextView2); 
     textview2.setText(R.string.statusreservafail); 
    } 
}); 

我的數據:

"reserva" : { 
    "1" : { 
    "email" : "[email protected]", 
    "status" : "check in" 
    }, 
    "2" : { 
    "email" : "[email protected]", 
    "status" : "check out" 
    }, 
    "123" : { 
    "email" : "[email protected]", 
    "status" : "reservado" 
    } 
} 

當我把一個電子郵件[email protected]返回null。我需要它返回狀態,但它返回null。我想我錯過了一個孩子。

+3

什麼奇怪的標題。 – shmosel

+1

奇怪的問題 –

+1

請在您的問題中輸入正確的英文。 –

回答

0

你在代碼中有幾個問題,但沒有什麼重要的。

下面是摘錄,最有可能的工作:

myRef.orderByChild("email").equalTo(email).addValueEventListener(new ValueEventListener() { 
    @Override 
    public void onDataChange(DataSnapshot dataSnapshot) { 
     for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) { 
      String status = childSnapshot.child("status").getValue(String.class); 
     } 
    } 

我所做的改變是:

  1. 我加了一個遍歷dataSnapshot.getChildren()。查詢可以返回多個子項。因此,即使只有一個匹配項,它也會返回一個列表。通過循環播放dataSnapshot.getChildren()我們得到每場比賽。
  2. 我直接從statusSnapshot獲得值,而不是從根目錄查找它。

選擇,如果你想通過它的絕對路徑查找子,你可以做這樣的事情:

statusRef = database.getReference("reserva/1/status"); 
statusRef.addValueEventListener(new ValueEventListener() { 
    @Override 
    public void onDataChange(DataSnapshot dataSnapshot) { 
     String status = dataSnapshot.getValue(String.class); 
    } 
    ...