Reputation: 543
I hava a Worker
class in my application where I want to get the data from my Rooms database. Since I am using MVVM architecture, how can I get the data from the database using repository in my Worker
class?
Code -
Worker class
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();
}}
Repository
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);
}
Upvotes: 1
Views: 1673
Reputation: 2712
You should be able to create an instance of FlightRepository
inside the 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();
}}
Making some assumptions here. I'd refactor FlightDatabase
to accept a Context
, rather than Application
. I'm not sure why the database would need access to Application
Upvotes: 3