【问题标题】:SQLite Database Locked in DialogFragment onClick eventSQLite 数据库在 DialogFragment onClick 事件中锁定
【发布时间】:2014-03-31 16:29:24
【问题描述】:

人们说这可能是您没有关闭游标或数据库时造成的。但我有一些奇怪的事情。 我尝试在应用程序开头的 MainActivity 中的对话框片段窗口(resultClass)中单击 OK 按钮打开数据库。

调用DialogFragment窗口的方法

@SuppressLint("NewApi")
    public void vasya(View v){
    DialogFragment dlg_rec=new resultClass();
     dlg_rec.show(getFragmentManager(), "dlg_rec");}

在我的 DialogFragment 类中

public Score_DS dsoop=new Score_DS(getActivity());

..
case R.id.button1:

        dsoop.open();// Here comes the crash
           ...
            dsoop.close();

Score_DS 是我用来操作数据库的 DataSource 类。

public class Score_DS {
    ContentValues cv= new ContentValues();
    DB dbHelper;
    SQLiteDatabase db;
     public Score_DS(Context context) {
            dbHelper = new DB(context);
          }
    public void open() throws SQLException {
        if (dbHelper != null) {
            db = dbHelper.getWritableDatabase();
        }
    }
...
      (here I have a couple of methods that I've never called yet)
}

DB.java 是这个

package com.wordpress.jimmaru.tutorial.SimpleGame;

import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.BaseColumns;

public class DB extends SQLiteOpenHelper implements BaseColumns{

    private static final String DATABASE_NAME = "mygame.db";
    private static final int DATABASE_VERSION = 1;
    private static DB sInstance;
    ContentValues cv;
     public DB(Context context) {

         super(context, DATABASE_NAME, null, DATABASE_VERSION);}



    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        db.execSQL("CREATE TABLE Records(_id INTEGER PRIMARY KEY,   Player_Name VARCHAR(50), Player_Score VARCHAR(50));");

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldversion, int newversion) {
        // TODO Auto-generated method stub

    }

}

所以,再说一遍。我通过单击一个按钮在我的应用程序的最开始调用 DialogFragment 窗口。当我在对话框片段窗口中单击“确定”按钮时,应用程序崩溃并显示数据库已锁定。我关闭了一切(db.close)。我没有打开游标。在 MainActivity 我有另一个与数据库相关的方法。

Score_DS dseed=new Score_DS(this);
...
public void clearall(View v)
    {
         dseed.open();
         dseed.execution("DELETE FROM Records");
          dseed.close();
    }

而且效果很好。 有什么问题?

【问题讨论】:

    标签: android database sqlite database-locking


    【解决方案1】:

    不是“数据库被锁定”,而是NullPointerException in getDatabaseLocked()。这是因为您在这里将null Context 传递给SQLiteOpenHelper 造成的:

    public Score_DS dsoop=new Score_DS(getActivity());
    

    当片段对象被实例化时,它还没有附加到活动上,getActivity() 返回null。将 Score_DS 实例化推迟到例如onAttach() 或片段生命周期中的更高版本。

    【讨论】:

      猜你喜欢
      • 2019-02-05
      • 2011-08-05
      • 1970-01-01
      • 1970-01-01
      • 2011-10-30
      • 2018-10-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多