如何解决如何从 Android 中的 Worker 类访问我的房间数据库的存储库?
我在我的应用程序中有一个 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
以接受 Context
,而不是 Application
。我不确定为什么数据库需要访问 Application
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。