Answer the question
In order to leave comments, you need to log in
How to display desired row in Spinner from sqlite db in android?
There is a code that loads a list from the database into a spinner
private static final String DB_NAME = "ovis_mill.sqlite3";
//Заданее имена полей БД константами
private static final String TABLE_NAME = "baudratespinner";
private static final String BAUDRATE_ID = "_id";
private static final String BAUDRATE_NAME = "baudrate";
private static final String BAUDRATE_SELECTED = "selected";
private SQLiteDatabase database;
private ArrayList baudrate;
Spinner BaudrateSpinner;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.general_settings);
// Находим елементы
BaudrateSpinner = (Spinner) findViewById(R.id.BaudrateSpinner);
//Наш ключевой хелпер
ExternalDbOpenHelper dbOpenHelper = new ExternalDbOpenHelper(this, DB_NAME);
database = dbOpenHelper.getWritableDatabase();
//Все, база открыта!
// Загрузка данных спинера с БД
loadSpinnerBaudrateData();
//Используем адаптер и стандартный layout элемент для краткости
ArrayAdapter<String> BaudratedataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, baudrate);
BaudrateSpinner.setAdapter(BaudratedataAdapter);
}
// Загружаем с БД даныые и заносим их в список
private void loadSpinnerBaudrateData() {
baudrate = new ArrayList<String>();
Cursor baudrateCursor = database.query(TABLE_NAME,
new String[]{BAUDRATE_ID, BAUDRATE_NAME, BAUDRATE_SELECTED},
null, null, null, null,
BAUDRATE_NAME);
baudrateCursor.moveToFirst();
if (!baudrateCursor.isAfterLast()) {
do {
String name = baudrateCursor.getString(1);
baudrate.add(name);
} while (baudrateCursor.moveToNext());
}
baudrateCursor.close();
database.close(); // Закрываем БД
}
Answer the question
In order to leave comments, you need to log in
I don’t even know how to answer you - there are a lot of problems in your code, not a single solution fits normally. Let's say you can do this:
private String loadSpinnerBaudrateData() {
String selected;
baudrate = new ArrayList<String>();
Cursor baudrateCursor = database.query(TABLE_NAME,
new String[]{BAUDRATE_ID, BAUDRATE_NAME, BAUDRATE_SELECTED},
null, null, null, null,
BAUDRATE_NAME);
baudrateCursor.moveToFirst();
if (!baudrateCursor.isAfterLast()) {
do {
String name = baudrateCursor.getString(1);
if (baudrateCursor.getInt(baudrateCursor.getColumnIndex( BAUDRATE_SELECTED )) == 1){
selected = name;
}
baudrate.add(name);
} while (baudrateCursor.moveToNext());
}
baudrateCursor.close();
database.close(); // Закрываем БД
return selected;
}
String compareValue = loadSpinnerBaudrateData();
int spinnerPosition = BaudratedataAdapter.getPosition(compareValue);
BaudrateSpinner.setSelection(spinnerPosition);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question