2011-04-14 37 views
1

我一直在創建我的第一個應用程序的付費版本。如何將現有數據庫從一個應用程序複製到另一個應用程序

我想複製現有的數據庫到新的付費應用程序。

這怎麼可能?

編輯

在免費的應用程序我使用的是SQLiteOpenHelper。他們可以使用相同的數據庫,但想再次使用SQLiteOpenHelper,並且無法弄清楚如何讓它使用其他數據庫,因爲應用程序具有不同的軟件包名稱(如果它們使用相同的dosn't,則免費數據庫將被刪除當應用程序被刪除?)。

請評論,如果您希望瞭解更多信息(也許是你所需要的信息:))

+0

沒有更多的細節,這是不可能的。是否有他們無法連接到同一個數據庫的原因? – razlebe 2011-04-14 10:59:26

回答

6

你有幾個選項,你不會得到一個包有不同的名稱,以直接與另一包互動數據庫。

  • 所以,你可以一個Content Provider代碼到免費的應用程序,然後讓付費版本從內容提供商收集數據,然後在第一次運行整個傳遞的所有數據。這在我看來有點麻煩 - 但是這意味着用戶不需要SD卡,您還可以控制數據,IE如果用戶已經使用付費版本,則可以將數據添加到數據庫而不是替換新的一個與舊的免費版...

  • 您可以將數據庫從免費版本保存到SDcard,然後收集與付費版本。根據你想要編碼的多少,你可以在免費應用中設置Broadcast Receiver,然後在付費版本中設置sendBroadcast(),這樣,當免費應用接收到廣播時,它將其數據庫應對SD卡,然後付費應用收集它。另一種方式是讓用戶點擊免費版本中的保存按鈕,備份到SD卡,然後用戶點擊付費版本中的按鈕並接收它 - 這可以像複製文件和替換應用程序的數據庫,或者您可以將其作爲不同的數據庫導入付費應用程序,並將其添加到主數據庫中,然後將其丟棄。

作爲一個非常鬆散,簡單的指針,你可以將數據庫複製到SD卡與這樣的事情,這是非常從代碼工作有點剝離下來,因此應被視爲未經測試的程度 - 你將需要的地方增加一些catch塊來得到它具有讀寫權限的工作一起在SD卡中的清單:

// Get hold of the db: 
    InputStream myInput = new FileInputStream("/data/data/com.package.name/databases/database-name"); 
    // Set the output folder on the SDcard 
    File directory = new File("/sdcard/someFolderName"); 
    // Create the folder if it doesn't exist: 
    if (!directory.exists()) 
    { 
     directory.mkdirs(); 
    }  
    // Set the output file stream up: 
    OutputStream myOutput = new FileOutputStream(directory.getPath()+ "/database-name.backup"); 
    // Transfer bytes from the input file to the output file 
    byte[] buffer = new byte[1024]; 
    int length; 
    while ((length = myInput.read(buffer))>0) 
    { 
     myOutput.write(buffer, 0, length); 
    } 
    // Close and clear the streams 
    myOutput.flush(); 
    myOutput.close(); 
    myInput.close(); 

Retreival非常相似:

// Set location for the db: 
    OutputStream myOutput = new FileOutputStream("/data/data/com.package.name/databases/database-name"); 
    // Set the folder on the SDcard 
    File directory = new File("/sdcard/someFolderName"); 
    // Set the input file stream up: 
    InputStream myInput = new FileInputStream(directory.getPath()+ "/database-name.backup"); 
    // Transfer bytes from the input file to the output file 
    byte[] buffer = new byte[1024]; 
    int length; 
    while ((length = myInput.read(buffer))>0) 
    { 
     myOutput.write(buffer, 0, length); 
    } 
    // Close and clear the streams 
    myOutput.flush(); 
    myOutput.close(); 
    myInput.close(); 

然而,我會建議先做一些檢查並向用戶提問一下:

  • 檢查SD卡上是否存在文件,如果是的話,是否要覆蓋它。
  • 檢查他們是否想用當前數據庫覆蓋當前數據庫
  • 您還需要進行一些檢查,例如是SD卡安裝等。

就像我說的上面的代碼真的只是給你一點提示,你如何可能使用SD卡來移動數據庫。

+0

謝謝你的詳細回覆。想想我會嘗試解決方案與內容提供商,因爲我知道人們使用沒有SD卡的應用程序。也許我可以在路上學到一些東西:) – Bastaix 2011-04-15 08:09:14

+0

@Bastaix,你好,請你分享你的解決方案!我試圖通過'FileProvider'實現完全相同的事情,但沒有運氣。無論我走到哪裏,都有'SecurityException'。 – WindRider 2016-02-18 14:51:44

相關問題