Room.createFromAsset() 每次打开应用程序时重写应用程序的数据库

Room.createFromAsset() rewrite app's database every time the app is opened

计算器溢出

我试图在首次安装时从资产数据库初始化我的应用程序的数据库。但是,在应用程序关闭之前它可以正常工作。当我再次打开应用程序时,它会调用 createFromAsset()。据我所知,问题在于我正在获取应用程序数据库的实例并用资产数据库重写它。 我不知道如何仅在第一次安装应用程序时调用 createFromAsset() 。

@Database(entities = {ActivitySession.class}, exportSchema = true, version = 1)
public abstract class ActivityPackageDatabase extends RoomDatabase {

private static ActivityPackageDatabase INSTANCE;


public static ActivityPackageDatabase getDatabase(final Context context) {
        if (INSTANCE == null) {
            synchronized (ActivityPackageDatabase.class) {
                if (INSTANCE == null) {
                    INSTANCE = Room.databaseBuilder(context.getApplicationContext(),
                            ActivityPackageDatabase.class, "appDB")
                            .createFromAsset("database/assetDB.db")
                            .fallbackToDestructiveMigration()
                            .build();
                }
            }
        }
        return INSTANCE;
    }

万一有实体和DAO的例子

@Entity
public class SessionPhoto {
    @PrimaryKey(autoGenerate = true)
    public long id;

    public long sessionId;
    public String path;

    public SessionPhoto() {
    }

    public long getSessionId() {
        return sessionId;
    }

    public void setSessionId(long sessionId) {
        this.sessionId = sessionId;
    }

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }
}

@Dao
public abstract class ActivitySessionDao {
    @Update(onConflict = OnConflictStrategy.REPLACE, entity = ActivitySession.class)
    public abstract void updateSession(ActivitySession activitySession);

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    public abstract void addNewJournalEntry(ActivityJournal journalEntry);

    @Insert
    public abstract long insertSession(ActivitySession activitySession);

    @Query("SELECT * FROM activitySession")
    public abstract LiveData<List<ActivitySession>> getAllSessionsRecords();

    @Transaction
    @Query("SELECT * FROM activityPackage WHERE id = :id")
    public abstract LiveData<List<ActivityWithSessions>> getActivityWithSessionById(long id);

    public  void cancelSession(ActivitySession session){
        session.completedDateTime = new Date();
        session.status = ActivityPackageStatus.CANCELED;
        updateSession(session);
    }
    @Query("SELECT * FROM activitysession WHERE activityId = :acitivityId AND id = :id")
    public abstract ActivitySession findSessionByActivityId(long acitivityId, long id);
}

删除fallbackToDestructiveMigration()。不需要调用那个。

INSTANCE = Room.databaseBuilder(context.getApplicationContext(),
                            ActivityPackageDatabase.class, "appDB")
                            .createFromAsset("database/assetDB.db")
                            .build();