Reputation: 3562
I add data into a database using this code,
/**
* Storing deck
* */
public void addDeck(String id, String name, String uid, String did) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_DECK_ID, id); // ID
values.put(KEY_DECK_NAME, name); // Name
values.put(KEY_DECK_UID, uid); // Unique Id
values.put(KEY_DECK_DID, did); // Deck id
// Inserting Row
db.insert(TABLE_DECK, null, values);
db.close(); // Closing database connection
}
Now I want to be able to access each row, how can I do this?
This is my current code to access the rows in the database
// Getting deck data from database
public HashMap<String, String> getDeckDetails(){
HashMap<String,String> deck = new HashMap<String,String>();
String selectQuery = "SELECT * FROM " + TABLE_DECK;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// Move to first row
cursor.moveToFirst();
if(cursor.getCount() > 0){
deck.put("id", cursor.getString(1));
deck.put("name", cursor.getString(2));
deck.put("uid", cursor.getString(3));
deck.put("did", cursor.getString(4));
}
cursor.close();
db.close();
// return user
return deck;
}
This code only returns the first row, how can I get it to return every row?
Upvotes: 0
Views: 218
Reputation: 20699
you have to use a loop:
Cursor cursor = db.rawQuery(selectQuery, null);
while( cursor.moveToNext() ){
deck.put("id", cursor.getString(1));
deck.put("name", cursor.getString(2));
deck.put("uid", cursor.getString(3));
deck.put("did", cursor.getString(4));
}
cursor.close();
also, instead of cursor.getString(3)
I'd use:
int uidPos = cursor.getColumnIndex( "uid" );
if( -1 != uidPos ) cursor.getString( uidPos );
as it's safer
Upvotes: 1