我花了几个小时使Sqlite在Android上运行,但我仍然不能。在Unity编辑器上,一切正常,但是当我为Android编译时,构建apk,安装apk,则应用程序不起作用。应该从数据库中返回一个值,但是不会发生。
任何帮助都很感谢。
这是我用于与数据库连接的代码。
private void Awake()
{
//dbFile = "URI= File:assets/database/wordsdb.sqlite";
GenerateConnectionString();
}
private void Connection()
{
//connection = new SqliteConnection(dbFile);
connection = new SqliteConnection(connectionString);
command = connection.CreateCommand();
connection.Open();
}
public void GenerateConnectionString()
{
string DatabaseName = "wordsdb.sqlite";
#if UNITY_EDITOR
string dbPath = Application.dataPath + "/database/" + DatabaseName;
Debug.Log("Compilado no unity. " + Application.dataPath);
#else
//check if file exists in Application.persistentDataPath
string filepath = Application.persistentDataPath + "/" + DatabaseName;
if (!File.Exists(filepath) || new System.IO.FileInfo(filepath).Length == 0)
{
// if it doesn't ->
// open StreamingAssets directory and load the db ->
#if UNITY_ANDROID
WWW loadDb = new WWW("jar:file://" + Application.dataPath + "!/assets/" + DatabaseName); // this is the path to your StreamingAssets in android
//WWW loadDb = new WWW("jar:file://" + Application.dataPath + "!/assets/" + DatabaseName);
while (!loadDb.isDone) { } // CAREFUL here, for safety reasons you shouldn't let this while loop unattended, place a timer and error check
// then save to Application.persistentDataPath
File.WriteAllBytes(filepath, loadDb.bytes);
Debug.Log("Compilado no android. " + Application.dataPath);
#elif UNITY_IOS
var loadDb = Application.dataPath + "/Raw/" + DatabaseName; // this is the path to your StreamingAssets in iOS
// then save to Application.persistentDataPath
File.Copy(loadDb, filepath);
#elif UNITY_WP8
var loadDb = Application.dataPath + "/StreamingAssets/" + DatabaseName; // this is the path to your StreamingAssets in iOS
// then save to Application.persistentDataPath
File.Copy(loadDb, filepath);
#elif UNITY_WINRT
var loadDb = Application.dataPath + "/StreamingAssets/" + DatabaseName; // this is the path to your StreamingAssets in iOS
// then save to Application.persistentDataPath
File.Copy(loadDb, filepath);
#endif
}
var dbPath = filepath;
#endif
connectionString = "URI=file:" + dbPath;
}