方法getReadableDatabase()上的java.lang.NullPointerException错误

时间:2013-12-21 12:27:57

标签: android sqlite listpreference

你可以帮我解决错误“java.lang.NullPointerException”。我使用自定义列表首选项来显示数据库中的元素。有两个文件CustomListPreference.java和DbHelper.java

CustomListPreference.java

public class CustomListPreference extends ListPreference {
    CustomListPreferenceAdapter customListPreferenceAdapter = null;
    Context mContext;

private SQLiteDatabase db;
DbHelper dbHelp = new DbHelper(mContext);

public CustomListPreference(Context context, AttributeSet attrs)
{
    super(context, attrs);
    mContext = context;
    mInflater = LayoutInflater.from(context);

}

@Override
protected void onPrepareDialogBuilder(Builder builder)
{

    ...

    try {
    db = dbHelp.getReadableDatabase();//I get error java.lang.NullPointerException
  ...
}

DbHelper.java

   import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DbHelper extends SQLiteOpenHelper {
    static String DATABASE_NAME="myBase";
    public static final String KEY_NAME="name";
    public static final String KEY_ID="id";

    public DbHelper(Context context) {
        super(context, DATABASE_NAME, null, 1);
    }

@Override
public void onCreate(SQLiteDatabase db) {
     db.execSQL("create table tUser ("
              + "id integer primary key autoincrement," 
              + "name text,"
              + "exists integer" + ");");

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
    onCreate(db);

}

}

2 个答案:

答案 0 :(得分:8)

因为您的mContextnull

在使用它之前将此行放在构造函数或任何其他优先方法中

dbHelp = new DbHelper(context);

答案 1 :(得分:2)

Context mContext;

private SQLiteDatabase db;
DbHelper dbHelp = new DbHelper(mContext);

您传递给mContext构造函数的DbHelpernull

无论如何,您不应该初始化需要有效Context的任何类成员,直到onCreate()