How to get the item id in an onItemClick handler - android

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

Related

How to pass the data in the database to a spinner

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();
}

How to display data from a list view to a activity

I have a list view and a database I want to display the data from the database in another activity so I made a OnItemClickListener for my list view.
Now I get the position of the ClickListener but because I have made my adapter to display data so the latest input from the user is on top. I nead to reverse the position of the onClick.
At the moment I get:
1
2
3
4
but I need:
4
3
2
1
because of the database id.
If for example the user clicks position 3 on the list I want the database to return the row 3.
ListView:
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
Intent myIntent = new Intent(getActivity(), JornalListViewClick.class);
myIntent.putExtra("intVariableName",position);
startActivity(myIntent);
}
});
The getRows of the database:
public Cursor getAllRowre(){
String where=null;
Cursor cursor=db.query(true, DATABASE_TABLE, ALL_KEY, where, null, null, null,ID_KEY + " DESC", null);
if(cursor!=null){
cursor.moveToFirst();
}
return cursor;
}
The activity where I want to display the data:
Intent mIntent = getIntent();
int intValue = mIntent.getIntExtra("intVariableName", 0);
intValue++;
text=(TextView) findViewById(R.id.textViewUserInputFromListClicked);
Cursor cursor=dbJ.getRowUserInput(intValue+"");
if(cursor.moveToFirst()){
do{
String mes=cursor.getString(0);
text.setText(mes);
}while(cursor.moveToNext());
}
An alternative way:
Use a POJO to store every row retrieved
Implement Comparator and use Collections.sort(List, Comparator) to sort it before putting it into adapter
public class MyData{
private String field;
// getter and setter
}
After retrieve the String from database, you can instantiate MyData class and set the string (or more fields) into the instance. Put all results in a Collection. E.g.:
Vector<MyData> listOfResults=new Vector<MyData>();
if(cursor.moveToFirst()){
do{
String mes=cursor.getString(0);
MyData instance=new MyData();
listOfResults.add(instance);
}while(cursor.moveToNext());
}
return listOfResults;
After retrieving data from database, you want to sort it, right? Try this:
Collections.sort(listOfResults,new Comparator<MyData>(){
public int compareTo(MyData a,MyData b){
return a.getField().compareTo(b.getField());
}
});
Inside the Activity containing the ListView, create a private class implementing ListAdapter. E.g.:
private class MyListAdapter implements ListAdapter{
private Vector<MyData> data;
public MyListAdapter(Vector<MyData> list){
data=list;
}
/*** other methods you need to implement ***/
}
Instantiate MyListAdapter by supplying the Vector you got from database access method.
Then call setAdapter(ListAdapter) of the ListView inside the Activity after the data is ready.

to display items in a listview based on a parameter

i am displaying only three details from my database in 1 row of the listview after the user clicks on this list item all the details should be made visible in another activity in a list view.i tried but m getting a blank activity to open instead of a list..
ListViewDetails.java
listview.setOnItemClickListener(new OnItemClickListener() {
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 state's capital from this row in the database.
int appno=cursor.getInt(cursor.getColumnIndexOrThrow("appln_no"));
Intent objintent=new Intent(getApplicationContext(),DisplayDetails.class);
objintent.putExtra("countryCode", countryCode);
startActivity(objintent);
}
});
here m passing an appno parameter to the next intent so that details related to this appno are displayed in DisplayDetails.java
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listdisplay);
Intent intentobj=getIntent();
int appno=intentobj.getIntExtra("appln_no", 0);
WayDataBase way=new WayDataBase(getApplicationContext());
ArrayList<String> listvalues=way.getListDetails(appno);
if(listvalues.size()!=0)
{
ListView lv=getListView();
ListAdapter adapter=new ArrayAdapter<String>(DisplayDetails.this, R.layout.view_animal_entry, R.id.animalName, listvalues);
lv.setAdapter(adapter);
}
}
but the screen is just balnk..
whats the issue??? please help! thanks!
Shiv,
You have fetched the values in variable "appno" but set values from variable "countryCode" instead of "appno".
In your DisplayDetails.java, you are trying to fetch it from the the variable "appln_no" which is incorrect.
If i look at your code then it seems that you want to pass appno value to another activity
so should keep it like this:
ListViewDetails.java
objintent.putExtra("countryCode", appno);
DisplayDetails.java
int appno=intentobj.getIntExtra("appln_no", "countryCode");

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

How can I reset the SQLite query for my Listview after it has been created?

I have a ListView which is populated by a SQLite query in OnCreate using the following code which then sets up an OnItemClickListener.
ListView menuList = (ListView) findViewById(R.id.ListView_Menu);
String sql = "SELECT EXHIBITORS, ('Stand No. ' || STANDNO) AS STANDNO, _ID FROM EXHIBITOR ORDER BY EXHIBITORS";
cursor = myDbHelper.getReadableDatabase().rawQuery(sql, null);
startManagingCursor(cursor);
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.menu_item, cursor, FROM, TO);
menuList.setAdapter(adapter);
menuList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View itemClicked, int position, long id) {
However, I want to be able to filter the ListView and then amend the query so that the user can reduce the size of the ListView by say requesting all Exhibitors that start with the letter 'A'. How can I do this, I assume by using the above code again but how do I this and still keep the OnItemClickListener working?
CursorAdapter.changeCursor() will allow you to replace your query with one that filters the Exhibitor names.

Categories

Resources