user12786901
user12786901

Reputation:

How to pass parameters to Workmanager DoWork method

I want to Schedule task to be deleted from the database after 24 hours

public class WorkManager extends Worker {

    public WorkManager(@NonNull Context context, @NonNull WorkerParameters workerParams) {
        super(context, workerParams);
    }

    @NonNull
    @Override
    public Result doWork() {
        return null;
    }}

how can i pass the Task to be deleted as a parameter to the DoWork method like so...

public void deleteTask(Task task){
        DataBaseHelper db = new DataBaseHelper(context);
        db.deleteOne(task);
    }

Upvotes: 2

Views: 7163

Answers (1)

Hussain
Hussain

Reputation: 1345

Worker class still does not support custom object as parameters to pass in Data. What you can do is tweak your deleteOne method to delete task based on id and pass this id to be deleted to Worker.

  public static OneTimeWorkRequest create(String id) {
      Data inputData = new Data.Builder()
              .putString(TASK_ID, id)
              .build();
      return new OneTimeWorkRequest.Builder(SampleWorker.class)
              .setInputData(inputData)
              .setInitialDelay(24, TimeUnit.HOURS)
              .build();
 }

...

@NonNull
@Override
public Result doWork() {
    String taskId = getInputData().getString(TASK_ID);

    ...
    ...
}

If you still insist on passing Task as parameter to your Worker you can try

 public static OneTimeWorkRequest create(Task task) {
     String strTask = new Gson().toJson(task);
     Data inputData = new Data.Builder()
             .putString(TASK, strTask)
             .build();
     return new OneTimeWorkRequest.Builder(SampleWorker.class)
             .setInputData(inputData)
             .setInitialDelay(24, TimeUnit.HOURS)
             .build();
 }

 ...

 @NonNull
 @Override
 public Result doWork() {
     String strTask = getInputData().getString(TASK);
     Task task = new Gson().fromJson(strTask, Task.class);

    ...
    ...
 }

Add this dependency in build.gradle for Gson

implementation 'com.google.code.gson:gson:2.8.6'

For more information and studies check out here

Upvotes: 2

Related Questions