I’m trying to populate a list view from a SQLite db I can create the db and add items to it and display them in a TextView but for some reason not on a ListView
Is it that sData is the wrong type of object?
Can anyone help, please?
public void DBTest() {
SQLiteDatabase myDB = null;
String TableName = "myTable";
/* Create a Database. */
try {
myDB = this.openOrCreateDatabase(DATABASE_NAME, MODE_PRIVATE, null);
/* Create a Table in the Database. */
myDB.execSQL("CREATE TABLE IF NOT EXISTS "
+ TableName
+ " (_id integer primary key autoincrement, name text, script text, su short);");
/* Insert data to a Table*/
myDB.execSQL("INSERT INTO "
+ TableName
+ " (name, script, su)"
+ " VALUES ('hello', 'reboot', 1);");
/*retrieve data from database */
Cursor c = myDB.rawQuery("SELECT * FROM " + TableName, null);
int Column1 = c.getColumnIndex("name");
int Column2 = c.getColumnIndex("script");
int Column3 = c.getColumnIndex("su");
// Check if our result was valid.
c.moveToFirst();
String sData="";
if (c != null) {
// Loop through all Results
do {
String Name = c.getString(Column1);
String Script = c.getString(Column2);
int su = c.getInt(Column3);
sData = sData + Name + " " + Script + " " + su + "\n";
} while (c.moveToNext());
}
ListView lv = (ListView) findViewById(R.id.mainListView);
lv.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_single_choice, sData));
} catch (Exception e) {
Log.e("Error", "Error", e);
} finally {
if (myDB != null)
myDB.close();
}
}
You will end up with a
ListViewwith just one single item, the value ofsData. You need to create a list such as:I also recommend you change your cursor looping to be similar to this:
because at the moment you are not checking the return value of
moveToFirst, and it may return false (meaning there are no rows), however your do-while loop means the cursor will be read at least once whether or not it has 0 rows, and if there are 0 rows, you app will crash.