0

私の質問は、デバイスで同じアプリを上書きした後、アプリケーションの sqlite データベースを復元したいということです。アプリの起動時に設定を何度も追加するのは好きではありません。

Androidでデータベースをどこかに保存して、そこから再び復元することは可能ですか?

Google と SO で何時間も検索しましたが、解決策は見つかりませんでした。

編集:固定データベースではありません。そのため、Assets フォルダーに保存できません。ユーザーが編集できますが、デフォルトでは、最後に編集された値 (アプリが上書きされる前の値) を保持する必要があります。

4

2 に答える 2

1

私が非常に役立つと思うこの方法:

public static void movedb(File srcdb, File destdb)
{
    try 
    {
        if (Environment.getExternalStorageDirectory().canWrite()) 
        {                 
            if (srcdb.exists()) 
            {
                FileChannel src = new FileInputStream(srcdb).getChannel();
                FileChannel dst = new FileOutputStream(destdb).getChannel();
                dst.transferFrom(src, 0, src.size());
                src.close();
                dst.close();                    
            }
            else
            {
                //ERROR: "Database file references are incorrect"                    
            }
        }
        else
        {
            //ERROR: "Cannot write to file"
        }
    }
    catch (Exception e) 
    {
        //ERROR: e.getMessage()
    }
}

それから私はただ電話します

movedb(this, new File(<context>.getDatabasePath("...your DB name...")), new File("... your location ..."));

バックアップしてから復元するには:

movedb(this, new File("... your location ..."), new File(<context>.getDatabasePath("...your DB name...")));
于 2012-07-30T13:02:57.123 に答える
0

私は ORMLite を使用しており、データベースを外部パブリック ディレクトリに保存する以外に、ファイルをデータベース ディレクトリに復元した後、DatabaseHelperシングルトンを再インスタンス化して新しいものを作成する必要があります。

これが私のバージョンで、簡単にするためにすべての try/catch ブロックを省略しています。

public boolean restoreBackup(Context context){

    String databasePath = "data/data/my.package.name/databases/myDatabase.sqlite";
    String backUpPath = context.getDatabaseDir("myDatabase.sqlite");

    // Copies back-up to database directory
    new File(databasePath).delete();
    FileInputStream streemToBackUp = new FileInputStream(new File(backUpPath));
    OutputStream streamToDatabaseFile = new FileOutputStream(databasePath);

    byte[] buffer = new byte[1024];
    int length;
    while ((length = streamToBackUp.read(buffer)) > 0) {
        streamToDatabaseFile.write(buffer, 0, length);
    }
    streamToDatabaseFile.flush();
    streamToDatabaseFile.close();
    streamToBackUp.close();

    // Re-instantiate DatabasHelper singleton
    DatabaseHelper.closeHelper();
}

の本体closeHelper()は次のとおりです。

public static void closeHelper() {
    helper.close();
}

@Override
public void close() {
    super.close();
    myDao = null; // Set to null every day you have
    helper = null; // Set to null the singleton instance of the helper
}

これは、 OpenHelperManagerクラスを使用してヘルパーをインスタンス化しない限り機能しgetHelper()、返されたインスタンスを格納する代わりにデータベースが必要な場合は常に使用します。

于 2016-07-28T23:42:20.043 に答える