Putting Cursor Data Into An Array
Being new in Android, I am having trouble dealing with the following: public String[] getContacts(){ Cursor cursor = getReadableDatabase().rawQuery('SELECT name FROM contacts',
Solution 1:
names.add(cursor.getString(i));
"i" is not the cursor row index, it's the column index. A cursor is already positioned to a specific row. If you need to reposition your cursor. Use cursor.move or moveToXXXX (see documentation).
For getString/Int/Long etc. you just need to tell the cursor which column you want. If you don't know the columnIndex you can use cursor.getColumnIndex("yourColumnName")
.
Your loop should look like this:
publicString[] getContacts(){
Cursor cursor = getReadableDatabase().rawQuery("SELECT name FROM contacts", null);
cursor.moveToFirst();
ArrayList<String> names = newArrayList<String>();
while(!cursor.isAfterLast()) {
names.add(cursor.getString(cursor.getColumnIndex("name")));
cursor.moveToNext();
}
cursor.close();
return names.toArray(newString[names.size()]);
}
Solution 2:
I hope its useful to you.
publicstatic ArrayList<ModelAgents> SelectAll(DbHelper dbaConnection) {
ArrayList<ModelAgents> Agents_aList = newArrayList<ModelAgents>();
SQLiteDatabasesqldb= dbaConnection.openDataBase();
Cursorcursor= sqldb.rawQuery("SELECT * FROM Agents", null);
if (cursor != null)// If Cursordepot is null then do// nothing
{
if (cursor.moveToFirst()) {
do {
// Set agents information in model.ModelAgentsAgents=newModelAgents();
Agents.setID(cursor.getInt(cursor
.getColumnIndex(TblAgents.ID)));
Agents.setCode(cursor.getString(cursor
.getColumnIndex(TblAgents.CODE)));
Agents.setName(cursor.getString(cursor
.getColumnIndex(TblAgents.NAME)));
Agents_aList.add(Agents);
} while (cursor.moveToNext());
}
cursor.close();
}
sqldb.close();
return Agents_aList;
}
Solution 3:
use this:
if (cursor != null && cursor.getCount()>0){
cursor.moveToFirst();
do{
for(int i = 0; i < cursor.getCount(); i ++){
names.add(cursor.getString(i));
}
}while(cursor.moveToNext());
}
cursor.close();
Solution 4:
Try to put the data into the ArrayList<String>
as below:
publicArrayList<String> getContacts(){
Cursor cursor = getReadableDatabase().rawQuery("SELECT name FROM contacts", null);
ArrayList<String> names=newArrayList<String>();
if (cursor != null)
{
if (cursor.moveToFirst()) {
for(int i = 0; i < cursor.getCount(); i ++){
names.add(cursor.getString(i));
}
}
cursor.close();
}
return names;
}
Post a Comment for "Putting Cursor Data Into An Array"