我的Android应用程序有一个firebase后端。我从后端(不同玩家的名字)中提取了我需要的数据并将其放入Strings的arraylist中。例如
{"John Doe1", "John Doe2"...."John Doe15"}
我现在需要为我的活动填充15个不同的文本视图ID和这些名称。最有效的方法是什么?这是我到目前为止的代码,这是我的活动的样子......
public void onDataChange(DataSnapshot dataSnapshot) {
ArrayList<String> al= new ArrayList<String>();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Player player = snapshot.getValue(Player.class);
String name=player.Name;
al.add(name);
}
答案 0 :(得分:0)
您应该将所有TextView
及其所需的ID放入HashMap
,如下所示:
// init object
HashMap<Integer, TexView> textViewMap = new HashMap<>();
... onCreate(...) {
....
// put value inside
TextView textView1 = (TextView) findViewById(R.id.text_view_1);
textViewMap.put(1, textView1);
...
}
然后,当您从Firebase数据库获取数据时,您可以使用放在那里的存储ID来指示数据属于哪个TextView
:
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
// if you use custom Player object, replace following line
Integer id = snapshot.child("id").getValue(Integer.class);
String name = snapshot.child("name").getValue(String.class);
// then get the TextView and put text in it
textViewMap.get(id).setText(name);
}
...
}
应该这样做。希望这会有所帮助。