Reputation: 43
I'm using WorkManager
1.0.0-alpha02
found in the android.arch.work:work-runtime
dependency to query a web page every one minute (the querying code is excluded for this example as it's irrelevant).
When I use WorkManager
like this:
WorkManager
.getInstance()
.enqueue(
new PeriodicWorkRequest.Builder(
MessageWorker.class,
1,
TimeUnit.MINUTES
)
.setConstraints(
new Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build()
)
.build()
);
private class MessageWorker extends Worker {
public MessageWorker() {
}
@NonNull
@Override
public WorkerResult doWork() {
// Do stuff
return WorkerResult.SUCCESS;
}
}
it gives this error message:
05-31 17:50:05.645 11749-12168/com.neelkamath.webview E/WorkerWrapper: Trouble instantiating com.neelkamath.webview.MainActivity$MessageWorker
java.lang.InstantiationException: java.lang.Class<com.neelkamath.webview.MainActivity$MessageWorker> has no zero argument constructor
at java.lang.Class.newInstance(Native Method)
at androidx.work.impl.WorkerWrapper.workerFromClassName(WorkerWrapper.java:405)
at androidx.work.impl.WorkerWrapper.workerFromWorkSpec(WorkerWrapper.java:377)
at androidx.work.impl.WorkerWrapper.run(WorkerWrapper.java:132)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
at java.lang.Thread.run(Thread.java:764)
05-31 17:50:05.645 11749-12168/com.neelkamath.webview E/WorkerWrapper: Could for create Worker com.neelkamath.webview.MainActivity$MessageWorker
I have tried the following constructors to no avail:
super();
Upvotes: 4
Views: 1270
Reputation: 39
You can create the MessageWorker class in separate file, and if you want to make MessageWorker class as nested class, you can also make it static
:
public static class MessageWorker extends Worker {
@NonNull
@Override
public WorkerResult doWork() {
// Do stuff
return WorkerResult.SUCCESS;
}
}
The reason is the WorkerWrapper will create your worker instance by clazz.newInstance()
, and there is no zero argument constructor for nested class
Upvotes: 1
Reputation: 24907
Remove following constructor from MessageWorker and make the class public
. :
public MessageWorker() {
}
Also ensure class is in separate file.
Upvotes: 2