我Worker
在应用程序中有一个类,希望从Rooms数据库中获取数据。由于我使用的是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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句