【问题标题】:Create and copy db in Room from Assets folder?从 Assets 文件夹中创建和复制 Room 中的数据库?
【发布时间】:2019-08-22 09:29:40
【问题描述】:

下面是我的代码;

 private void copyAttachedDatabase() {
    try {
        InputStream mInput = getAssets().open("dummy");
        String outFileName = "/data/data/package_name/databases/" + Util.DATABASE_NAME;
        OutputStream mOutput = new FileOutputStream(outFileName);
        byte[] mBuffer = new byte[2024];
        int mLength;
        while ((mLength = mInput.read(mBuffer)) > 0) {
            mOutput.write(mBuffer, 0, mLength);
        }
        mOutput.flush();
        mOutput.close();
        mInput.close();


        db = DatabaseClass.initializeDB(HomeScreenActivity.this);

        emailsList = db.daoClass().getAllData();

        Log.e("EEEEEEEEEEEEEEEEEE", "" + emailsList.toString());
    } catch (Exception e) {
        e.printStackTrace();
    }

}


    public static DatabaseClass  initializeDB(Context context) {

    if (INSTANCE == null) {
        synchronized (DatabaseClass.class) {
            if (INSTANCE == null) {
                INSTANCE = Room.databaseBuilder(context,
                        DatabaseClass.class, Util.DATABASE_NAME)
                        .allowMainThreadQueries()
                        .fallbackToDestructiveMigration()
                        .addMigrations(MIGRATION_1_2)
                        .build();
            }
        }
    }
    return INSTANCE;
}

我第一次遇到异常,第二次运行良好...

 java.io.FileNotFoundException: /data/data/package_name/databases/myDatabase (No such file or directory)

【问题讨论】:

标签: android sqlite android-studio android-room


【解决方案1】:

我得到了以下解决方案;

            holder.dataListBinding.llView.setOnClickListener(v -> {

            AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(ImportedDBsActivity.this);
            alertDialogBuilder.setTitle("Import Data");
            alertDialogBuilder
                    .setMessage("Do you want to import this data ?")
                    .setCancelable(false)
                    .setPositiveButton("OK", (dialog, id) -> {
                        Util.deleteDatabaseFile(ImportedDBsActivity.this, Util.DATABASE_NAME);
                        db = Room.databaseBuilder(getApplicationContext(), DatabaseClass.class, Util.DATABASE_NAME)
                                .createFromFile(new File(filePath.get(position))).allowMainThreadQueries()
                                .addMigrations(MIGRATION_1_2
                                        ,
                                        MIGRATION_2_3,MIGRATION_3_4,MIGRATION_4_5)
                                .setJournalMode(RoomDatabase.JournalMode.TRUNCATE)
                                .build();
                        Toast.makeText(getApplicationContext(), "Data Imported", Toast.LENGTH_SHORT).show();
                    })
                    .setNegativeButton("CANCEL", (dialog, id) -> dialog.cancel());
            AlertDialog alertDialog = alertDialogBuilder.create();
            alertDialog.show();


        });

以下是函数;

 public static void deleteDatabaseFile(Context context, String databaseName) {


    File databases = new File(context.getApplicationInfo().dataDir + "/databases");
    File db = new File(databases, databaseName);
    if (db.delete()) {
        Toast.makeText(context, "Database deleted", Toast.LENGTH_SHORT).show();
    }
    else {
        Toast.makeText(context, "Failed to delete database", Toast.LENGTH_SHORT).show();
    }
    File journal = new File(databases, databaseName + "-journal");
    if (journal.exists()) {
        if (journal.delete()) 
           Toast.makeText(context, "Database journal deleted", Toast.LENGTH_SHORT).show();
        }
        else {
            System.out.println("Failed to delete database journal");
        }
    }

    File cache = context.getCacheDir();
    File appDir = new File(cache.getParent());
    if (appDir.exists()) {
        String[] children = appDir.list();
        for (String s : children) {
            if (!s.equals("lib")) {
                deleteDir(new File(appDir, s));
                Log.i("EEEEEERRRRRROOOOOOORRRR", "**************** File /data/data/APP_PACKAGE/" + s + " DELETED *******************");
            }
        }
    }

}

public static boolean deleteDir(File dir) {
    if (dir != null && dir.isDirectory()) {
        String[] children = dir.list();
        int i = 0;
        while (i < children.length) {
            boolean success = deleteDir(new File(dir, children[i]));
            if (!success) {
                return false;
            }
            i++;
        }
    }

    assert dir != null;
    return dir.delete();
}

【讨论】:

    猜你喜欢
    • 2013-04-27
    • 1970-01-01
    • 2012-04-07
    • 1970-01-01
    • 1970-01-01
    • 2013-04-19
    • 2018-02-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多