【发布时间】:2016-12-30 19:49:22
【问题描述】:
我从FirebaseDatabase 获取一些数据,然后将它们放入array,然后尝试在自定义AlertDialog 中的List 中显示它们。
代码如下:
query = mDatabase.child("child").child(anotherChild).child("yetAnotherChild");
uProfile.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
query.orderByChild("someChild").addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
if (dataSnapshot != null) {
Map<String, String> newD = (Map<String, String>) dataSnapshot.getValue();
ArrayList<String> l = new ArrayList<String>();
l.add(newD.get("lol").substring(30));
String names[] = l.toArray(new String[0]);
AlertDialog.Builder alertDialog = new AlertDialog.Builder(Activity.this);
LayoutInflater inflater = getLayoutInflater();
View convertView = inflater.inflate(R.layout.dialog_list, null);
alertDialog.setView(convertView);
alertDialog.setTitle("title");
ListView lv = (ListView) convertView.findViewById(R.id.lv);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getBaseContext(), android.R.layout.simple_list_item_1, names);
lv.setAdapter(adapter);
alertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
alertDialog.show();
} else {
Toast.makeText(getBaseContext(), "NULLLLL", Toast.LENGTH_SHORT).show();
}
}
...
...
});
}
});
这是数据库结构:
app
-child
-anotherChild
-yetAnotherChild
-inaccessibleChild
-someChild: "value"
-lol: "value"
我无法在此处使用valueEventListener(),因为我无法访问inaccessibleChild。这里的inaccessibleChild 是关注特定用户的其他用户的uid。我怎样才能访问那里uid?
问题是正在获取数据,但不是在AlertDialog 中的列表中显示,而是在3 中逐一显示单独的AlertDialog。
这里出了什么问题?
请告诉我。
【问题讨论】:
-
child/anotherChild/yetAnotherChild下有多少个孩子?您正在附加一个ChildEventListener,它看起来在该节点下有 3 个子节点,所以这就是为什么onChildAdded被触发 3 次(alertDialog.show();被调用 3 次 -
@Wilik 是的......这就是正在发生的事情。如何让
alertDialog.show();仅被调用 1 次,显示所有 3 个值? -
Reaz Murshed 的回答提供了最好的例子,使用
ValueEventListener -
@Wilik 请查看已编辑的问题
-
@Reaz Murshed 有最好的答案。如果您不能使用 SingleValueListener,请考虑重组数据以减少和简化查询,如 DavidEast youtube.com/playlist?list=PLl-K7zZEsYLlP-k-RKFa7RyNPa9_wCH2s 的 Firebase Database For SQL Developers 系列中所示
标签: android firebase firebase-realtime-database android-arrayadapter android-alertdialog