F
F
foonfyrick2021-03-03 08:16:29
Android
foonfyrick, 2021-03-03 08:16:29

IlegalStateException system services not available to activities before oncreate()?

Error while creating the database, I solved the error, but I can not understand why it happens.
llegalStateException: System services not available to Activities before onCreate(), the error points to the MyRepository class, as soon as I remove it and move all the code to MainActivity everything starts working correctly.

@Dao
interface MyDao {
    @Insert(onConflict = OnConflictStrategy.ABORT)
    fun insert(user: User)
}

@Database(entities = [User::class],version = 1,exportSchema = true)
abstract class MyDatabase:RoomDatabase() {
    abstract fun getDao(): MyDao

    companion object{
        private var INSTANCE:MyDatabase?=null
        fun getInstance(context: Context):MyDatabase?{
            val tempInstance = INSTANCE
            return if (tempInstance!=null){
                tempInstance
            } else{
                val database = Room.databaseBuilder(
                    context,
                    MyDatabase::class.java,
                    "db"
                ).build()
                INSTANCE = database
                INSTANCE
            }
        }
    }
}

class MyRepository(context: Context) {
    private val getMyDao = MyDatabase.getInstance(context)?.getDao()

    fun insert(user: User) = getMyDao?.insert(user)

}

class MainActivity : AppCompatActivity() {
    val repository = MyRepository(this)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        Thread{
            val result=repository.insert(User(0,"qwe"))
           
            Log.e("RESULT:",result.toString())
        }.start()

    }
    
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Zagaevsky, 2021-03-03
@foonfyrick

You create a repository when you create an activity (in fact, in its constructor). Inside you create a Room, which, obviously, tries to take a system service ( getSystemService ) from the context (which is the activity that is just being created at this time ). This is illegal because the activity only becomes usable during onCreate execution. You don't need to do anything before.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question