简体   繁体   English

Android Java 访问 ROOM 数据库的对象

[英]Android Java accessing objects of a ROOM Database

I am trying to write an android app with a room database implemented.我正在尝试编写一个实现房间数据库的 android 应用程序。 i followed a tutorial to setup the Database (honestly not fully understanding everything that i have done).我按照教程设置数据库(老实说,我没有完全理解我所做的一切)。

From the Database i am getting a "LiveData< List< Player>>" Object with all "Player"s in my Table.从数据库中,我得到一个“LiveData<List<Player>>”Object,所有“Player”都在我的表中。 Each player has a Name and a Price.每个玩家都有一个名字和一个价格。

I want to add up all prices and get a average value when adding a new player.我想在添加新玩家时将所有价格相加并获得平均值。 But the code from me always disregards the last entry and only does the calculation for everything in the List except the last player.但是我的代码总是忽略最后一个条目,只计算列表中除最后一个玩家之外的所有内容。 Where is my error?我的错误在哪里?

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

I don't have enough reputation to comment but did you try changing the loop condition in durschnittspreis function like:我没有足够的声誉发表评论,但您是否尝试更改 durschnittspreis function 中的循环条件,例如:

for (int i = 0; i <= players.getValue().size(); i++)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM