I'm trying to read data out of a database I created, but I always get a NullPointerException when trying to fetch all my records.
I practically copypasted the code from another application I have running perfectly, but somehow I'm doing it wrong here.
The NullPointerException is at the line of
return mDb.query(DATABASE_TABLE_LOCALLOGIN, new String[] {LOCALLOGIN_ID, LOCALLOGIN_LOGIN, LOCALLOGIN_PASSWORD}, null, null, null, null, null);
Here's the relevant code (don't mind the string arrays, its for adding tables later on: GoingOutDbAdapter.java
public class GoingOutDbAdapter {
private static final String DATABASE_NAME = "GoingOutData";
private static final String DATABASE_TABLE_LOCALLOGIN = "LocalLogin";
public static final String LOCALLOGIN_ID = "LocalLogin_id";
public static final String LOCALLOGIN_LOGIN = "Login";
public static final String LOCALLOGIN_PASSWORD = "Password";
private static final String TAG = "Debugstring";
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
private static final String[] DATABASE_CREATE = {
"CREATE Table " + DATABASE_TABLE_LOCALLOGIN + " ( "
+ LOCALLOGIN_ID + " integer PRIMARY KEY Autoincrement, "
+ LOCALLOGIN_LOGIN + " text NOT NULL, "
+ LOCALLOGIN_PASSWORD + " text NOT NULL );"};
private final Context mCtx;
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
for(int i = 0; i < DATABASE_CREATE.length; i++){
Log.d(TAG,DATABASE_CREATE[i]);
db.execSQL(DATABASE_CREATE[i]);
}
}
}
public GoingOutDbAdapter(Context ctx) {
this.mCtx = ctx;
}
public GoingOutDbAdapter open() throws SQLException {
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}
public void close() {
mDbHelper.close();
}
public Cursor fetchAllLocalLogins() {
return mDb.query(DATABASE_TABLE_LOCALLOGIN, new String[] {LOCALLOGIN_ID, LOCALLOGIN_LOGIN, LOCALLOGIN_PASSWORD}, null, null, null, null, null);
}
}
MyActivity.java, where I call fetchAllLocalLogins
public class MyActivity extends Activity {
/** Called when the activity is first created. */
private GoingOutDbAdapter mDbHelper;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mDbHelper = new GoingOutDbAdapter(this);
setContentView(R.layout.main);
Cursor localLogin = mDbHelper.fetchAllLocalLogins();
}
}
You'll probably want to call the open()
method before you make the query:
//...
mDbHelper.open(); //whitout this call mdb will be NULL
Cursor localLogin = mDbHelper.fetchAllLocalLogins();
You should open the database before performing the database operation. mDbHelper.open();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With