Android Studio 无法识别 createFromAsset()

createFromAsset() is not recognized in Android Studio

我试图预填充我的房间数据库,但 Android Studio 说它“无法解析 'Builder' 中的方法 'createFromAsset()'。我使用的是房间版本 2.2.6 和功能已在 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 {

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(项目)

ext {
roomVersion = '2.2.6'
archLifecycleVersion = '2.2.0'
}

您正在使用 AndroidX 之前时代的 android.arch 依赖项。这些 包含任何新功能 - 尽管您提供了更新的版本,但它们永久停留在 2.0 版本。您需要根据 Room dependencies and Lifecycle dependencies 切换到这些工件的 androidx 版本才能真正获得较新的版本。

// 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"