I’m trying to use an SQLite database to store some data for my app. I’ve got this in my DbHelper class (which extends SqLiteOpenHelper)
// Database creation sql statement
private static final String DATABASE_CREATE = "create table "
+ jarsTable + "( "+colID+" integer primary key autoincrement, "+colName+" varchar(100), " +
colGoal+" real not null, "+colBal+" real not null, "+colCurr+" varchar(100));";
public DbHelper(Context context) {
super(context, dbName, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase database) {
database.execSQL(DATABASE_CREATE);
}
And I’ve got this inside my DataSource class
private Jar cursorToJar(Cursor cursor) {
Jar myJar = new Jar();
myJar.setId(cursor.getLong(0));
myJar.setName(cursor.getString(1));
myJar.setBalance(cursor.getDouble(2));
myJar.setGoal(cursor.getDouble(3));
myJar.setCurrency(cursor.getString(4));
return myJar;
}
And I get the error I mentioned in the question title, which crashes the app, when it reaches the line myJar.setName above. I’m really a bit confused as to where I’ve gone wrong, I’m getting a string, and my table is storing a field at column 1, I think, so.. yeah. Thanks for the help, in advance
EDIT: Here’s my population method:
public Jar createJar(String name, double goal, String currency) {
ContentValues values = new ContentValues();
values.put(DbHelper.colName, name);
values.put(DbHelper.colGoal, goal);
values.put(DbHelper.colCurr, currency);
values.put(DbHelper.colBal, 0.0);
long insertId = database.insert(DbHelper.jarsTable, null,
values);
Log.d("Insert ID:", ""+insertId);
// To show how to query
Cursor cursor = database.query(DbHelper.jarsTable,
allColumns, DbHelper.colID + " = " + insertId, null,
null, null, null);
cursor.moveToFirst();
return cursorToJar(cursor);
}
Always use the cursor’s
getColumnIndex()method to access columns. Like so:Not saying that’s absolutely the issue — since you haven’t shown how the
Cursorwas populated — but it’s likely.