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);
Related
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)
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
I'm new to android. What i'm trying to do is to populate a listview from my sqlite database.I know how to do it using arrays. Can somebody help me doing this? I know there is a away to adapt the following code and using it for populating the listview using SQLite but i don't know how to do it.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_item);
final ListView lt = (ListView)findViewById(R.id.ListView01);
List<String> w= new ArrayList<String>();
ArrayAdapter<String> aa;
w.add("waka");
w.add("weka");
w.add("woka");
aa = new ArrayAdapter<String>(this, R.layout.listW, w);
lt.setAdapter(aa);
lt.setTextFilterEnabled(true);
lt.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
final String aux= (String) lt.getItemAtPosition(position);
Intent myIntent = new Intent(infoList.this, tabList.class);
startActivity(myIntent);
}});
}
Thanks
The best way to poputaling a ListView with data is using Content Providers: http://developer.android.com/guide/topics/providers/content-providers.html
Using content providers will you safe headaches regarding open/close operation for the database.
You can use SimpleCursorAdapter.
Image you have a list view (named 'list_item') item with two fields having ids txtOne and txtTwo respectively. Also, you are having a database table with tow fields - field1 and field2.
When you sgolud use the following adapter call.
SimpleCursorAdapter adapter = new SimpleCursorAdapter(
ctx,
R.layout.list_item,
getContentResolver().query(....), // getting cursor for database query here.
new String[] { "field1", "field2" },
new int[] { R.id.txtOne, R.id.txtTwo }
);
This adapter will map a text from field1 to txtOne and from field2 to txtTwo.
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.
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();