While accessing SQLite from non-activity class, getting NullPointerException
File -> SessionDB.java
public class SessionDB {
private SQLiteDatabase database;
private SQLiteHelper dbHelper;
private String[] allColumns = { SQLiteHelper.SESSION_ID,
SQLiteHelper.SESSION_STRING };
public SessionDB(Context context) {
dbHelper = new SQLiteHelper(context);
}
public void open() throws SQLException {
database = dbHelper.getWritableDatabase();
}
public void createSession(String session_string) {
ContentValues values = new ContentValues();
values.put(SQLiteHelper.SESSION_STRING, session_string);
database.insert(SQLiteHelper.SESSION_TABLE, null, values); // NullPointerException Here
}
}
File ->Live.java
public class Live {
protected Context context;
public Live(Context context) {
this.context = context;
}
public accessOK {
SessionDB ses = new SessionDB(context);
ses.createSession("Sample"); // NullPointerException
}
}
Then, what should be the best way to do this?
You don't seem to be calling SessionDB.open() anywhere. This means that your database field is never being initialized, so is null when you call SessionDB.createSession().