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条)

报告相同问题?

悬赏问题

  • ¥35 平滑拟合曲线该如何生成
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站