android在意图之间传递datahelper

时间:2012-01-16 10:44:12

标签: android

我得到“应用程序未关闭此处打开的游标或数据库对象”错误,因此我决定在意图之间传递datahelper而不是为每个意图关闭/打开数据库..

我试图加入Extras但是没有用......

感谢您的帮助

  

this.dhn = new DataHelper(this);

public void StartGame(View v) { 
Intent intent = new Intent(StartScreen.this, Game.class); 
intent.putExtra("dhn",this.dhn); 
startActivity(intent); 
}

2 个答案:

答案 0 :(得分:0)

我将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;
}

答案 1 :(得分:0)

这就是我在代码中解决问题的方法:

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{};