【发布时间】:2019-10-25 10:06:39
【问题描述】:
我正在尝试使用UnityWebRequest 从本地数据库中获取数据。在 Windows 上它可以正常工作。在 Android 上,它第一次运行时找不到数据库,但如果您返回上一个场景并再次加载此场景,那么数据库就会创建并正常工作。
我将数据库放在StreamingAssets 文件夹中(我也直接在Assets/ 中尝试过,但结果是一样的)。
这是我目前所拥有的:
private void Start()
{
//Check platform.
if (Application.platform == RuntimePlatform.Android)
{
platformPath = Application.persistentDataPath;
databasePath = Path.Combine("URI=file:" + platformPath + dbName);
}
else
{
platformPath = Application.dataPath;
databasePath = Path.Combine("URI=file:" + platformPath + "/StreamingAssets" + dbName);
}
if (!File.Exists(Path.Combine(platformPath + dbName)))
{
Debug.Log("File doesn't exists!");
StartCoroutine(GetText());
}
try
{
//Communicate with database.
IDbConnection dbConnection = new SqliteConnection(databasePath);
dbConnection.Open();
//Read and print data in DB table.
IDbCommand cmnd_read = dbConnection.CreateCommand();
IDataReader reader;
string query = "SELECT * FROM BonusWords";
cmnd_read.CommandText = query;
reader = cmnd_read.ExecuteReader();
while (reader.Read())
BonusWordsList.Add(reader[0].ToString().ToUpper());
//Close DB connection.
dbConnection.Close();
}
catch(Exception ex)
{
Debug.Log("EXCEPTION: " + ex);
}
}
private IEnumerator GetText()
{
string path = Path.Combine("jar:file://" + Application.dataPath + "!/assets" + dbName);
UnityWebRequest www = UnityWebRequest.Get(path);
yield return www.SendWebRequest();
while (!www.isDone) { }
try
{
// Retrieve results as binary data.
byte[] data = www.downloadHandler.data;
// Writes the DB in the persistent memory.
File.WriteAllBytes(Path.Combine(Application.persistentDataPath + dbName), data);
}
catch (Exception ex)
{
Debug.Log(ex.Message);
}
}
所以问题在于,在 Android 上,第一次运行时找不到数据库,因此它会在关卡加载后创建它。在加载其余场景内容之前,我应该如何将其更改为始终定位和加载数据库?
【问题讨论】:
-
可能是因为在您下载资产之前尝试打开它?
-
@BugFinder 如何确保在下载资源后打开?但我认为情况并非如此,因为它在 Windows 上正常工作。问题只出在Android..
-
将打开的东西移到方法中,如果存在则立即打开,如果下载后没有打开则在下载代码中
标签: android database sqlite unity3d