[英]Android Room - Get the id of new inserted row form @Insert
In my code below I'm getting rowId
.在下面的代码中,我得到了rowId
。 I've read that it's also possible to get the last inserted row id from @Insert
directly.我读过也可以直接从@Insert
获取最后插入的行ID。 In my code I changed void insert to long and tried many other things as in examples I found on the internet, but every time I get errors.在我的代码中,我将 void insert 更改为 long 并尝试了许多其他事情,就像我在互联网上找到的示例一样,但每次我都遇到错误。 Would you like to provide me a code/solution to get the row/user ID from @Insert?您愿意为我提供从@Insert 获取行/用户 ID 的代码/解决方案吗?
@Dao
public interface UserDao {
@Insert
void insert(UserEntity userEntity);
@Update
void update(UserEntity userEntity);
@Delete
void delete(UserEntity userEntity);
@Query("DELETE FROM user_table")
void deleteAllUsers();
@Query("SELECT * FROM user_table")
LiveData<List<UserEntity>> getAllUsers();
// ====== from here ======
@Query("SELECT * FROM user_table")
LiveData<UserEntity> getRowId();
// ====== till here ======
}
Entity实体
@Entity(tableName = "user_table")
public class UserEntity {
@PrimaryKey(autoGenerate = true)
private int id;
private String userName;
private String userTelephoneNumber;
public UserEntity(String userName, String userTelephoneNumber) {
this.userName = userName;
this.userTelephoneNumber = userTelephoneNumber;
}
public void setId(int id) {
this.id = id;
}
public int getId() {
return id;
}
public String getUserName() {
return userName;
}
public String getUserTelephoneNumber() {
return userTelephoneNumber;
}
}
Repository存储库
public class UserRepository {
private UserDao userDao;
private LiveData<List<UserEntity>> allUsers;
public UserRepository(Application application) {
HandymanDatabase handymanDatabase = HandymanDatabase.getInstance(application);
userDao = handymanDatabase.userDao();
allUsers = userDao.getAllUsers();
}
public void insert(UserEntity userEntity) {
new InsertUserAsyncTask(userDao).execute(userEntity);
}
public void update(UserEntity userEntity) {
new UpdateUserAsyncTask(userDao).execute(userEntity);
}
public void delete(UserEntity userEntity) {
new DeleteUserAsyncTask(userDao).execute(userEntity);
}
public void deleteAllUsers() {
new DeleteAllUsersAsyncTask(userDao).execute();
}
public LiveData<List<UserEntity>> getAllUsers() {
return allUsers;
}
// ====== from here ======
public LiveData<UserEntity> getRowId() {
return userDao.getRowId();
}
// ====== till here ======
private static class InsertUserAsyncTask extends AsyncTask<UserEntity, Void, Void> {
private UserDao userDao;
private InsertUserAsyncTask(UserDao userDao) {
this.userDao = userDao;
}
@Override
protected Void doInBackground(UserEntity... userEntities) {
userDao.insert(userEntities[0]);
return null;
}
}
private static class UpdateUserAsyncTask extends AsyncTask<UserEntity, Void, Void> {
private UserDao userDao;
private UpdateUserAsyncTask(UserDao userDao) {
this.userDao = userDao;
}
@Override
protected Void doInBackground(UserEntity... userEntities) {
userDao.update(userEntities[0]);
return null;
}
}
private static class DeleteUserAsyncTask extends AsyncTask<UserEntity, Void, Void> {
private UserDao userDao;
private DeleteUserAsyncTask(UserDao userDao) {
this.userDao = userDao;
}
@Override
protected Void doInBackground(UserEntity... userEntities) {
userDao.delete(userEntities[0]);
return null;
}
}
private static class DeleteAllUsersAsyncTask extends AsyncTask<Void, Void, Void> {
private UserDao userDao;
private DeleteAllUsersAsyncTask(UserDao userDao) {
this.userDao = userDao;
}
@Override
protected Void doInBackground(Void... voids) {
userDao.deleteAllUsers();
return null;
}
}
}
ViewModel视图模型
public UserViewModel(@NonNull Application application) {
super(application);
userRepository = new UserRepository(application);
allUsers = userRepository.getAllUsers();
}
public void insert(UserEntity userEntity) {
userRepository.insert(userEntity);
}
public void update(UserEntity userEntity) {
userRepository.update(userEntity);
}
public void delete(UserEntity userEntity) {
userRepository.delete(userEntity);
}
public void deleteAllUsers() {
userRepository.deleteAllUsers();
}
public LiveData<List<UserEntity>> getAllUsers() {
return allUsers;
}
// ====== from here ======
public LiveData<UserEntity> getRowId() {
return userRepository.getRowId();
}
// ====== till here ======
}
Fragment/Activity片段/活动
public class UserFavoritesFragment extends Fragment {
private static final String TAG = "UserFavoritesFragment";
private UserViewModel userViewModel;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = getLayoutInflater().inflate(R.layout.fragment_user_favorites, container, false);
final TextView textViewUserName = view.findViewById(R.id.textViewUserName);
TextView textViewUserPhone = view.findViewById(R.id.textViewUserPhone);
userViewModel = new ViewModelProvider(this).get(UserViewModel.class);
// ====== from here ======
userViewModel.getRowId().observe(getViewLifecycleOwner(), new Observer<UserEntity>() {
@Override
public void onChanged(UserEntity userEntity) {
long rowId = userEntity.getId();
Log.d(TAG, "onChanged: " + rowId);
}
});
// ====== till here ======
return view;
}
}
You can do that using a listener interface that has a callback that accepts a long value of the inserted row id in the database.您可以使用具有回调的侦听器接口来执行此操作,该回调接受数据库中插入的行 ID 的长值。
Listener Interface监听器接口
public interface NewIdListener {
void onInsert(long id);
}
Dao道
@Dao
public interface UserDao {
@Insert
long insert(UserEntity userEntity); // return id of the inserted userEntity
}
Repository存储库
public class UserRepository {
private Executor mExecutor = Executors.newSingleThreadExecutor();
private UserDao userDao;
...
public void insertUserEntity(final UserEntity entity, final NewIdListener listener) {
mExecutor.execute(new Runnable() {
@Override
public void run() {
listener.onInsert(userDao.insert(entity));
}
});
}
ViewModel视图模型
public void insertUserEntity(UserEntity entity, NewIdListener listener) {
userRepository.insertUserEntity(entity, listener);
}
Activity活动
userViewModel.insertUserEntity(new UserEntity("User Name", "12345678"), new NewIdListener() {
@Override
public void onInsert(final long id) {
requireActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(requireActivity(), "Id: " + id, Toast.LENGTH_SHORT).show();
}
});
}
});
Note : For background thread, I've used Executor
instead of AsyncTask
as AsyncTask
is deprecated now.注意:对于后台线程,我使用了Executor
而不是AsyncTask
,因为AsyncTask
现在已被弃用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.