我想让我的用户表中的所有用户名都显示在我的微调器中以供选择,但不是显示我列表中的所有用户名,而是只显示一个来自我数据库的第一个用户..我怎样才能获得所有用户名?
String q = "SELECT * FROM " + User.TABLE;
Cursor cursor = dbHelper.getReadableDatabase().rawQuery(q, null);
String[] ComRep = new String[0];
if (cursor.moveToFirst()) {
String rep = cursor.getString(cursor.getColumnIndex(User.KEY_username));
do {
ComRep = new String[]{rep};
} while (cursor.moveToNext());
}
cursor.close();
Comrep = (Spinner) findViewById(R.id.spincomrep);
ArrayAdapter<CharSequence> adapterrep = new ArrayAdapter<CharSequence>(this, R.layout.spinner_item, ComRep);
adapterrep.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Comrep.setAdapter(adapterrep);
Comrep.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Comrep.setSelection(position);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
提前感谢..
答案 0 :(得分:1)
您实际上并未在数组中累积任何值。每次循环时都会创建一个新数组。
ArrayList<String> values = new ArrayList<String>();
while (cursor.moveToNext()) {
String rep = cursor.getString(cursor.getColumnIndex(User.KEY_username));
values.add(rep);
}
cursor.close();
ArrayAdapter<CharSequence> adapterrep = new ArrayAdapter<CharSequence>(this, R.layout.spinner_item, values.toArray(new String[values.size]));
你应该看看CursorAdapter
。您可以直接从光标创建适配器,这样就不需要对循环进行编码。