2016-06-28 145 views
0

我正在使用this code(android-sqlite-asset-helper)從資產文件夾中的文件位置加載數據庫。這很好。Android:從數據庫中刪除數據

但是,刷新/升級數據庫的處理並不簡單,我想知道是否有一種簡單的方法可以手動從應用程序中的數據庫中刪除所有數據;以便從資產文件加載新的數據庫。

+0

閱讀技能0/10 ... https://github.com/jgilfelt/android-sqlite-asset-helper#upgrades-via-overwrite – Selvin

+0

@Selvin你是對的,它似乎你沒有讀過這個問題! ;-) – PatriceG

+0

「從應用程序中的數據庫中刪除所有數據;以便從資產文件加載新的數據庫。」 ==強制加載 – Selvin

回答

0

它似乎適用於此主要活動產生:

getApplicationContext().deleteDatabase("mydatabase.db"); 
0

您可以使用簡單副本文件覆蓋默認數據庫中的數據。只需通過用新數據庫文件覆蓋默認數據庫即可。 以下代碼僅適用於一個文件,因此您需要稍作更改才能使其與資產文件一起使用。 這裏覆蓋數據庫文件的方法:

/** 
* Copies the database file at the specified location over the current 
* internal application database. 
**/ 
public boolean importDatabase(Context context, String dbPath) throws IOException { 

    File OldDbFile = context.getApplicationContext().getDatabasePath(DBSchema.DATABASE_NAME); 
    // Close the SQLiteOpenHelper so it will commit the created empty 
    // database to internal storage. 
    close(); 
    File newDb = new File(dbPath); 
    if (newDb.exists()) { 
    FileUtils.copyFile(new FileInputStream(newDb), new FileOutputStream(OldDbFile)); 
    // Access the copied database so SQLiteHelper will cache it and mark 
    // it as created. 
    getWritableDatabase().close(); 

    return true; 
    } 
    return false; 
} 

文件實用程序類:

public class FileUtils { 
    /** 
    * Creates the specified <code>toFile</code> as a byte for byte copy of the 
    * <code>fromFile</code>. If <code>toFile</code> already exists, then it 
    * will be replaced with a copy of <code>fromFile</code>. The name and path 
    * of <code>toFile</code> will be that of <code>toFile</code>.<br/> 
    * <br/> 
    * <i> Note: <code>fromFile</code> and <code>toFile</code> will be closed by 
    * this function.</i> 
    * 
    * @param fromFile - FileInputStream for the file to copy from. 
    * @param toFile - FileInputStream for the file to copy to. 
    */ 
    public static void copyFile(FileInputStream fromFile, FileOutputStream toFile) 
     throws IOException { 
    FileChannel fromChannel = null; 
    FileChannel toChannel = null; 
    try { 
     fromChannel = fromFile.getChannel(); 
     toChannel = toFile.getChannel(); 
     fromChannel.transferTo(0, fromChannel.size(), toChannel); 
    } finally { 
     try { 
     if (fromChannel != null) { 
      fromChannel.close(); 
     } 
     } finally { 
     if (toChannel != null) { 
      toChannel.close(); 
     } 
     } 
    } 
    } 
} 

我真的忘了,我拿着的CopyFile方法:(

有一點需要注意:當用戶清理應用程序數據時,數據庫將恢復爲默認狀態。