android - 为什么 Android Room 不在我创建对象后立即分配我自动生成的 ID?

标签 android android-fragments android-room

我正在创建一个需要一组玩家的应用程序。我使用团队 ID 作为团队主键和每个玩家的外键。在一个 fragment 中,我创建了一个新团队。创建团队并将其添加到我的房间数据库时,它最初的 ID 为 0 或未设置,即使我已将自动生成设置为 true。然后我导航到团队花名册 View ,该 View 能够向团队添加新球员。当我创建一个新玩家并在团队 View 模型中使用新团队 ID 时,团队 ID 仍为 0 或未设置,因此应用程序崩溃并且存在外键约束失败。崩溃后,如果我重新打开应用程序,或者如果我通过返回团队列表并选择刚刚创建的初始 ID 为 0 的团队来避免崩溃,这次当我创建一个玩家时,该团队将有一个有效的 ID .为什么 room 在创建对象时不立即分配唯一 ID,而是等待导航离开并返回到 fragment 或应用程序重启?下面的相关代码,感觉我可能提供了太多代码,但我正在遵循我从 android 文档中找到的 jetpack 最佳实践,我不知道问题出在哪里。 https://developer.android.com/jetpack/docs/guide .

数据库

@Database (entities = {Team.class,
                   Player.class},
       version = 6)
public abstract class AppDatabase
    extends RoomDatabase
{
private static final String DATABASE_NAME = "Ultimate_Stats_Database";
private static volatile AppDatabase instance;

public abstract TeamDAO teamDao ();
public abstract PlayerDAO playerDAO ();

static synchronized AppDatabase getInstance (Context context)
{
    if (instance == null)
    {
        // Create the instance
        instance = create(context);
    }

    // Return the instance
    return instance;
}

private static AppDatabase create (final Context context)
{
    // Create a new room database
    return Room.databaseBuilder(
                context,
                AppDatabase.class,
                DATABASE_NAME)
               .fallbackToDestructiveMigration()    // TODO Add migrations, poor practice to ignore
               .build();
}
}

团队实体

@Entity (tableName = "teams")
public class Team
    implements Parcelable
{
@PrimaryKey (autoGenerate = true)
private long id;
private String name;


public Team ()
{
    this.name = "";
}


public Team (String name)
{
    this.name = name;
}
...

DAO 团队

@Dao
public abstract class TeamDAO
{

@Insert (onConflict = OnConflictStrategy.REPLACE)
public abstract long insert (Team team);


@Delete
public abstract int deleteTeam (Team team);


@Query ("SELECT * FROM teams")
public abstract LiveData<List<Team>> getAllTeams ();
}

团队存储库(仅插入)

private TeamDAO teamDao;
private LiveData<List<Team>> teams;

public TeamRepository (Application application)
{
    AppDatabase db = AppDatabase.getInstance(application);
    teamDao = db.teamDao();
    teams = teamDao.getAllTeams();
}

private static class insertAsyncTask
        extends AsyncTask<Team, Void, Void>
{

    private TeamDAO asyncTeamTaskDao;


    insertAsyncTask (TeamDAO teamDao)
    {
        asyncTeamTaskDao = teamDao;
    }


    @Override
    protected Void doInBackground (final Team... params)
    {
        // Trace entry
        Trace t = new Trace();

        // Insert the team into the database
        asyncTeamTaskDao.insert(params[0]);

        // Trace exit
        t.end();

        return null;
    }
}

团队 View 模型

public class TeamViewModel
    extends AndroidViewModel
{
private TeamRepository teamRepository;
private LiveData<List<Team>> teams;
private MutableLiveData<Team> selectedTeam;

public TeamViewModel (Application application)
{
    super(application);
    teamRepository = new TeamRepository(application);
    teams = teamRepository.getAllTeams();
    selectedTeam = new MutableLiveData<Team>();
}

public LiveData<Team> getSelectedTeam()
{
    return selectedTeam;
}

public void selectTeam(Team team)
{
    selectedTeam.setValue(team);
}

public LiveData<List<Team>> getTeams ()
{
    return teams;
}

public void insert (Team team)
{
    teamRepository.insert(team);
}
...

玩家实体

@Entity(tableName = "players",
        foreignKeys = @ForeignKey(entity = Team.class,
                              parentColumns = "id",
                              childColumns = "teamId"),
        indices = {@Index(value = ("teamId"))})
public class Player
    implements Parcelable
{

@PrimaryKey (autoGenerate = true)
private long id;
private String name;
private int line;
private int position;
private long teamId;

public Player ()
{
    this.name = "";
    this.line = 0;
    this.position = 0;
    this.teamId = 0;
}


public Player(String name,
              int line,
              int position,
              long teamId)
{
    this.name = name;
    this.line = line;
    this.position = position;
    this.teamId = teamId;
}
....

玩家DAO

@Dao
public abstract class PlayerDAO
{

@Insert (onConflict = OnConflictStrategy.REPLACE)
public abstract void insert (Player player);


@Delete
public abstract int deletePlayer (Player player);


@Query ("SELECT * FROM players WHERE teamId = :teamId")
public abstract LiveData<List<Player>> getPlayersOnTeam (long teamId);


@Query ("SELECT * FROM players")
public abstract LiveData<List<Player>> getAllPlayers();


@Query ("SELECT * FROM players WHERE id = :id")
public abstract LiveData<Player> getPlayerById (long id);
}

播放器存储库(仅插入)

private PlayerDAO playerDAO;
private LiveData<List<Player>> players;

public PlayerRepository(Application application)
{
    AppDatabase db = AppDatabase.getInstance(application);
    playerDAO = db.playerDAO();
    players = playerDAO.getAllPlayers();
}

public void insert (Player player)
{
    new PlayerRepository.insertAsyncTask(playerDAO).execute(player);
}

private static class insertAsyncTask
        extends AsyncTask<Player, Void, Void>
{
    private PlayerDAO asyncTaskDao;

    insertAsyncTask (PlayerDAO dao)
    {
        asyncTaskDao = dao;
    }

    @Override
    protected Void doInBackground (final Player... params)
    {
        // Get the player being inserted by its id
        LiveData<Player> player = asyncTaskDao.getPlayerById(((Player) params[0]).getId());

        if (player != null)
        {
            // Delete the old record of the player
            asyncTaskDao.deletePlayer(params[0]);
        }

        // Insert the player into the database
        asyncTaskDao.insert(params[0]);

        return null;
    }
}
...

玩家 View 模型

public class PlayerViewModel
    extends AndroidViewModel
{
private PlayerRepository playerRepository;
private LiveData<List<Player>> players;
private MutableLiveData<Player> selectedPlayer;

public PlayerViewModel(Application application)
{
    super(application);
    playerRepository = new PlayerRepository(application);
    players = playerRepository.getAllPlayers();
    selectedPlayer = new MutableLiveData<Player>();
}

public LiveData<Player> getSelectedPlayer()
{
    return selectedPlayer;
}

public void selectPlayer(Player player)
{
    selectedPlayer.setValue(player);
}

public LiveData<List<Player>> getPlayers ()
{
    return players;
}

public void insert (Player player)
{
    playerRepository.insert(player);
}
...

我在哪里创建团队(在 TeamListFragment 中以及完成对话 fragment 时)

public void onDialogPositiveClick (String teamName)
{
    // Trace entry
    Trace t = new Trace();

    // Create a new team object
    Team newTeam = new Team();

    // Name the new team
    newTeam.setName(teamName);

    // Insert the team into the database and set it as the selected team
    teamViewModel.insert(newTeam);
    teamViewModel.selectTeam(newTeam);

    // Trace exit
    t.end();

    // Go to the player list view
    routeToPlayerList();
}

创建时在playerListFragment中

    /*------------------------------------------------------------------------------------------------------------------------------------------*
     *  If the view model has a selected team                                                                                                   *
     *------------------------------------------------------------------------------------------------------------------------------------------*/
    if (sharedTeamViewModel.getSelectedTeam().getValue() != null)
    {
        // Set the team to the team selected
        team = sharedTeamViewModel.getSelectedTeam().getValue();

        // Set the team name fields default text
        teamNameField.setText(team.getName());
    }

点击保存按钮时在playerFragment中

        @Override
        public void onClick (View v)
        {
            // Trace entry
            Trace t = new Trace();

            // Update the player object with the info given by the user
            boolean success = getUserInput();

            /*------------------------------------------------------------------------------------------------------------------------------*
             *  If the input was valid                                                                                                      *
             *------------------------------------------------------------------------------------------------------------------------------*/
            if (success)
            {
                // Set the player id to the team that is selected
                player.setTeamId(sharedTeamViewModel.getSelectedTeam()
                                                    .getValue()
                                                    .getId());

                // Input the the player into the player view model
                sharedPlayerViewModel.insert(player);

                // Remove this fragment from the stack
                getActivity().onBackPressed();
            }

            // Trace exit
            t.end();
        }

如果需要任何其他代码,请告诉我

最佳答案

这是预期的行为。 Room 不会直接更新 newTeam 中的 id 字段。

Room 更改输入对象没有意义,更不用说 Room 不假定实体字段是可变的。您可以使所有 Entity 字段不可变,我相信尽可能使您的实体类不可变是一个很好的做法。

如果您想检索插入行的 id,请查看此 SO 链接:Android Room - Get the id of new inserted row with auto-generate

关于android - 为什么 Android Room 不在我创建对象后立即分配我自动生成的 ID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54727875/

相关文章:

java - Android onActivityResult 在对话框中

布局编辑后 Android RecyclerView 滚动不起作用

Android:CursorLoader 在非最顶层的 Fragment 上崩溃

android - 无法为 org.gradle.api.Project 类型的根项目 'roomVersion' 获取未知属性 'RoomWordSample'

java - 限制基于 Java 的 Web 服务器 TLS 协议(protocol)以供 Wireshark 检查

android - 在 Android Room 中如何创建和调用自定义查询

android - 通过 Dagger 2 提供 RoomDatabase 时实现 .addCallback() 的正确方法是什么?

android - 从 DB 文件创建 Android Room 实体类

android - 如何在 MPAndroidChart 中使用 setLabelCount(...)?

android - onActivityResult Android 的请求代码