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 求TYPCE母转母转接头24PIN线路板图
  • ¥100 国外网络搭建,有偿交流
  • ¥15 高价求中通快递查询接口
  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型