2017-04-05 59 views
0
dbRef.addValueEventListener(new ValueEventListener() { 
     @Override 
     public void onDataChange(final DataSnapshot dataSnapshot) { 

      for (final DataSnapshot ds : dataSnapshot.getChildren()){ 
       arr.add(ds.child("name").getValue().toString()+"--"+ds.child("id").getValue().toString()); 
//ds.child("id").getValue().toString() this is how i get id from database 
       lv.setOnItemClickListener(new AdapterView.OnItemClickListener() { 
        @Override 
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 
         Toast.makeText(getApplication(),"id :"+ds.getKey(),Toast.LENGTH_SHORT).show(); 
        } 
       }); 
      } 
      lv.setAdapter(arrayAdapter); 
     } 
     @Override 
     public void onCancelled(DatabaseError databaseError) { 

     } 
    }); 

這就是我如何從Firebase獲取數據並將其發佈到列表視圖中。 onItemClick我想在烤麪包中顯示用戶的ID(來自數據庫)。從Firebase中檢索數據並在列表視圖中填充它們

回答

0

儘量不要在Firebase方法中創建適配器的點擊偵聽器。

lv.setAdapter(arrayAdapter); 
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() { 
    @Override 
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 
     String clicked = arrayAdapter.getItem(position).toString(); 
     Toast.makeText(MainActivity.this, 
      "id :" + clicked, 
      Toast.LENGTH_SHORT).show(); 
    } 
}); 


dbRef.addValueEventListener(new ValueEventListener() { 
    @Override 
    public void onDataChange(final DataSnapshot dataSnapshot) { 
     arrayAdapter.clear(); 
     for (DataSnapshot ds : dataSnapshot.getChildren()){ 
      arrayAdapter.add(ds.child("name").getValue().toString()+"--"+ds.child("id").getValue().toString()); 
     } 
    } 
    @Override 
    public void onCancelled(DatabaseError databaseError) { 

    } 
}); 

我想表明的用戶(從數據庫)的ID一起舉杯

然後你可以使用這樣的事情

String clicked = arrayAdapter.getItem(position).toString(); 
String[] parts = clicked.split("--"); // This is because you added "--" on the other string. 
Toast.makeText(MainActivity.this, 
    "id :" + parts[1], 
    Toast.LENGTH_SHORT).show(); 

這將是如果有些簡單您將您的Firebase值映射到Java對象

+0

是的但我想隱藏在列表視圖中的id值 –

相關問題