user3082303 user3082303 - 2 months ago 6x
Android Question

Error java.lang.NullPointerException on method getReadableDatabase()

Could you please help me with error "java.lang.NullPointerException". I use custom listpreference to show elements from database. There two files and

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


protected void onPrepareDialogBuilder(Builder builder)


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

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

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


public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {




because your mContext is null

place this line inside constructor..or any of your other preferece methods before using it

dbHelp = new DbHelper(context);