// Entities
@Entity(tableName = "users")
public class User {
@PrimaryKey(autoGenerate = true)
private int id;
private String name;
// Getters and Setters
}
// DAO
@Dao
public interface UserDao {
@Insert
void insert(User user);
@Query("SELECT * FROM users")
LiveData> getAllUsers();
}
// Database
@Database(entities = {User.class}, version = 1)
public abstract class AppDatabase extends RoomDatabase {
public abstract UserDao userDao();
}
// Repository
public class UserRepository {
private UserDao userDao;
private LiveData> allUsers;
public UserRepository(Application application) {
AppDatabase db = Room.databaseBuilder(application, AppDatabase.class, "database-name").build();
userDao = db.userDao();
allUsers = userDao.getAllUsers();
}
public LiveData> getAllUsers() {
return allUsers;
}
public void insert(User user) {
new InsertAsyncTask(userDao).execute(user);
}
private static class InsertAsyncTask extends AsyncTask {
private UserDao asyncTaskDao;
InsertAsyncTask(UserDao dao) {
asyncTaskDao = dao;
}
@Override
protected Void doInBackground(final User... params) {
asyncTaskDao.insert(params[0]);
return null;
}
}
}
// ViewModel
public class UserViewModel extends AndroidViewModel {
private UserRepository repository;
private LiveData> allUsers;
public UserViewModel(Application application) {
super(application);
repository = new UserRepository(application);
allUsers = repository.getAllUsers();
}
LiveData> getAllUsers() {
return allUsers;
}
public void insert(User user) {
repository.insert(user);
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?