i was trying to prepopulate my Room Database but Android Studio says that it "cannot resolve method 'createFromAsset()' in 'Builder'. I am using room version 2.2.6 and the function was implemented in version 2.2.0.
package com.example.elementsfoodapp;
import android.content.Context;
import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;
import androidx.sqlite.db.SupportSQLiteDatabase;
@Database(entities = {Food.class}, version = 2, exportSchema = false)
public abstract class FoodRoomDatabase extends RoomDatabase {
public abstract FoodDao foodDao();
private static FoodRoomDatabase INSTANCE;
public static FoodRoomDatabase getDatabase(final Context context) {
if (INSTANCE == null) {
synchronized (FoodRoomDatabase.class) {
if (INSTANCE == null) {
// Create database here
INSTANCE = Room.databaseBuilder(context.getApplicationContext(),
FoodRoomDatabase.class, "food_database")
.createFromAsset("databases/food_database")
.build();
}
}
}
return INSTANCE;
}
}
dependencies:
dependencies {
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'com.google.android.material:material:1.3.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
implementation 'androidx.navigation:navigation-fragment:2.3.3'
implementation 'androidx.navigation:navigation-ui:2.3.3'
implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.3.0'
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.3.0'
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
// Room components
implementation "android.arch.persistence.room:runtime:$rootProject.roomVersion"
annotationProcessor "android.arch.persistence.room:compiler:$rootProject.roomVersion"
androidTestImplementation "android.arch.persistence.room:testing:$rootProject.roomVersion"
//Lifecycle components
implementation "android.arch.lifecycle:extensions:$rootProject.archLifecycleVersion"
annotationProcessor "android.arch.lifecycle:compiler:$rootProject.archLifecycleVersion"
}
build.gradle (Project)
ext {
roomVersion = '2.2.6'
archLifecycleVersion = '2.2.0'
}
You're using the android.arch
dependencies from the pre-AndroidX era. Those do not include any new features - they are permanently stuck at the 2.0 versions, despite you giving a newer version. You need to switch to the androidx
versions of those artifacts as per the Room dependencies and Lifecycle dependencies to actually get the newer versions.
// Room components
implementation "androidx.room:runtime:$rootProject.roomVersion"
kapt "androidx.room:compiler:$rootProject.roomVersion"
androidTestImplementation "androidx.room:testing:$rootProject.roomVersion"
//Lifecycle components
implementation "androidx.lifecycle:runtime-ktx:$rootProject.archLifecycleVersion"
kapt "androidx.lifecycle:compiler:$rootProject.archLifecycleVersion"