Android Java访问房间数据库的对象
我正在尝试编写一个安卓应用程序,并实现一个房间数据库。我按照教程设置了数据库(老实说,我并没有完全理解我所做的一切)
从数据库中我得到了一个“LiveData<;List<;Player>;”反对我桌上所有的“玩家”。 每个玩家都有名字和价格
我想把所有价格加起来,在添加新玩家时得到一个平均值。但是我的代码总是忽略最后一个条目,只对列表中的所有内容进行计算,除了最后一个玩家。我的错误在哪里
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == NEW_WORD_ACTIVITY_REQUEST_CODE && resultCode == RESULT_OK) {
// Add a New Player to the Database
int preis = data.getExtras().getInt("EXTRA_REPLY_PREIS");
String name = data.getExtras().getString("EXTRA_REPLY_NAME");
Player player = new Player(name, preis);
mPlayerViewModel.insert(player);
// Populate the TextView "durchschnitt" with the average Value of all players, calculated in durchschnittspreis()
TextView durchschnitt = findViewById(R.id.tvPreis);
LiveData<List<Player>> alleSpieler = mPlayerViewModel.getAllPlayers();
durchschnitt.setText("" + durschnittspreis(alleSpieler));
} else {
Toast.makeText(
getApplicationContext(),
R.string.empty_not_saved,
Toast.LENGTH_LONG).show();
}
}
public int durschnittspreis(LiveData<List<Player>> players) {
int durchschnittspreis = 0;
int preis = 0;
for (int i = 0; i < players.getValue().size(); i++) {
preis = preis + players.getValue().get(i).getPreis();
System.out.println(preis);
durchschnittspreis = preis / players.getValue().size();
}
return durchschnittspreis;
}
# 1 楼答案
我没有足够的声誉发表评论,但您是否尝试过更改durschnittspreis函数中的循环条件,如: