我是SQLite的新手,我正试图将'name'列中的所有数据显示到Android Studio中的ListView中。但是,我在ListView中显示“名称”和“年龄”数据。以下是我目前的代码。
usersScreen.java
private void populateListView() {
Log.d(TAG, "populateListView: Displaying data in the ListView.");
//get the data and append to a list
Cursor data = mDatabaseHelper.getData();
ArrayList<String> listData = new ArrayList<>();
while (data.moveToNext()) {
//get the value from the database in column 1
//then add it to the ArrayList
listData.add(data.getString(data.getColumnIndex( "name" )));
}
//create the list adapter and set the adapter
ListAdapter adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, listData);
mListView.setAdapter(adapter);
}
DatabaseHelper.java
public Cursor getData(){
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT " + COL2 + " FROM " + TABLE_NAME;
Cursor data = db.rawQuery(query, null);
return data;
}
public Cursor getItemID(String name){
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT " + COL1 + " FROM " + TABLE_NAME +
" WHERE " + COL2 + " = '" + name + "'";
Cursor data = db.rawQuery(query, null);
return data;
}
public boolean addDataName(String item) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL2, item);
Log.d(TAG, "addData: Adding " + item + " to " + TABLE_NAME);
long result = db.insert(TABLE_NAME, null, contentValues);
//if date as inserted incorrectly it will return -1
if (result == -1) {
return false;
} else {
return true;
}
}
非常感谢