如何在Android视图上循环添加数据库中的文本?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (114)

数据库结构:

视图实例化如下:

// 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
    }
});
提问于
用户回答回答于

这样试试:

// 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
    }
});

扫码关注云+社区

领取腾讯云代金券