How to pass the data in the database to a spinner - android

I'm creating a method to read all the information in the database and view it through a spinner here is the code i tried for this function
public Spinner loadArtist(){
SQLiteDatabase DB = getReadableDatabase();
String[] projection = {
ArtistMaster.Artist.ARTIST_NAME};
Cursor cursor = DB.query(
ArtistMaster.Artist.TABLE_ARTIST,
projection,
null,
null,
null,
null,
null);
Spinner itemIds = new ArrayList<>();
while(cursor.moveToNext()) {
long itemId = cursor.getLong(
cursor.getColumnIndex(ArtistMaster.Artist.ARTIST_NAME));
itemIds.setAdapter(itemId);
}
cursor.close();
return itemIds;
}
but it gives me an error in this line Spinner itemIds = new ArrayList<>();
Should i declare it as a list instead of spinner

itemIds should be defined as an ArrayList<Long>. A Spinner is a UI element and an ArrayList is a data structure. You will most likely need to map the data to your UI using an adapter of some sort, eg. an ArrayAdapter:
Spinner spinner = ... // findViewById, new Spinner() etc.
ArrayList<Long> itemIds = new ArrayList<>();
//... fill array with artist IDs
spinner.setAdapter(
new ArrayAdapter(
this, // Context, Activity etc.,
android.R.layout.simple_list_item_1, // Spinner TextView item resource ID
itemIds // Data set.
));
By default, ArrayAdapter will call Object#toString() on each data object in the collection.

I'd suggest that it would be easier if you used a Cursor Adpater as they are designed to be used with a Cursor and there is no need to generate arrays.
SimpleCursorAdapter being that, a simple but still pretty flexible adapter for use with Cursors.
The only issue is that a Cursor Adapter requires a column name specifically _id (BaseColumns._ID resolves to this (as used below)).
First have the following member variables (obviously names can be what you wish)
:-
Cursor mCursor;
SimpleCursorAdapter mAdapter;
Spinner spinner;
SQLiteDatabase db;
In the onCreate Method of the activity have
:-
spinner = this.findViewById(R.id.?????); //
db = ???????? (as per your existing code)
manageSpinner();
Have a method
:-
private void manageSpinner() {
mCursor = db.query(
ArtistMaster.Artist.ARTIST_NAME,
new String[]{"*","rowid AS " + BaseColumns._ID}, //<<<<<<<< adds _ID column (unless the table is a WITHOUT ROWID table, pretty unlikely)
null,null,null,null,null
);
if (mAdapter == null) {
mAdapter = new SimpleCursorAdapter(
this,
android.R.layout.simple_list_item_1,
mCursor,
new String[]{"the_column"}, // column(s) from which to extract data
new int[]{android.R.id.text1}, // layout views into which the data is placed
0
);
spinner.setAdapter(mAdapter);
// You want want to do something when an Item in the spinner is clicked (this does nothing as it is)
spinner.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//........... do your stuff here
// notes
// id will be the id of the row
// cursor will be positioned, so you can access data from the cursor if needed
}
});
} else {
mAdapter.swapCursor(mCursor);
}
}
Override the activity's onResume (refresh the spinner when returning to activity as underlying data may have changed) and onDestroy (to close the Cursor) methods using
:-
#Override
protected void onDestroy() {
super.onDestroy();
mCursor.close();
}
#Override
protected void onResume() {
super.onResume();
manageSpinner();
}

Related

Retrieve values from database and launch a new activity when listview item is clicked

I created a listview using an adapter. The list view contains elements retrieved from a SQLite database using a distinct query.
When the listview item is clicked, it should retrieve all items which have that value used to do the distinct query.
My query looks like this:
#Override
public List<Registro> distinctByCol3(){
List aux = new ArrayList();
Cursor cursor = db.query(true,Registro.TABLE_NAME,new String[]{
BaseColumns._ID,
RegistroColumns.Col1,
RegistroColumns.Col2,
RegistroColumns.Col3,
},null,null,RegistroColumnas.Col3,null,null,null);
if (cursor.moveToFirst())
do {
Registro registro = this.parseCursorToR(cursor);
if (registro != null)
aux.add(registro);
}
while (cursor.moveToNext()) ;
if(!cursor.isClosed()){
cursor.close();
}
return aux;
}
The java class:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lista_registros);
final ListView listView = (ListView) findViewById(R.id.lvRegistros);
DataManager servicio = new DataManagerImpl(this);
List<Registro> listRM = service.getRegistroDistinctedByCol3();
final ArrayAdapter<Registro> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, listRM);
listView.setAdapter(adapter);
After click in the element, I need to launch a new activity and show all the elements whit COL3, which is the value I used in my query.
How can I achieved my goal?
If some clarification is needed, let me know. Thanks.

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

Problem using Cursor to populate a spinner

I'm having a problem populating my spinner with data from my SQLite database. Here's the code from my Activity. The Activity crashes with an Unable to start Activity ComponentInfo error where indicated with an arrow.
public class ProjectsActivity extends Activity {
private ReelDbAdapter dbHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.projects_select);
fillProjectSpinner();
}
private void fillProjectSpinner(){
// initialize cursor to manage data binding to spinner
Cursor projectCursor = null;
Spinner spnExistingProjects = (Spinner)findViewById(R.id.spnExistingProject);
---> projectCursor = dbHelper.getExistingProjects();
//startManagingCursor(projectCursor);
/*
//get the list of project names from the database
String[] from = new String[] {dbHelper.clmProjectName};
//add a new item to the spinner for each of the rows in the database
int [] to = new int[]{R.id.txtViewProjectRow};
//initialize a cursor adapter (similar to ArrayAdapter when populating a spinner from a pre-defined array)
SimpleCursorAdapter projectAdapter = new SimpleCursorAdapter(this, R.layout.view_project_row, projectCursor, from, to);
//add all the rows to the spinner
spnExistingProjects.setAdapter(projectAdapter);
*/
}
Here's the code from the getExistingProjects method from my dbAdapter
public Cursor getExistingProjects() {
if(mDb == null)
{
this.open();
}
return mDb.query(dbTableProject, new String[] {clmProjectName, clmProjectShootingTitle, clmProjectJobNumber},
null, null, null, null, null);
}
Any clues on what I might be doing wrong?
TIA for any help.
Norm
Why don't you try making sure the query is returning something before returning the cursor in your method? Put a log line in that spits out the count of the cursor. Also, you should be able to see this easily while stepping through with the debugger.
Also, why assign null to the cursor's deceleration when you're just going to initialize it a few lines down. Do it all in one line.
Lastly, what db are you trying to one with that this.open() line? I obviously can't tell with just the code you've posted, but put a try catch around that whole thing and spit out the strackTrace. You should see your issue.

How to get the item id in an onItemClick handler

I have a category table with two columns category_id and name. I have created a data helper class named CategoryDataHelper. I have a method named getCategoryCursor() of that helper class which fetches the id and the name from the category table and returns the cursor. Using that cursor, I have used SimpleCursorAdapter to display the list of categories. It is working fine.
public class Categories extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
categoryDataHelper = new CategoryDataHelper(getApplicationContext());
Cursor categoryCursor = categoryDataHelper.getCategoryCursor();
ListAdapter adapter = new SimpleCursorAdapter (
this,
android.R.layout.simple_list_item_1,
categoryCursor,
new String[] { CategoryDataHelper.NAME },
new int[] {android.R.id.text1});
// Bind to our new adapter.
setListAdapter(adapter);
list = getListView();
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Here I want the category_id
}
});
}
}
Now I want to implement an OnItemClickListener and send an Intent with the category_id of the selected category. How can I get the id in the onItemClick() method?
You probably should get the cursor from the adapter. This way if your cursor gets replaced you are still are still getting a valid cursor.
Cursor cursor = ((SimpleCursorAdapter) adapterView).getCursor();
cursor.moveToPosition(position);
long categoryId = cursor.getLong(cursor.getColumnIndex(CategoryDataHelper.ID));
or use "category_id" or whatever the name of your column is in place of CategoryDataHelper.ID.
Thanks Zack, I could solve with your post...Excelent!!!
...
I send a parameter from an activity to another so:
Intent myIntent = new Intent(Clientes.this, Edc.class);
Cursor cursor = (Cursor) adapter.getItem(position);
myIntent.putExtra("CLIENTE_ID", cursor.getInt(cursor.getColumnIndex("_id")));
startActivity(myIntent);
In the other activity (EDC)....i get the parameter so:
int _clienteId = getIntent().getIntExtra("CLIENTE_ID", 0);
How about in onItemclick:
categoryCursor.moveToPosition(position);
and then from the returned cursor get the ID from your helper?
With the SimpleCursorAdapter, the onItemClick function passes in the databases id for the selected item. So, the solution is simply
long category_id = id

ListView Click event

I have a List of Items which I retrieved from my Sqlite DB...
I want to set a Click event for each item. How I can customize this event based on the Item clicked????
Be descriptive... I am a beginner.
This is the method that I used to fill data in my List:
private void fillData() {
db = new DBAdapter(this);
db.open();
ArrayList db_results = new ArrayList();
//All Category
//Cursor cursor = db.getAllTitles();
//Single Category
Cursor cursor = db.getTitle(1);
if (cursor.moveToFirst())
{
do {
db_results.add(cursor.getString(4));
} while (cursor.moveToNext());
}
cursor.close();
this.list.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, db_results));
}
Call setOnItemClickListener() on the ListView. The AdapterView.OnItemClickListener listener you provide will be given the position (0-based index) and ID (if you were using a CursorAdapter, as you should be, rather than converting the Cursor into an ArrayList), so you will know which item was clicked upon.

Categories

Resources