嗨,我是Android和Firebase的新手。我正在尝试遍历TextViews并更新数据库中的值。
我得到了一个简单的数据库,并想在多个文本视图上显示所有的关键字(如71001)。我将我的视图实例化如下:
// Instantiate Views for Rolls:
mRoll1 = findViewById(R.id.rollno1);
mRoll2 = findViewById(R.id.rollno2);
mRoll3 = findViewById(R.id.rollno3);
mRoll4 = findViewById(R.id.rollno4);
mRoll5 = findViewById(R.id.rollno5);
mRoll6 = findViewById(R.id.rollno6);
mRoll7 = findViewById(R.id.rollno7);
mRoll8 = findViewById(R.id.rollno8);
这只会将最后一个数字放在文本视图中
// Read from the database
mRootReference.addListenerForSingleValueEvent (new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
mRolll.setText(snapshot.getKey());
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
//Failed to read value
}
});
请帮帮忙。
发布于 2018-08-09 02:22:39
现在的情况是,您最终在第一个TextView
中只有71008
,因为您循环遍历keys
,但只访问第一个TextView
。
如果你知道你总是有8个密钥,在你的例子中,你可以尝试将它们添加到你的TextViews
中,而不是循环,类似于:
// Read from the database
mRootReference.addListenerForSingleValueEvent (new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
Iterator<DataSnapshot> children = dataSnapshot.getChildren().iterator();
mRolll.setText(children.next().getKey());
mRoll2.setText(children.next().getKey());
mRoll3.setText(children.next().getKey());
mRoll4.setText(children.next().getKey());
mRoll5.setText(children.next().getKey());
mRoll6.setText(children.next().getKey());
mRoll7.setText(children.next().getKey());
mRoll8.setText(children.next().getKey());
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
//Failed to read value
}
});
如果你想使用循环,我建议将你的TextViews
放在一个Array
或List
中,然后循环遍历那些包含子元素的元素:
// Read from the database
mRootReference.addListenerForSingleValueEvent (new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
Iterator<DataSnapshot> children = dataSnapshot.getChildren().iterator();
TextView[] views = new TextView[] {
mRolll,
mRoll2,
mRoll3,
mRoll4,
mRoll5,
mRoll6,
mRoll7,
mRoll8,
}
for (int i = 0; i < views.length && children.hasNext(); i++) {
views[i].setText(children.next().getKey());
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
//Failed to read value
}
});
(可以在其他地方创建Array
,可能与实例化Views
的位置相同)
https://stackoverflow.com/questions/51752858
复制相似问题