Android Room 是一个抽象层,它提供了与 SQLite 数据库的交互方式。Room 使用注解处理器生成实现代码,简化了数据库操作。ViewModel 是 Android Architecture Components 的一部分,用于管理 UI 相关的数据,并在配置更改(如屏幕旋转)时保持数据。
Room 和 ViewModel 通常用于 Android 应用中,特别是在需要持久化数据并确保数据在配置更改时保持不变的场景。
假设我们有两个表 User
和 Order
,我们希望将这两个表的数据合并到一个 ViewModel 中。
@Entity(tableName = "user")
public class User {
@PrimaryKey
public int id;
public String name;
}
@Entity(tableName = "order")
public class Order {
@PrimaryKey
public int id;
public int userId;
public String productName;
}
@Dao
public interface UserDao {
@Query("SELECT * FROM user")
LiveData<List<User>> getAllUsers();
@Query("SELECT * FROM `order` WHERE userId = :userId")
LiveData<List<Order>> getOrdersForUser(int userId);
}
@Dao
public interface OrderDao {
@Query("SELECT * FROM `order`")
LiveData<List<Order>> getAllOrders();
}
@Database(entities = {User.class, Order.class}, version = 1)
public abstract class AppDatabase extends RoomDatabase {
public abstract UserDao userDao();
public abstract OrderDao orderDao();
}
public class CombinedViewModel extends ViewModel {
private final UserDao userDao;
private final OrderDao orderDao;
private final MediatorLiveData<List<UserWithOrders>> combinedData = new MediatorLiveData<>();
public CombinedViewModel(UserDao userDao, OrderDao orderDao) {
this.userDao = userDao;
this.orderDao = orderDao;
LiveData<List<User>> usersLiveData = userDao.getAllUsers();
LiveData<List<Order>> ordersLiveData = orderDao.getAllOrders();
combinedData.addSource(usersLiveData, users -> {
updateCombinedData(users, ordersLiveData.getValue());
});
combinedData.addSource(ordersLiveData, orders -> {
updateCombinedData(usersLiveData.getValue(), orders);
});
}
private void updateCombinedData(List<User> users, List<Order> orders) {
if (users != null && orders != null) {
List<UserWithOrders> userWithOrdersList = new ArrayList<>();
for (User user : users) {
List<Order> userOrders = new ArrayList<>();
for (Order order : orders) {
if (order.userId == user.id) {
userOrders.add(order);
}
}
userWithOrdersList.add(new UserWithOrders(user, userOrders));
}
combinedData.setValue(userWithOrdersList);
}
}
public LiveData<List<UserWithOrders>> getCombinedData() {
return combinedData;
}
public static class UserWithOrders {
public User user;
public List<Order> orders;
public UserWithResolver(User user, List<Order> orders) {
this.user = user;
this.orders = orders;
}
}
}
public class MainActivity extends AppCompatActivity {
private CombinedViewModel viewModel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AppDatabase db = Room.databaseBuilder(getApplicationContext(), AppDatabase.class, "database-name").build();
UserDao userDao = db.userDao();
OrderDao orderDao = db.orderDao();
viewModel = new ViewModelProvider(this, new ViewModelFactory(userDao, orderDao)).get(CombinedViewModel.class);
viewModel.getCombinedData().observe(this, userWithOrdersList -> {
// Update UI with combined data
});
}
}
通过上述步骤,你可以将多个 SQL 查询的数据合并到一个 ViewModel 中,并在 UI 中使用这些数据。
领取专属 10元无门槛券
手把手带您无忧上云