错误显示java.lang.NullPointerException的方法getReadableDatabase() [英] Error java.lang.NullPointerException on method getReadableDatabase()
本文介绍了错误显示java.lang.NullPointerException的方法getReadableDatabase()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
能否请你帮我错误显示java.lang.NullPointerException。我使用自定义列表preference显示来自数据库元素。有两个文件CustomList preference.java和DbHelper.java
Could you please help me with error "java.lang.NullPointerException". I use custom listpreference to show elements from database. There two files CustomListPreference.java and DbHelper.java
CustomList preference.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
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);
}
}
推荐答案
由于您的 mContext
是空
这个地方里面行任何constructor..or使用之前,你的其他preferece方法
place this line inside constructor..or any of your other preferece methods before using it
dbHelp = new DbHelper(context);
这篇关于错误显示java.lang.NullPointerException的方法getReadableDatabase()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文