如何在WorkManager中获取会议室数据库ViewModel实例?

时间:2020-06-18 17:35:22

标签: android-room android-viewmodel android-workmanager

我是Android开发的新手。我无法获得在WorkManager中扩展AndroidViewModel的 room db viewmodel 。我想获取一个viewmodel类实例,以将其插入到房间db中。

AppAdViewModel.class

public class AppAdViewModel extends AndroidViewModel {

    private AppAdRepository appAdRepository;

    public AppAdViewModel(@NonNull Application application) {
        super(application);
        appAdRepository = new AppAdRepository(application);
    }

    public void insert(AppAdModel appAdModel){
        appAdRepository.insertAd(appAdModel);
    }

}

MyBackgroundWorker.class

public class AppDataSyncingworker extends Worker{


    private Context context;
    private AppAdViewModel appAdViewModel;

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

    @NonNull
    @Override
    public Result doWork() {

        this.context = getApplicationContext();
        // error on this line
        this.appAdViewModel = new ViewModelProvider((AppCompatActivity)context).get(AppAdViewModel.class);
        return null;
    }

显示的错误是:

java.util.concurrent.ExecutionException: java.lang.ClassCastException: android.app.Application cannot be cast to androidx.appcompat.app.AppCompatActivity
        at androidx.work.impl.utils.futures.AbstractFuture.getDoneValue(AbstractFuture.java:516)
        at androidx.work.impl.utils.futures.AbstractFuture.get(AbstractFuture.java:475)
        at androidx.work.impl.WorkerWrapper$2.run(WorkerWrapper.java:298)
        at androidx.work.impl.utils.SerialExecutor$Task.run(SerialExecutor.java:91)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
        at java.lang.Thread.run(Thread.java:764)
     Caused by: java.lang.ClassCastException: android.app.Application cannot be cast to androidx.appcompat.app.AppCompatActivity

任何帮助或指导我做错了什么?

1 个答案:

答案 0 :(得分:0)

调用getApplicationContext()不应是获取Context的首选方法。 Worker的public构造函数将Context作为第一个参数。您可以使用