当前位置: 首页 > 知识库问答 >
问题:

为什么Android Room不会在我创建对象时自动生成id?

孙熠彤
2023-03-14

我正在创建一个需要一组玩家的应用程序。我使用团队ID作为每个球员的团队主键和外键。在一个片段中,我创建了一个新团队。创建团队并将其添加到我的房间数据库时,它最初的ID为0或未设置,即使我已将“自动生成”设置为true。然后,我导航到团队花名册视图,该视图能够向团队添加新球员。当我创建新玩家并在团队视图模型中使用新团队ID时,团队ID仍然为0或未设置,因此应用程序崩溃,外键约束失败。崩溃后,如果我重新打开应用程序或通过返回团队列表并选择刚创建的初始id为0的团队来避免崩溃,当我这次创建一个玩家时,团队将拥有一个有效的ID。为什么在创建对象并等待导航到片段或重新启动应用程序时,room不立即分配一个唯一的ID?下面的相关代码,感觉我可能给出了太多的代码,但我遵循的是从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;
    }
}

团队视图模型

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

播放器视图模型

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中,以及对话框片段完成时)

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

当创建时,在playerListFra402中

    /*------------------------------------------------------------------------------------------------------------------------------------------*
     *  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());
    }

当点击保存按钮时,在playerFra402中

        @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();
        }

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

共有1个答案

太叔涵亮
2023-03-14

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

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

如果您想检索插入行的id,请查看此SO链接:Android Room-使用auto-generate获取新插入行的id

 类似资料:
  • 问题内容: 我的老师给我一个问题: “用Java创建对象时会发生什么”。 据我所知,创建对象时会发生内存分配,变量初始化和构造函数方法调用。 但是我的老师说我几乎是对的。后面的两件事是正确的,除了内存堆。相反,他说发生了内存分配。我认为对象存储在堆中,所以我的老师错了。你这样认为吗? 问题答案: 与往常一样,找到针对此类问题的解决方案的最佳位置是Java语言规范。 具体来说,从创建新实例的部分可以

  • 有ManyToOne链接的表。每个学生被分配一个方向从教育方向。当我创建学生时,所选方向被重新创建。为什么在创建学生时创建方向? 学生: 教育方向: 学生道:

  • 我正在使用 https://github.com/OpenAPITools/openapi-generator 为我的应用编程接口创建一个客户端。它基本上工作正常,但是生成器创建了许多类型,这些类型封装了包括任何复杂性类型的参数,例如、、 例如 其中InlineObject11定义为 这有什么意义?为什么生成的客户端不接受流再平衡贸易文件(Stream rebalanceTradeFile),而不

  • 当我用main方法为类创建对象时会发生什么?我能在main方法中使用这些实例变量吗,因为它们在同一个类中?

  • 我正在使用hibernate作为我的应用程序的JPA提供者,现在我需要最近存储的请求对象的id,但是当我执行它打印。 我回答了这个问题。 此代码的输出:

  • 下面是所有3个jsp页面的代码; test1.jsp(jsp第1页的代码) test2.jsp(jsp第2页的代码) test3.jsp(jsp第3页的代码) 在我的例子中,当我第一次调用test1.jsp并单击hyper链接时,它调用test2.jsp,并发现会话已经存在,然后直接调用test3.jsp。但在实际情况中,会话既不在test1.jsp上启动,也不在test2.jsp上启动,除非它进