具有新线程和数据绑定问题的Room persistent library

时间:2017-05-29 11:53:03

标签: android android-databinding android-room

我正在使用Android Room Persistent库。我还在我的项目中实现了双向数据绑定。在项目中,我通过填写表单并在行中显示所有用户并通过单击特定用户行更新它来插入用户。以下是我的UserDao类:

@Dao
public interface UserDao {

  @Query("SELECT * FROM user")
  List<User> getAllUsers();

  @Insert
  void insertAll(User... users);

  @Update
  void updateUser(User... users);

  @Query("SELECT * FROM user WHERE user_id IN (:userId)")
  User getSpecifiedUser(int...userId);
 }

对于数据绑定,我在UserFormActivity中绑定用户模型

binding.setUserModel(userModel);

现在,由于Room持久化库不允许您在主线程中执行任何数据库操作,为了更新用户,我通过单击新线程中的行来获取用户表单中特定用户的数据,如下所示: / p>

 private void getUserFormData(final int userId) {
    try {
        Thread t = new Thread(new Runnable() {
            public void run() {
                userModel = db.userDao().getSpecifiedUser(userId);
            }
        }, "Thread A");
        t.start();
    } catch (NumberFormatException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

在userModel中获取用户数据以进行更新后,我希望用户数据反映在执行数据绑定的用户表单中,但它没有反映出来。我坚持这个问题。

1 个答案:

答案 0 :(得分:10)

我在项目中实现了LiveData和ViewModel,并在UserListActivity中扩展了LifecycleActivity。这是我的AddUserViewModel类:

sakai-dev

在AddUserActivity中,我从数据库方法获取特定的用户数据

public class AddUserViewModel extends AndroidViewModel { private UserDatabase userDatabase; public AddUserViewModel(Application application) { super(application); userDatabase = UserDatabase.getDatabase(this.getApplication()); } public void addUser(User user) { new AddUserAsyncTask(userDatabase).execute(user); } private static class AddUserAsyncTask extends AsyncTask<User, Void, Void> { private UserDatabase db; public AddUserAsyncTask(UserDatabase userDatabase) { db = userDatabase; } @Override protected Void doInBackground(User... params) { db.userDao().insertUser(params); return null; } } public User getSpecificUserData(int userId) { User user = null; try { user = new getUserDataAsyncTask(userDatabase).execute(userId).get(); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } return user; } private static class getUserDataAsyncTask extends AsyncTask<Integer, Void, User> { private UserDatabase db; public getUserDataAsyncTask(UserDatabase userDatabase) { db = userDatabase; } @Override protected User doInBackground(Integer... userId) { User user = db.userDao().getSpecifiedUser(userId); return user; } @Override protected void onPostExecute(User user) { super.onPostExecute(user); } } }

并点击提交按钮更新数据。我的UserListActivity扩展了LifecycleActivity,其中观察了用户列表,当有更改时,它会更新使用列表,如下所示:

userModel = addUserViewModel.getSpecificUserData(userId);

这对我来说很好,我得到了解决方案!