问题
I am new to android development. In my app, I need to have a user table in the database. I have created the database using room. Now, if I allow to run the db in the main thread, my app is running fine. But, I don't want to run it in the main thread. So, I created the repository and viewmodel classes and calling the db in the main thread using the viewmodel. Still if I don't put allowMainThreadQueries()
in the database building statement, java.lang.IllegalStateException: Cannot access database on the main thread since it may potentially lock the UI for a long period of time.
error pops up. I checked the following question:
How does the Room Database with LiveData, repository, and viewmodel work together?
, still, don't find the mistake in my code. What is wrong with my code?
My database class:
@Database(entities = {User.class,Order.class,Items.class}, version = 1)
public abstract class MyDatabase extends RoomDatabase {
public abstract UserDao userDao();
public abstract OrderDao orderDao();
public abstract ItemsDao itemsDao();
private static volatile MyDatabase INSTANCE;
public static MyDatabase getDatabase(final Context context) {
if (INSTANCE == null) {
synchronized (MyDatabase.class) {
if (INSTANCE == null) {
INSTANCE = Room.databaseBuilder(context.getApplicationContext(),
MyDatabase.class, "new_database")
.addCallback(sRoomDatabaseCallback).build();
}
}
}
return INSTANCE;
}
private static RoomDatabase.Callback sRoomDatabaseCallback = new RoomDatabase.Callback() {
@Override
public void onOpen(@NonNull SupportSQLiteDatabase db) {
super.onOpen(db);
}
};
}
My repository class:
public class UserRepository {
private UserDao mUserDao;
private LiveData<List<User>> mAllUsers;
public UserRepository(Application application){
AatchalaDatabase db = AatchalaDatabase.getDatabase(application);
mUserDao = db.userDao();
}
LiveData<List<User>> getAllUsers() {
return mAllUsers;
}
public void insert(User newDBUser){
mUserDao.addUser(newDBUser);
}
}
My viewmodel:
public class UserViewModel extends AndroidViewModel {
private UserRepository mRepository;
private LiveData<List<User>> mAllUsers;
public UserViewModel(Application application) {
super(application);
mRepository = new UserRepository(application);
mAllUsers = mRepository.getAllUsers();
}
LiveData<List<User>> getAllUsers() {
return mAllUsers;
}
void insert(User user) {
mRepository.insert(user);
}
}
Part of my fragment:
public class RegisterFragment extends Fragment implements View.OnClickListener {
private UserViewModel nUserViewModel;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_register, container, false);
Button submitRegister = (Button) rootView.findViewById(R.id.registerSubmit);
submitRegister.setOnClickListener(this);
EditText et = (EditText) rootView.findViewById(R.id.registerDOB);
DatePickerUniversal dob = new DatePickerUniversal(et, "dd-MM-yyyy");
nUserViewModel = new ViewModelProvider(this).get(UserViewModel.class);
return rootView;
}
@Override
public void onClick(View view) {
if (view.getId() == R.id.registerSubmit) {
if (readInput(R.id.registerName).matches("") || readInput(R.id.registerAddress).matches("")
|| readInput(R.id.registerPhone).matches("") || readInput(R.id.registerDOB).matches("")
|| readInput(R.id.registerPassword).matches(""))
showErrorStatus("Please fill all required fields");
else if (!readInput(R.id.registerPassword).equals(readInput(R.id.registerReTypePassword)))
showErrorStatus("Password doesn't match");
else if (!invalidUser(readInput(R.id.registerPhone)))
showErrorStatus("Sorry this mobile number is already registered");
else {
User newDBUser=new User(readInput(R.id.registerPhone), readInput(R.id.registerName),
readInput(R.id.registerDOB), readInput(R.id.registerAddress),
readInput(R.id.registerEmail), readInput(R.id.registerPassword));
Log.d("userdb",newDBUser.toString());
nUserViewModel.insert(newDBUser);
Toast.makeText(getActivity().getApplicationContext(), "Registration successful", Toast.LENGTH_LONG).show();
getActivity().getSupportFragmentManager().popBackStackImmediate();
}
}
}
I also created the necessary dao and entity files.
回答1:
In Database class add below:
private static final int NUMBER_OF_THREADS = 4;
static final ExecutorService databaseWriteExecutor =
Executors.newFixedThreadPool(NUMBER_OF_THREADS);
In Repository class change below
AatchalaDatabase db = AatchalaDatabase.getDatabase(application);
AatchalaDatabase db = AatchalaDatabase.getinstance(application);
Add below to functions
`LiveData<List<User>> getAllUsers() {
AatchalaDatabase.databaseWriteExecutor.execute(() -> {
mAllUsers = mUserDao.getAllUsers();
}
return mAllUsers;
}`
回答2:
The documentation explains that:
Room doesn't support database access on the main thread unless you've called allowMainThreadQueries() on the builder because it might lock the UI for a long period of time.
This applies to insert, update and delete operations also, not just queries.
You are performing an insert on the main thread:
nUserViewModel.insert(newDBUser);
That needs to be moved onto a background thread.
来源:https://stackoverflow.com/questions/62778923/how-to-access-room-db-using-viewmodel-repository-and-livedata