Reputation: 1
First of all i'm new to Android Development. I'm having some issues with fetching data from database. Whenever i try to fetch a data, the cursor is being empty.
Here is my code:
public ArrayList<Word> getWords(){
SQLiteDatabase db = this.getReadableDatabase();
String query = "SELECT * FROM " + TABLE_NAME;
Cursor cursor = db.rawQuery(query, null);
ArrayList<Word> List = new ArrayList<Word>();
if(cursor != null){
cursor.moveToFirst();
while (cursor.moveToNext()){
List.add(new Word(cursor.getString(cursor.getPosition())));
}
}
cursor.close();
db.close();
return List;
}
The size of the cursor is always 1 but the size of the "List" variable is always 0.
I didn't understand the problem, thanks for helping me.
Upvotes: 0
Views: 134
Reputation: 1
I feel like a idiot because i forgot to type the database name at the constructor method like that:
Old
super(context, null, null, 1);
Now
super(context, "database", null, 1);
Thanks for your help!
Upvotes: 0
Reputation: 1
I just realised that the program does not go into the while loop in the code that i given above. I think there is a problem with database.
I used that query to create database:
private static final String SQL_CREATE_ENTRIES =
"CREATE TABLE " + TABLE_NAME + " (" +
COLUMN_NAME_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_NAME_TURKISH + " TEXT, " +
COLUMN_NAME_ENGLISH + " TEXT, " +
COLUMN_NAME_GERMAN + " TEXT, " +
COLUMN_NAME_FRENCH + " TEXT, " +
COLUMN_NAME_ARABIC + " TEXT, " +
COLUMN_NAME_RUSSIAN + " TEXT, " +
COLUMN_NAME_SPANISH + " TEXT, " +
COLUMN_NAME_ITALIAN + " TEXT)";
Upvotes: 0
Reputation: 1701
Try like this
public ArrayList<Word> getWords(){
SQLiteDatabase db = this.getReadableDatabase();
String query = "SELECT * FROM " + TABLE_NAME;
Cursor cursor = db.rawQuery(query, null);
ArrayList<Word> list = new ArrayList<Word>();
if(cursor != null){
while (cursor.moveToNext()){
list.add(new Word(cursor.getString(cursor.getPosition())));
}
}
cursor.close();
db.close();
return list;
}
Upvotes: 0
Reputation: 1
I checked everything but your recommendations didn't worked. Just to be sure: I want to fetch all rows.
Upvotes: 0
Reputation: 581
you can use this code:
1-If you need first row:
if(cursor != null){
cursor.moveToFirst();
if(cursor.isAfterLast() == false){
List.add(new Word(cursor.getString(cursor.getPosition())));
}
}
2- if you need several rows :
if(cursor != null){
cursor.moveToFirst();
while (cursor.isAfterLast() == false) {
List.add(new Word(cursor.getString(cursor.getPosition())));
cursor.moveToNext();
}
}
Upvotes: 0
Reputation: 13
You are shifting the cursor position twice. Just remove the line cursor.moveToFirst(); The moveToNext method is sufficient as it moves to the first position on the first iteration.
Upvotes: 1