When I try to build the app it gives me an error
Execution failed for task ':app:kaptDebugKotlin'.
> A failure occurred while executing org.jetbrains.kotlin.gradle.internal.KaptWithoutKotlincTask$KaptExecutionWorkAction
> java.lang.reflect.InvocationTargetException (no error message)
In build.gradle I specified
apply plugin: 'kotlin-kapt'
and
implementation "android.arch.persistence.room:runtime:1.1.1"
kapt 'android.arch.persistence.room:compiler:1.1.1'
My database class
@Database(entities = [WeatherOfCities::class], version = 1, exportSchema = false)
public abstract class AppDatabase : RoomDatabase(){
public abstract fun weatherOfCitiesDao(): WeatherOfCitiesDao
companion object {
private var INSTANCE: AppDatabase? = null
fun getDatabase(context: Context): AppDatabase {
if (INSTANCE == null) {
synchronized(this) {
INSTANCE =
Room.databaseBuilder(context, AppDatabase::class.java, "database")
.build()
}
}
return INSTANCE!!
}
}
}
My entity class
@Entity
data class WeatherOfCities (
@PrimaryKey(autoGenerate = true)
val id: Long,
val city: String,
val weather: Int
)
My Dao interface
@Dao
interface WeatherOfCitiesDao {
@Query("SELECT * FROM weatherOfCities")
fun getAll(): List<WeatherOfCities>
@Insert
fun insert(weatherOfCities: WeatherOfCities)
@Update
fun update(weatherOfCities: WeatherOfCities)
}
And Build db in MainActivity
class MainActivity : AppCompatActivity(), MainView {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
var presenter = (application as MVPApplication).mainPresenter
presenter?.attachView(this)
var db = AppDatabase.getDatabase(this)
var weatherOfCitiesDao = db.weatherOfCitiesDao()
}
}
Why is the application not building and is it due to errors in the application code?
You need to add the ktx dependency e.g.
implementation 'androidx.room:room-ktx:1.1.1'
I'd also suggest using 2.4.1 for all the room dependencies rather than 1.1.1
So using 2.4.1, .allowMainThreadQueries() (in the AppDatabase before .build()
And
//var presenter = (application as MVPApplication).mainPresenter
//presenter?.attachView(this)
var db = AppDatabase.getDatabase(this)
var weatherOfCitiesDao = db.weatherOfCitiesDao()
weatherOfCitiesDao.insert(WeatherOfCities(0,"London",10))
weatherOfCitiesDao.insert(WeatherOfCities(0,"Paris",20))
weatherOfCitiesDao.update(WeatherOfCities(2,"New York", 30))
for(woc: WeatherOfCities in weatherOfCitiesDao.getAll()) {
Log.d("DBINFO","ID = ${woc.id} City is ${woc.city} Weather is ${woc.weather}")
}
The result written to the log is :-
D/DBINFO: ID = 1 City is London Weather is 10
D/DBINFO: ID = 2 City is New York Weather is 30
Via App Inspection :-