如何从数据库获取数据列表到微调器
How to get list of data from database to spinner
我想让我的用户 table 的所有用户名显示在我的微调器中以供选择,但它没有显示我列表中的所有用户名,而是只显示一个,它是我数据库中的第一个用户..我怎样才能得到所有的用户名?
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) {
}
});
提前致谢..
您实际上并没有在数组中累积任何值。每次循环时都会创建一个新数组。
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
。您可以直接从您的光标创建一个适配器,这样您就不需要编写循环代码。
我想让我的用户 table 的所有用户名显示在我的微调器中以供选择,但它没有显示我列表中的所有用户名,而是只显示一个,它是我数据库中的第一个用户..我怎样才能得到所有的用户名?
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) {
}
});
提前致谢..
您实际上并没有在数组中累积任何值。每次循环时都会创建一个新数组。
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
。您可以直接从您的光标创建一个适配器,这样您就不需要编写循环代码。