I'm learning how to implement Room from Android jetpack into my android studio app but a message saying "not enough information to infer type variable T" keeps showing up when I try to use Room.databaseBuilder
this is my code:
// if there is no instance, we create a new one
synchronized(this){
val instance = Room.databaseBuilder(
context.applicationContext,
UserDatabase::class.java,
"user_database"
).build()
INSTANCE = instance
return instance
}
I can add the surrounding function or the whole file if that helps. Thanks in advance!
CodePudding user response:
I'm not sure but this is the problem i faced as well and i solved it by downgrading 'implementation 'androidx.core:core-ktx:1.6.0'
to 'implementation 'androidx.core:core-ktx:1.5.0'
in the build.gradle file
CodePudding user response:
If you have for example:-
@Database(entities = [Objects::class], version = 1)
abstract class MyDatabase: RoomDatabase() {
abstract fun getAllDao(): AllDAO
companion object {
var INSTANCE: MyDatabase? = null
fun getInstance(context: Context): MyDatabase {
synchronized(this) {
val instance = Room.databaseBuilder(
context.applicationContext,
UserDatabase::class.java,
"user_database"
).build()
INSTANCE = instance
return instance
}
}
}
}
The you get the not enough information to infer type variable T
e.g. :-
Changing to use the same class then all is fine, e.g.
@Database(entities = [Objects::class], version = 1)
abstract class UserDatabase: RoomDatabase() { //<<<<<<<<<< CHANGED
abstract fun getAllDao(): AllDAO
companion object {
var INSTANCE: UserDatabase? = null //<<<<<<<<<< CHANGED
fun getInstance(context: Context): UserDatabase { //<<<<<<<<<< CHANGED
if (INSTANCE == null) {
synchronized(this) {
val instance = Room.databaseBuilder(
context.applicationContext,
UserDatabase::class.java, //<<<<<<<<<< AS WAS/ MATCHES
"user_database"
)
.allowMainThreadQueries() /*<<<<<<<<<< ADDED FOR convenience brevity */
.build()
INSTANCE = instance
return instance
}
}
return INSTANCE!!
}
}
}
- Note run on the main thread to just demonstrate that the above runs (see following example run)
As a test/proof consider :-
class MainActivity : AppCompatActivity() {
lateinit var db1: UserDatabase
lateinit var dao1: AllDAO
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
db1 = UserDatabase.getInstance(this) //<<<<<<<<<< GET INSTANCE
dao1 = db1.getAllDao()
dao1.getObjects(listOf("nothing to get as no data has been added, just forcing open/create of database")) //<<<<<<<<< as per text USE/OPEN/CREATE Database(first use, once created database is opened as it persists)
// existing app used ....
The result (ignore TheDatabase as existing code was used for the answer) :-