只需制作一个小的Android应用程序,我需要保存一组数据,并且不确定我是否应该使用对象,数组,listarray,hashmap等。
它需要能够存储字符串和整数(例如,tamename,score,category,turn of number)。
它需要能够存储可变数量的团队。
目前我遇到的问题是我尝试将其存储为对象,但它不会增加得分int值。
我应该为此实例使用哪个集合,何时应该在其他实例中使用每个集合?
修改
好的就是这样,但是当我尝试访问/增加它时,我一直收到NullPointerException。我只能假设它无法从upScore正确访问团队var
所以我的onCreate就像这样
public ArrayList<Team> teams;
public int currentTeam;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
currentTeam = 0;
List<Team> teams = new ArrayList<Team>();
teams.add(new Team("Team 1"));
teams.add(new Team("Team 2"));
}
然后在按下按钮时调用upScore。致命的例外是在这一行
public void upScore(int team_key) {
teams.get(0).score++;
}
这是我的团队对象
class Team {
public String name;
public int score;
public String category;
public int turns;
public Team (String teamName) {
name = teamName;
}
}
答案 0 :(得分:6)
创建自己的类,表示可以保存所需数据的对象,如:
class Team
{
public String teamName;
public int score;
public String category;
public int numberOfTurns;
public Team(...){...} // the constructor
}
然后使用您想要的任何数据结构,例如,arraylist:
List<Team> list = new ArrayList<Team>();
要将元素添加到列表中:
list.add(new Team(...));
增加列表中第一个团队的分数:
list.get(0).score++;
依旧......
答案 1 :(得分:1)
更改
List<Team> teams = new ArrayList<Team>();
到
teams = new ArrayList<Team>();