0

To save something param to local in JobScheduler, I have implemented below JobService,

class MyJobService : JobService() {

  private var context = applicationContext

  private var db = Room.databaseBuilder(
    context, // ERROR
    AppDatabase::class.java, "database-name"
  ).build()

  override fun onStopJob(params: JobParameters?): Boolean {
    ... 
  }

  override fun onStartJob(params: JobParameters?): Boolean {
    // use db
    ...
  }

but applicationContext is not working with below error message,

Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference

so I'm trying another way that passing room instance to MyJobService in JobInfo,

val job = JobInfo.Builder(
   MY_BACKGROUND_JOB,
   ComponentName(context, MyJobService::class.java) // seems to can not passing any arguments for constructor
)
.build()

but in Class<?>, It seems to can't passing arguments.

How to use room instance in onStartJob ?

1 Answers1

0

You should create a (f.e.)Repository class that handles all interactions with Room. Create a singleton in your Application.

Then you only need to get it via ((MainApp) getApplication()).getRepository()

Find a really good example on the official Android examples Github!

Tobi
  • 858
  • 7
  • 15