New to using databases, so not sure where my error lies to be honest. Here is my code:
Creating the database
private static final String DATABASE_CREATE =
"create table job_details (_id integer primary key autoincrement, "
+ "company text not null, advertised text, status text not null, position text not null, " +
"wage text, hours text, address text, " +
"email text, number text, notes text);";
@Override
public void onCreate(SQLiteDatabase db){
db.execSQL(DATABASE_CREATE);
}
Creating a row
public long createJob(String company, String advertised, String status, String position, String wage, String hours,
String address, String email, String number, String notes) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_COMPANY, company);
initialValues.put(KEY_ADVERTISED, advertised);
initialValues.put(KEY_STATUS, status);
initialValues.put(KEY_POSITION, position);
initialValues.put(KEY_WAGE, wage);
initialValues.put(KEY_HOURS, hours);
initialValues.put(KEY_ADDRESS, address);
initialValues.put(KEY_EMAIL, email);
initialValues.put(KEY_NUMBER, number);
initialValues.put(KEY_NOTES, notes);
return mDb.insert(DATABASE_TABLE, null, initialValues);
}
Getting a cursor to all rows in table
public Cursor fetchAllJobs() {
return mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_COMPANY,
KEY_ADVERTISED, KEY_STATUS, KEY_POSITION, KEY_WAGE, KEY_HOURS,
KEY_ADDRESS, KEY_EMAIL, KEY_NUMBER, KEY_NOTES}, null,
null, null, null, null);
}
Using cursor to log some of the attributes of all the rows
private void getAllData(){
Cursor c = mDbHelper.fetchAllJobs();
startManagingCursor(c);
do{
if(c.moveToFirst()){
String company;
String position;
String number;
int companyColumn = c.getColumnIndex(JobsDbAdapter.KEY_COMPANY);
int positionColumn = c.getColumnIndex(JobsDbAdapter.KEY_POSITION);
int numberColumn = c.getColumnIndex(JobsDbAdapter.KEY_NUMBER);
do{
company = c.getString(companyColumn);
position = c.getString(positionColumn);
number = c.getString(numberColumn);
}while(c.moveToNext());
Log.d(TAG, "Company is = "+company);
Log.d(TAG, "Position is = "+position);
Log.d(TAG, "Number is = "+number);
}
}while(c.moveToNext());
}
When I use this code, the output/logged values are just those contained in the last row that I tried to enter in the database. I am not sure if I am entering the data wrong, or looking up the database wrong.
This is incorrect:
When you want to read what a cursor is actually pointing to you don’t need to move it. A cursor points to the full record.
Also your if statment always move the cursor back to the first result. That’s probably why you were only seeing the first row. Try this instead.