java - 如何从 Android 中的 Worker 类访问我的 Rooms 数据库的存储库?
问题描述
我在我的应用程序中有一个Worker
类,我想从我的房间数据库中获取数据。由于我使用的是 MVVM 架构,如何在Worker
课堂上使用存储库从数据库中获取数据?
代码 -
工人阶级
public class SendNotification extends Worker {
public SendNotification(@NonNull Context context, @NonNull WorkerParameters workerParams) {
super(context, workerParams);
}
@RequiresApi(api = Build.VERSION_CODES.M)
@NonNull
@Override
public Result doWork() {
String flightnumber = getInputData().getString("flight");
String date = getInputData().getString("date");
sendNotification(flightnumber,date);
return Result.success();
}}
存储库
public class FlightRepository {
private FlightDao flightDao;
private LiveData<List<Flight>> allFlights;
public FlightRepository(Application application) {
FlightDatabase database = FlightDatabase.getInstance(application);
flightDao = database.flightDao();
allFlights = flightDao.getAllFlights();
}
public void insert(Flight flight) {
new InsertFlightAsyncTask(flightDao).execute(flight);
}
public void update(Flight flight) {
new UpdateFlightAsyncTask(flightDao).execute(flight);
}
public void delete(Flight flight) {
new DeleteFlightAsyncTask(flightDao).execute(flight);
}
public void deleteAllFlights() {
new DeleteAllFlightsAsyncTask(flightDao).execute();
}
public LiveData<List<Flight>> getAllFlights() {
return allFlights;
}
public Flight getFlight(String flightNumber, String date){
return flightDao.getFlight(flightNumber,date);
}
public boolean existsFlight(String flightNumber, String date){
return flightDao.existsFlight(flightNumber, date);
}
解决方案
您应该能够在 FlightRepository
内部创建一个实例Worker
:
public class SendNotification extends Worker {
private FlightRepository flightRepo;
public SendNotification(@NonNull Context context, @NonNull WorkerParameters workerParams) {
super(context, workerParams);
this.flightRepo = new FlightRepository(context)
}
@RequiresApi(api = Build.VERSION_CODES.M)
@NonNull
@Override
public Result doWork() {
String flightnumber = getInputData().getString("flight");
String date = getInputData().getString("date");
// Do what is needed with flightRepo
sendNotification(flightnumber,date);
return Result.success();
}}
在这里做一些假设。我会重构FlightDatabase
以接受 a Context
,而不是Application
. 我不确定为什么数据库需要访问Application
推荐阅读
- java - (Java) 如何使用 SecureRandom 生成 1 到 4 之间的随机整数
- c++ - 是否可以重载将抽象类的引用/指针作为输入的运算符?
- mysql - mysql查询从不同的表中添加列,左连接为空值
- arrays - 在 mongo 的数组中查找平均天数
- jquery - 在 div 内滚动时添加 CSS 动画溢出:滚动
- bash - 用于从文件中获取值并将其保存到其他文件的 Shell 脚本
- python - 试图让答案重复
- c++ -
未定义的引用 Native Android Activity VS 2019 - reactjs - React - 将状态作为道具传递给另一个组件
- c++ - 确定 DLL_PROCESS_DETACH 是否是最后一个