我得到"应用程序没有关闭在此处打开的游标或数据库对象"错误,所以我决定在意图之间传递datahelper,而不是为每个意图关闭/打开数据库。。
我试着加入Extras,但没有成功。。。
谢谢你的帮助
this.dhn=新的DataHelper(this);
public void StartGame(View v) {
Intent intent = new Intent(StartScreen.this, Game.class);
intent.putExtra("dhn",this.dhn);
startActivity(intent);
}
我将DataHelper更改为Singleton,看起来可以在没有新助手的情况下从任何其他意图使用。。看起来目前有效。将测试更多
private static DataHelper singleton;
public static DataHelper getDataHelper(Context context) {
if (singleton == null) {
singleton = new DataHelper(context);
OpenHelper openHelper = new OpenHelper(singleton.context);
singleton.db = openHelper.getWritableDatabase();
}
if(!singleton.db.isOpen()){
OpenHelper openHelper = new OpenHelper(singleton.context);
singleton.db = openHelper.getWritableDatabase();
}
singleton.context = context;
return singleton;
}
private DataHelper(Context context) {
this.context = context;
}
这就是我在代码中处理问题的方法:
public class DataOpenHelper extends SQLiteOpenHelper
{
private static Object lock = new Object();
private static DataOpenHelper inst = null;
private static Context nextContext = null;
private DataOpenHelper()
{
super(nextContext);
nextContext = null;
}
public static void registerContext(Context ctx)
{
synchronized (lock)
{
nextContext = ctx;
}
}
public static DataOpenHelper getInstance() throws ContextNotRegisteredException
{
if (inst == null)
{
synchronized (lock)
{
if (inst == null)
{
if (nextContext == null)
{
throw new ContextNotRegisteredException();
}
inst = new DataOpenHelper();
}
}
}
}
}
public class ContextNotRegisteredException extends Exception{};