O_1001_O 2012-10-25 02:45 采纳率: 0%
浏览 2590
已采纳

android应用里出现了错误

在android应用里出现问题:

单例中的方法代码如下:

public Cursor getFooCursor(Context context)
{
    StorageDBOpenHelper helper = new StorageDBOpenHelper(context);
    SQLiteDatabase db = helper.getReadableDatabase();

    Cursor c = db.query("Foo", new String[] {"_id", "Titel"}, null, null, null, null, "Test DESC");

    return c;
}

然后就出现error:**SQLiteDatabase: close() was never explicitly called on database**

怎么避免这个错误?并且还有一个问题,不能在return c 之前 进行db.close().这样会返回空值。

  • 写回答

3条回答 默认 最新

  • loFataMer 2012-10-25 06:39
    关注

    我建议不要使用单例,用下面的方法试试:

    public class FooDB
    {
        private SQLiteDatabase db = null;
    
        private void open() throws SQLiteException
        {
            if (db != null)
            {
                throw new SQLiteException("Database already opened");
            }
    
            // 创建开放助手
            StorageDBOpenHelper helper = new StorageDBOpenHelper(context);
            try
            {
                // 获取数据库对象
                db = m_openHelper.getWritableDatabase();
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
    
            if (db == null)
            {
                throw new SQLiteException("Failed to open database");
            }
        }
    
        private void close() throws SQLiteException
        {
            if (db != null)
            {
                db.close();
                db = null;
            }        
        }
    
        public Cursor getFooCursor(Context context)
        {
            if(db == null)
                throw new SQLiteException("Database not open");    
    
            Cursor c = db.query("Foo", new String[] {"_id", "Titel"}, null, null, null, null, "Test DESC");
    
            return c;
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置