我想在我用Haxe-OpenFl开发的Android游戏中使用Sqllite datbase,但当我试图查询数据库时,应用程序不断崩溃。如果这是不可能的,或者在Android中有任何其他方法来处理数据,请告诉我,因为json和共享对象在我的场景中不起作用。
我也在OpenFl社区发布了这个问题,但我认为它与Haxe的关系比与OpenFl的关系更密切。
OpenFl Community Post
我在做什么:
-
使用创建数据库
DB Browser
并将其保存到
assets/data/db/data.db
-
然后,当应用程序启动时,我会将其复制到
lime.system.System.applicationStorageDirectory
-
它在
applicationStorageDirectory
-
然后我尝试连接到新创建的db文件,它只是连接,但在连接到它之后,尝试获取它连接到的db的名称
trace("Connected to database " +_conn.dbName );
除了连接到数据库的文本之外,它不会在跟踪中显示任何内容。
-
忽略名称,我试图查询数据库,它只是关闭了我的应用程序,没有任何错误,也没有任何我知道的错误。
我的项目。xml
<android target-sdk-version="26" install-location="preferExternal" if="android" />
<android permission="android.permission.WRITE_EXTERNAL_STORAGE"/>
<android permission="android.permission.WRITE_INTERNAL_STORAGE"/>
<haxelib name="openfl" />
<haxelib name="hxcpp" />
<assets path="assets/data/db" rename="db" />
数据库类
package;
import haxe.io.Bytes;
import lime.Assets;
import openfl.system.System;
import sys.FileSystem;
import sys.db.Connection;
import sys.db.Sqlite;
import sys.io.File;
#if android
// Make SQLite work on android by statically compiling the library
import hxcpp.StaticSqlite;
#end
/**
* ...
* @author Sim
*/
class DBManager
{
private var CLONE:String = "db/asset_database.db";
private var NEW:String = "new_db.db";
private var _conn:Connection = null;
public function new()
{
}
public function openDatabase():Void
{
trace("CREATING FILE");
trace("targetPath: " +lime.system.System.applicationStorageDirectory);
//trace("targetPath: " +lime.system.System.applicationDirectory); //Crashing the app
trace("targetPath: " +lime.system.System.documentsDirectory);
trace("targetPath: " +lime.system.System.desktopDirectory);
var targetPath: String = lime.system.System.applicationStorageDirectory+ NEW;
trace("targetPath " + targetPath);
trace("FileSystem.exists(targetPath) " + FileSystem.exists(targetPath));
//Debugging
/*var bytes:Bytes = Assets.getBytes(CLONE);
trace("bytes are here "+bytes);
var content:String = bytes.toString();
trace("content "+content);
File.saveContent(targetPath, content);
trace("Saved");*/
//uncomment when done with errors
/*if (FileSystem.exists(targetPath) == false)
{
var bytes:Bytes = Assets.getBytes(CLONE);
var content:String = bytes.toString();
File.saveContent(targetPath, content);
}*/
var bytes:Bytes = Assets.getBytes(CLONE);
var content:String = bytes.toString();
File.saveContent(targetPath, content);
trace("Saved");
try
{
_conn = Sqlite.open(targetPath+NEW);
}
catch (e:Dynamic)
{
trace("Connection failed with error: "+e);
}
if (_conn != null)
{
trace("Connected to database " +_conn.dbName );
//not getting any database name trying to query
// and KaBoom app gone :D XD
var result = _conn.request("SELECT * FROM TEST");
trace("Query Result "+result.results());
//if i comment then it will go and close the connection too
//without breaking anything O_O
_conn.close();
}
}
}