我正在创建一个需要一组玩家的应用程序。我将团队ID用作团队主键和每个玩家的外键。在一个片段中,我创建了一个新团队。创建团队并将其添加到我的房间数据库后,即使我将auto generate设置为true,它最初的ID还是未设置为0。然后,我导航到团队名册视图,该视图可以向团队中添加新球员。当我创建新玩家并在团队视图模型中使用新的团队ID时,团队ID仍为0或未设置,因此应用程序崩溃,并且外键约束失败。崩溃后,如果我重新打开应用程序,或者如果我通过返回团队列表并选择刚创建的初始ID为0的团队来避免崩溃,那么当我这次创建一名球员时,该团队将拥有一个有效的ID 。在创建对象并等待导航离开并返回片段或重新启动应用程序时,为什么房间不立即分配唯一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
@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();
}
在创建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();
}
如果需要其他任何代码,请告诉我
答案 0 :(得分:0)
这是预期的行为。 Room
不会直接更新id
中的newTeam
字段。
Room
更改输入对象没有任何意义,更不用说Room
并不假定实体字段是可变的。您可以将所有Entity
字段都设为不可变,并且我认为这是一种使您的实体类尽可能不可变的好习惯。
如果要检索插入行的id
,请查看以下SO链接:Android Room - Get the id of new inserted row with auto-generate