我有一個創建 SQLite DB 的 Xamarin Android 應用程式。重新安裝此應用程式后,我無法使用新版本的應用程式打開資料庫。出于測驗目的,資料庫檔案位于下載檔案夾中。當應用程式剛剛更新而不重新安裝時,它可以正常訪問資料庫。
一個動機:獲得一個獨立的資料庫檔案,可以在將應用程式移動到另一臺設備時用作備份。
編輯:
應用程式.xaml.cs:
public partial class App : Application
{
private readonly static string _dirPath = "/storage/emulated/0/Download/InventoryApp";
private static InvDB _database;
public static InvDB Database
{
get
{
if (_database == null)
{
string dbFileName = "InventoryDB.db3";
_database = new InvDB(Path.Combine(_dirPath, dbFileName));
}
return _database;
}
}
// ....
}
資料庫類建構式:
public class InvDB
{
readonly SQLiteAsyncConnection conn;
public const SQLite.SQLiteOpenFlags Flags =
SQLite.SQLiteOpenFlags.ReadWrite |
SQLite.SQLiteOpenFlags.Create |
SQLite.SQLiteOpenFlags.FullMutex;
public InvDB(string dbPath)
{
if(File.Exists(dbPath))
{
conn = new SQLiteAsyncConnection(dbPath, Flags);
conn.CreateTableAsync<Item>().Wait();
conn.CreateTableAsync<Room>().Wait();
}
}
// ....
}
uj5u.com熱心網友回復:
首先,READ_EXTERNAL_STORAGE、WRITE_EXTERNAL_STORAGE權限需要用戶自己授予,所以你不僅需要將它們添加到manifest檔案中,還需要做一個權限請求來獲得權限。
您可以查看此鏈接:Can't write to Android External storage even with permissions set
如果還是不行,您可以嘗試授予應用訪問所有檔案權限,但我不建議這樣做。
您可以查看我幾個月前發布的答案:How to Request manage_external_storage Permission in Xamarin.Android
更新:
看來Download檔案夾比較特殊,我在里面新建了一個txt檔案,嘗試用寫外存權限寫入。但是我失敗了,官方檔案說:
如果您的應用想要訪問 MediaStore.Downloads 集合中不是您的應用創建的檔案,則必須使用存盤訪問框架。要了解有關如何使用此框架的更多資訊,請參閱有關如何訪問檔案和其他檔案的指南。
可以查看官方檔案:https ://developer.android.com/training/data-storage/shared/media#scoped_storage_enabled
然后我將其添加<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />到清單檔案中,并使用我上面提供的鏈接中的代碼來請求MANAGE_EXTERNAL_STORAGE權限。我成功寫入檔案。
所以你也可以嘗試這樣做或者use the Storage Access Framework像官方檔案說的那樣打開下載檔案夾中的資料庫檔案。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/476767.html
上一篇:QComboBox.curfrentText()不作業-我總是得到TypeError:execute()argument1mustbestr,nottuple
