Question

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

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

}

}

Was it helpful?

Solution

because your mContext is null

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

dbHelp = new DbHelper(context);

OTHER TIPS

Context mContext;

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

The mContext you passed to DbHelper constructor is null.

You should not initialize any class member requiring a valid Context until onCreate() anyway.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top