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我想在toast中显示用户的id(来自数据库)。
答案 0 :(得分: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) {
}
});
我想在toast中显示用户的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对象
,这会更简单一些