I have a ListView lv which uses a Cursor c from an SQL database to populate it. When an item is selected however, I need to get the ID of the row. How can I do this?
I assume that you are using a SimpleCursorAdapter (or similar), so I would use the OnItemClickListener:
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// id references the SQLiteDatabase _id column
}
});
Here's how it worked out for me. In an other class, I have created a method of List type and added the column id & the name of the item in the list from the sqlite database.
Here's the piece of code to retrieve the column id of the selected item.
public List<String> list;
adapt = new MyAdapter(this, R.layout.list_inner_view, list); //custom adapter
listTask.setAdapter(adapt);
listTask.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View v, int position, long l) {
Integer id = list.get(position).getId();
//position is the position of the item in the list.
}
});
Result: the item is at 3rd position in the list. Its database column_id (auto increment) value is 12 because I have deleted previous items. So the result you expect is 12, which is the value of variable id.
If you don't understand this fully, it may be because I haven't posted my entire code. But I'll help you out with your problem.
Related
I have a problem with receiving _ID value when an item is clicked on listView.
I have this code:
List<SavedSearch> values = mydb.getAllSavedSearches();
ArrayAdapter<SavedSearch> adapter = new ArrayAdapter<SavedSearch>(this,
android.R.layout.simple_list_item_1, values);
//adding it to the list view.
obj = (ListView)findViewById(R.id.listView1);
obj.setAdapter(adapter);
obj.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
And my problem is that i want in onItemClick to somehow get the _ID value from database of clicked item in listView. int position and long id both are returning just position on the list.
Thanks for help, and I can say that any of previous topics helped me.
If you're using a database I would suggest you do not use an ArrayAdapter and instead use a CursorAdapter. Then simply call the method getItemId() from your CursorAdapter to retrieve the id of an item at a given position. So, do this:
CursorAdapter adapter = new CursorAdapter(Context yourAppContext, Cursor yourDBCursor, false);
obj = (ListView)findViewById(R.id.listView1);
obj.setAdapter(adapter);
obj.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
adapter.getItemId(position); // This is the _ID value
}
This is just the suggestion. I am not sure this will solve the issue.
Method 1:
Whenever you load the listView just set the id for the row and you can get the id from onItemClikListener method
Method 2:
Add an texView (set visibility gone) and set text as your id and get id using getText() method
Note
Don't use position this is always changing when the listview is reCycling.
I have a list view and I've implemente filtering.
Lets say I have items A, B and C. If I type B in the filter box, only item B will be displayed and it is the position 0 of the list (before it was in position 1). So when I call the onClick item, I get the the id/position 0, which leads to displaying details about A instead of B.
This is the onclick code:
ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Poi poi = pois.get((int)id);
goPOIDETAIL(poi);
}
});
id and position have the same value.
is there a way to get the original position, or get some other value indicating the real item that I clicked?
Thanks
flashsearchList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Integer temp=flashSearchNameMap.get(adapter.getItem(position));
navigateSearch(temp);
}
});
(adapter.getItem(position) will return you the exact list name and in flashSearchNameMap i have stored names and position at beginning from oncreate before applying filtering.So you can get exact position by this
I think the problem is in the way you manage your filter. You should get the object with selected id not from the original List (or array) but from the filtered one.
I used something like it in this post from my blog. Hope this help you
ID and Index are not the same. Of course, you can return item index in getItemId() method of your adapter, but don't expect your items to be identified correctly by this method if you do.
Try providing unique ID for each of your items. The idea is somewhat similar to ID of each record in the database, which never changes (and lets you reliably identify each record), and it is easily implemented when you get your data from database.
But if your items don't have unique IDs, and you don't want to bother providing them, there's another approach (see this example code for Adapter below):
public MyAdapter extends BaseAdapter {
private List<Item> items;
private List<Item> displayedItems;
public MyAdapter(List<Item> items) {
this.items=items;
this.displayedItems=items;
}
public filter(String query) {
if(query.isEmpty()) {
displayedItems=items;
} else {
displayedItems=new ArrayList<Item>();
for (Item item : items) {
displayedItems.add(...) //add items matching your query
}
}
notifyDataSetChanged();
}
//...
//NOTE: we use displayedItems in getSize(), getView() and other callbacks
}
You can try:
#Override
public boolean hasStableIds() {
return false;
}
in your adapter
if you are using datbase you have the _id key that you can load in a filtered list as invisible field. Once you click on the item you can query data with _id key.
If you aren't using a database you could add a hidden id element in your row element as well.
I am displaying an arraylist through a listactivity. Also, i have associated id's with these arraylist elements which i can get together in a hashmap maybe. But the problem is i want to obtain that particular id of the element when it is clicked. How to achieve that. Any help is appreciated.
You can return the id based on the clicked position if you an implementation of the getItemId(position) method in your adapter. The id you return here will be the long id argument in the onListItemClick(...) method of your ListActivity.
getItemId(int position) is a member of the ArrayAdapter class. The ListActivity will call that function from the adapter of yourListView. All you have to do is to provide the implementation, the rest will work out just fine.
http://developer.android.com/reference/android/widget/ArrayAdapter.html#getItemId(int)
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
long pos=lv.getItemAtPosition(position);
//do your stuff here
}
});
if you are using your own ArrayAdapter, you can implement the getItem(position) method..
The answer that worked for me is as follows. Hope it maybe useful for others.
I had the data in Arraylist> testdata. I passed it like this :-
this.setListAdapter(new SimpleAdapter(Grammar_tab_start.this, testdata ,
.layout.tab_single_item, new String[] { "module_name"},
new int[] { R.id.from}));
ListView lv = getListView();
to single list item on click
lv.setOnItemClickListener(new OnItemClickListener()
public void onItemClick(AdapterView<?> parent, View view,
int position, long id)
{
Log.i("check","Module item clicked");
HashMap<String,String> pos=(HashMap<String, String>) lv.getItemAtPosition(position) ;
Log.i("check","----" + position + "id" + id +"actual is "+ pos.get("module_id"));
}
I used the lv.getItemAtPosition() function to retrieve the whole object that was clicked. And then took th eid part from it. Cheers.
I'm having somewhat of an issue in an application I'm developing.
So, all my tables have _id fields for primary keys, and I use SimpleCursorAdapter to bind them to ListViews and Spinners.
What I wanted to know is how can I make the ListView or Spinner selected item have the same ID as the corresponding row?
The strange thing is that this works with the ContextMenu, which I am using straight of the NotePad example:
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
info.id
This ID field IS the same as the RowID on the table, and I can delete items fine, but when I try something like this:
getListView().setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View view,
int position, long arg) {
Intent i = new Intent(getApplicationContext(),
FuelingList.class);
long id = view.getId();
The ID field is some random rubberish.
So my question is, in the first code bit, what Id is the AdapterContextMenuInfo getting and how can I retrieve it in other parts of my code?
Since you are using a SimpleCursorAdapter, the onItemClick is passing the database row id in to you..
public void onItemClick(AdapterView<?> adapter, View view, int position, long arg)
The long arg part is actually your row id from the database.
So your code should be:
getListView().setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View view,
int position, long arg) {
Intent i = new Intent(getApplicationContext(),
FuelingList.class);
long id = arg;
Since you know you are using a SimpleCursorAdapter, then in your onItemClick method, you can call
public void onItemClick(AdapterView<?> adapter, View view, int position, long arg) {
String value = ((SimpleCursorAdapter) adapter.getAdapter()).getCursor().getString(COLUMN_INDEX);
}
Where COLUMN_INDEX in the column that you want to fetch from the currently select row in the cursor.
Alternately, calling
adapter.getAdapter().getItem(position)
and then casting that to a Cursor, works as well.
NOTE 1: The AdapterView is actually your ListView.
NOTE 2: Since you using a SimpleCursorAdapter then getItem(position) on the Adapter returns the Cursor positioned at the row your specifed
NOTE 3: When you have Cursor, you can fetch data by providing the column index (0 based) or by using cursor.getString(cursor.getColumnIndex("COLUMN_NAME"))
NOTE 4: As per Barak's comment the arg parameter is the value from the _ID field when using a CursorAdapter, if all you need to know is the row _ID, then just use the arg value.
Can you store the ids of rows in an arraylist and take the id of the row from corresponding position of arraylist. This worked for me..
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
Intent intent=new Intent(this , Details.class);
Bundle extras = new Bundle();
extras.putLong("ID", IDList.get(position));
intent.putExtras(extras);
startActivityForResult(intent, SHOW_DETAILS);
}
You can use listview.setonitenclicklistener... Hope it helps
If I have a listview being populated with webservices and the elements added in each row have a unique id stored in the array list which utilizes a hashmap to store data,thn what would be the simplest way to obtain the id of the data,that was clicked in the row..
I am using a base adapter on my list,
Any help would be greatly appreciated.
set on item click listener on listview. it will return position of the clicked item in the adapter (equivalent to position in the array list). you can fetch the id using that.
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(),String.valueOf(position), Toast.LENGTH_SHORT).show();
}
});
Third parameter is Position of Item in the list.
use this method listView.getItemAtPosition(position). It got a position you can use
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
// Get item at position like this:
// listView.getItemAtPosition(position));
}
});
if you use the adapter.getItem(position) function you'll be able to get the item stored in the ListView in that specific position.
update: this is of-course in the setOnItemClickListener