spinner selected item - android

I've been reading stuff about this for hours and still haven't figured out how to do it.
I managed to populate a spinner from a cursor reading the database and now I'm trying to get the selected item on the spinner to help fill a listview.
Here's my code:
Cursor cursorpf = DatabaseHelper.getPFunc();
startManagingCursor(cursorpf);
Spinner spinnerpf = (Spinner) findViewById(R.id.spinner1);
String[] frompf = new String[] { "Designacao" };
int[] topf = new int[] { android.R.id.text1 };
SimpleCursorAdapter scaPFunc = new SimpleCursorAdapter(this,
android.R.layout.simple_spinner_item, cursorpf, frompf, topf);
scaPFunc
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerpf.setAdapter(scaPFunc);
spinnerpf.setOnItemSelectedListener(new MyOnItemSelectedListener());
final String stringpf = MyOnItemSelectedListener.getSelected();
long id = spinnerpf.getSelectedItemId();
String stringpf = String.valueOf(id);
DatabaseHelper.setPF(stringpf);
MyOnItemSelectedListener class:
public class MyOnItemSelectedListener implements OnItemSelectedListener {
private static String selected = "";
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
selected = String.valueOf(id);
Toast.makeText(parent.getContext(), "Escolha: " + selected, Toast.LENGTH_LONG).show();
}
#SuppressWarnings("unchecked")
public void onNothingSelected(AdapterView parent) {
// Do nothing.
}
}
The toast on this class returns the cursor position. Now, I know I must compare it against the database to get the value I want, but I just can't do it. Would you please help me out?
Thanks in advance.
Edit:
Guys, would you help me out?
I managed to get the selected item by implementing the code above, but it happens that the listview is only filled when the app starts. When I select something on the spinner, nothing happens. :|

If you want to retrieve selected item from database, just pass the fourth argument of onItemSelected (id) to you SQL query. It's the row id of the record, aka _ID.

Related

AutoCompleteTextView with SimpleCursorAdapter does not filter

In my app, I have a few AutoCompleteTextView widgets that use an ArrayAdapter.
private List<String> adapterList = new ArrayList<String>();
ArrayAdapter<String> dropdownAdapter;
dropdownAdapter = new ArrayAdapter<>(getContext(), R.layout.simple_dropdown_item, adapterList);
autoCompleteTextView.setAdapter(dropdownAdapter);
It works beautifully. As I type into the View, I get words-starting-with results in the dropdown.
I want to do this with another AutoCompleteTextView, but this time using a SimpleCursorAdapter.
nameSearchCursor = dbHelper.getChecklistTabDataByChecklistId(outingId, checklistId, nameColumn);
NameSearch = root.findViewById(R.id.SearchNames);
String[] nsColumns = new String[]{nameColumn};
int[] nsTo = new int[]{R.id.simpleDropdownItem};
nameSearchCursorAdapter = new SimpleCursorAdapter(getContext(), R.layout.simple_dropdown_item,
nameSearchCursor, nsColumns, nsTo, 0);
NameSearch.setAdapter(nameSearchCursorAdapter);
If I start typing in this new View, the dropdown appears and shows the entire list, and nothing changes as I type. No filtering occurs. What do I need to do differently (and perhaps why) to get a CursorAdapter to work with this View that I didn't need to do when using an ArrayAdapter. I have searched this site and read the Developer Docs and there must be something I just don't get. Please enlighten me.
This site allowed me to answer this question: http://www.outofwhatbox.com/blog/2010/11/android-simpler-autocompletetextview-with-simplecursoradapter/
Here is my completed code:
private void setUpNameSearch() {
// Get AutoCompleteTextView
nameSearchView = root.findViewById(R.id.SearchNames);
// Define from/to info
final String[] nsColumns = new String[]{nameColumn};
final int[] nsTo = new int[]{R.id.simpleDropdownItem};
// Create adapter. Cursor set in setFilterQueryProvider() below.
nameSearchCursorAdapter = new SimpleCursorAdapter(getContext(), R.layout.simple_dropdown_item,
null, nsColumns, nsTo, 0);
// Set adapter on view.
nameSearchView.setAdapter(nameSearchCursorAdapter);
// OnItemClickListener - User selected value from DropDown
nameSearchView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> listView, View view, int position, long id) {
// Get the cursor. Positioned to the corresponding row in the result set.
Cursor cursor = (Cursor) listView.getItemAtPosition(position);
// Get the name selected
String selectedName = cursor.getString(cursor.getColumnIndexOrThrow(nameColumn));
// Do something with this value...
}
});
// Set the CursorToStringconverter, to provide the values for the choices to be displayed
// in the AutoCompleteTextview.
nameSearchCursorAdapter.setCursorToStringConverter(new SimpleCursorAdapter.CursorToStringConverter() {
#Override
public CharSequence convertToString(Cursor cursor) {
final String name = cursor.getString(cursor.getColumnIndexOrThrow(nameColumn));
return name;
}
});
// Set the FilterQueryProvider, to run queries for choices
nameSearchCursorAdapter.setFilterQueryProvider(new FilterQueryProvider() {
#Override
public Cursor runQuery(CharSequence constraint) {
Cursor cursor = dbHelper.getMatchingNames(outingId, checklistId, nameColumn,
(constraint != null ? constraint.toString() : null));
return cursor;
}
});
}
I wanted to duplicate the word-starting-with default functionality of the AutoCompeteTextView using the SQLite Cursor, only to find that REGEXP are not fully supported. So this StackOverflow topic gave me the LIKE workaround. SQLite LIKE alternative for REGEXP, Match Start of Any Word
I hope this helps others.

Add a "Please Select" option to a Spinner in Android

I have a Spinner which is filled from a query using a SimpleCursorAdapter, this works fine... but now I need to put an option "Please Select" before all the items retrieved from the query, just for usability issues... but I'm not quite sure of how to do so... HELP please...
Here is my code...
private Spinner comboForm;
...
comboForm = (Spinner) findViewById(R.id.comboFormularios);
...
mDbH.abrir();
final Cursor cu = mDbH.consultaFormularios(idU);
if(cu.moveToFirst() == false){
cu.close();
mDbH.cerrar();
}else{
SimpleCursorAdapter adapter2 = new SimpleCursorAdapter(getApplicationContext(),R.layout.spinner,cu,new String[] {"nombre"},new int[] {R.id.textoCombo});
adapter2.setDropDownViewResource(R.layout.simple_spinner_dropdown_item);
comboForm.setAdapter(adapter2);
}
mDbH.cerrar();
...
comboForm.setOnItemSelectedListener(new OnItemSelectedListener(){
public void onItemSelected(AdapterView<?> parentView, View selectedItemView,int position, long id) {
idF = (int) id;
obtenerDatosRutas(idU,idF);
tabla.removeAllViews();
llenarTabla();
}
public void onNothingSelected(AdapterView<?> arg0) {}
});
Where mDbH is an instance of the class I'm using to manipulate the Database... as you can see the Spinner is filled up from Cursor resulting of the query consultaFormularios(idU)
When you create your cursor, one possible solution would be to use a SQL UNION and construct second SELECT that simply contains the label you need (adding hard-coded dummy fields for ordering).
Alternatively, and this is most likely the simplest solution. Instead of using a cursor adapter, use an array adapter and start by populating the array with your default value you want, then stick in all the items from your cursor. Something like,
ArrayList<String> arrayList = new ArrayList<String>();
arrayList.add("Please select");
final Cursor cu = mDbH.consultaFormularios(idU);
while(cu.moveToNext()) {
arrayList.add(cu.getString(0)); // assuming you want a
//string from the first column
}
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, arrayList);
comboForm.setAdapter(spinnerArrayAdapter);

Get item selected of a spinner when its filled up from a database cursor

In my Android App I hava a layout with to Spinners. What I want to do is given a selected item from the first spinner, fill up the second one.
The first spinner is filled up from a cursor (result of a database query) like this:
Spinner combo1 = (Spinner) findViewById(R.id.combo1);
mDbH.open();
Cursor c1 = null;
c1 = mDbH.consulta4();
startManagingCursor(c1);
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,android.R.layout.simple_spinner_item,c1,new String[] {"nombre"},new int[] {android.R.id.text1});
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
combo1.setAdapter(adapter);
This works fine! The problem comes inside my event listener:
combo1.setOnItemSelectedListener(new OnItemSelectedListener(){
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
String est = String.valueOf(combo1.getSelectedItem());
int idEst = (int) id;
Log.e("est",est);
Log.e("idEst",""+idEst);
mDbH.open();
Cursor c = null;
c = mDbH.consulta5(idEst,est);
SimpleCursorAdapter adapter2 = new SimpleCursorAdapter(getApplicationContext(),android.R.layout.simple_spinner_item,c,new String[] {"nombre"},new int[] {android.R.id.text1});
adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
combo1.setAdapter(adapter2);
}
public void onNothingSelected(AdapterView<?> arg0) {}
});
Because, in the LogCat the line Log.e("est",est); shows this:
10-25 09:48:50.390: E/est(3462): android.database.sqlite.SQLiteCursor#40625638
And of course, that value is not in my database and the second cursor is empty and the spinner doesn't fill up with anything!! So, this is my question, how do you get the item selected of a spinner when is filled up from a database? I also tried out:
String est = combo1.getSelectedItem().toString();
and
String est = parentView.getItemAtPosition(position).toString();
but the result is the same!! Am I doing something wrong? Please help!
Thanks!
Since your Spinner was filled out using a SimpleCursorAdapter, getItemAtPosition & getSelectedItem will return a Cursor reference. Use:
Cursor c=(Cursor) combo1.getSelectedItem();
String est=c.getString(c.getColumnIndex("nombre");
Same works for getItemAtPosition(position)

How to retrieve an ID of the selected item in a dynamic Spinner?

I have a spinner which is populated with Category objects that are retrieved from the db. The Categories table has _id and category_name columns. I want to show the category name in the spinner, but when the user selects an item, I need it to retrieve the selected item's ID. I tried the following:
Declaring variables (in class level):
int currCategoryId;
ArrayAdapter<String> adapter;
NotesManager manager = new NotesManager(this);
ArrayList<Category> arrListCategories;
ArrayList<String> arrListCategoriesString = new ArrayList<String>();
Spinner spCategories;
Instantiating them in onCreate method:
manager.getAllCategories();
arrListCategories = manager.getAllCategories();
for (int i = 0; i < arrListCategories.size(); i++)
{
Category currCategory = arrListCategories.get(i);
arrListCategoriesString.add(currCategory.getCategory_name().toString());
}
adapter=new ArrayAdapter<String> (this, android.R.layout.simple_spinner_item, arrListCategoriesString);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spCategories.setAdapter(adapter);
spCategories.setOnItemSelectedListener(spinnerListener);
And this is the spinnerListener I tried:
OnItemSelectedListener spinnerListener = new OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
// An item was selected.
//currCategory = (String) parent.getItemAtPosition(pos).toString();
//selectedCategory =
Category selectedCategory = (Category)spCategories.getItemAtPosition(pos);
currCategoryId = selectedCategory.getId();
}
public void onNothingSelected(AdapterView<?> arg0) {
}
};
But in this case the app crashes and I'm getting a "
String cannot be cast to Category" at this line: Category
selectedCategory = (Category)spCategories.getItemAtPosition(pos);
I also tried this:
currCategoryId = view.getId();
But then instead of 1 or 2 (depending on what category I selected, currently I have 2 of them), I'm getting a very long number...
How can I fix it? How can I retrieve the ID of the selected object?
I would use a SimpleCursorAdapter because it stores multiple columns, instead of an ArrayAdapter that only stores one.
First change NotesManager.getAllCategories() to return a Cursor that uses:
"SELECT _id, category_name FROM Table;"
You could alphabetize the results if you want:
"SELECT _id, category_name FROM Table ORDER BY category_name;"
Next bind this Cursor straight to your Spinner:
Cursor cursor = manager.getAllCategories();
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, cursor, new String[] {"category_name"}, new int[] {android.R.id.text1});
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spCategories.setAdapter(adapter);
Finally in your OnItemSelectedListener everything is ready and waiting:
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
// The parameter id already refers to your Category table's id column,
}
No extra get() calls or converting Cursors into Lists necessary!
You can't use the ArrayAdapter anyway because it's for Strings only (not Categories). Hence why you're getting a casting exception. Since you have your Category ArrayList and your String ArrayList (which is used for the ArrayAdapter) in the same order, just use
Category selectedCategory = arrListCategories.get(pos);
in your onItemSelected() method

Android how to get selected item from data driven spinner

Newbie question. I'm using a SimleCursorAdapter to populate a spinner from an SQLite table, as shown in the Android dev docs:
Spinner list=(Spinner)findViewById(R.id.cboModel);
SimpleCursorAdapter ModelAdapter = new SimpleCursorAdapter(this,
android.R.layout.simple_spinner_item, model,
new String[] {"Drug"},
new int[] {android.R.id.text1});
ModelAdapter.setDropDownViewResource(
android.R.layout.simple_spinner_dropdown_item);
list.setAdapter(ModelAdapter);
list.setOnItemSelectedListener(onModelSelect);
I've set up a listener, but I can't figure out how to get the selected item text, it pulls up the SQLiteCursor, not the actual text in the spinner.
private AdapterView.OnItemSelectedListener
onModelSelect= new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?>
parent, View view, int position, long id) {
ModelName = parent.getSelectedItem().toString();
android.util.Log.w("OnItemSelect.cboModel", ModelName);
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
};
Google turns up the question on several message boards, but no answers, so it appears to be a common newbie question. It may be painfully obvious to some, but if you could point me in the right direction I would appreciate it. Thank you.
Since the selected item is a Cursor, you can easily get the value by calling getString with the index of the column in the original database query that you used to populate the Spinner.
String spinnerString = null;
Cursor cc = (Cursor)(yourSpinner.getSelectedItem());
if (cc != null) {
spinnerString = cc.getString(
cc.getColumnIndex("Drug"));
}
This technique definitely works when the Spinner is populated from the database. I have not tried it with a resource array.
Figured it out... get the id, then make a DB query:
String id_string = String.valueOf(id);
thismodel=Pkmodel.getById(id_string, dbModel);
ModelName=thismodel.getDrug();

Categories

Resources