Get item ID from populated ListView - android

I need help retrieve my ListView items ID, to add delete functionality.
My ListView is populated with this code:
ListView BookList = (ListView)findViewById(R.id.listView1);
DbAdapter db = new DbAdapter(getApplicationContext());
db.open();
Cursor cursor = db.fetchAllBooks();
startManagingCursor(cursor);
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.book, cursor, new String[]{DbAdapter.KEY_TITLE,DbAdapter.KEY_AUTHOR},new int[]{R.id.booktitle,R.id.bookauthor});
BookList.setAdapter(adapter);
if(cursor.moveToFirst()) {
while (cursor.moveToNext());
}
db.close();
My delete code is set as this, in the DbAdapter class:
//delete a book
public boolean deleteBook(long bookID) {
return database.delete(DATABASE_TABLE, KEY_BOOKID + "=" + bookID, null) > 0;
}
Any help?
Full sources: pastebin.com/kKgePkPM

You have to add a listener to your listView. The best way is set
bookList.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// DO YOUR STUFF HERE
}
});
There you will get the view and the position clicked. With the view or the position you could obtain the value desired to your "deletebook" method.

If I understand you correctly, you can add itemclicklistener to your listview, then use the row id to remove it from your database, if the bookid is the same as the row id of course.
BookList.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if (db.deleteBook(position)) { // Success!
// remove from listview data source here
adapter.notifyDataSetChanged();
}
}
});

try adding something like this in getView method:
Button btnDelete = (Button) convertedRowView.findViewById(R.id.btnDeleteCustom);
btnDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int itemPos = 4; // This is position of item in ArrayList
deleteBook(getItemId(itemPos));
}
});

Related

How can I get the row id of the a table in the sqlite database when an Item is clicked in the listview

My code goes here.............! when there is a row deleted from the list-view. The indexes of the rows of the listview is changed but the primary key id in the database is not changed. now when i click the item and pass the position of the clicked item of the listview to the new activity. And try to retrieve the record with that ID it does not return me something or incorrect data is returned. now my question is how can I detect the row id of the clicked item of listview in the database.
Now what should be code inside the onItemclick method to retrieve the correct rows from the database.
Thanks in anticiaption......!
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myDb = new DBHelper(this);
titles = myDb.getAllNames();
times = myDb.getAllTimes();
ArrayAdapter<String> ad = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, titles);
lv = (ListView) findViewById(R.id.listView1);
lv.setAdapter(ad);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3)
{
}
});
}
First of all you have to write a query and retrieve id in your database.You must return the id in a cursor.
Refer the below code snippet:
public Cursor fetchAllNames() {
Cursor mCursor = app.myDbHelper.MyDB().query("cardlist", new String[] {"cardid as _id","cardname","carddesc"},
null, null, null, null, null);
try{
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}catch(Exception e)
{
return mCursor;
}
}
Then in your java page:
Cursor cursor = myDB.fetchAllNames();
Then you can get the database id by:
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3)
{
if(cursor!=null){
System.out.println("position===>"+position);
if(cursor.moveToFirst()){
cursor.moveToPosition(position);
String cardid = cursor.getString(cursor.getColumnIndex("_id"));
}
}
}
});
you will get the database id in the string cardid. You must use _id if you are using SimpleCursorAdapter else you must replace _id with that of the column name that represents your id in the sqlite database.
There's an easy way to achieve so :
First, create an object to represent one line in your database. Since I don't know what your database contains, let's just call it "Title".
public class Title {
private long id;
private String title;
// Constructor, setters and getters
}
Then, create a custom adapter. It will store a collection of Title which will allow you to get it when an item is clicked.
public class TitlesAdapter extends ArrayAdapter<Title> {
private Context context;
private List<Title> items;
public TitlesAdapter(Context context, List<Title> items) {
super(context, R.layout.row_draweritem, items);
this.context = context;
this.items = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) { /* ... */ }
}
You can then set your adapter in your activity easily:
this.titlesAdapter = new TitlesAdapter(context, titles);
listView.setAdapter(this.titlesAdapter);
... and define your onItemClickListener so you can get back the row id in your database
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
long id = titlesAdapter.getItems().get(i).getId();
}
});
You can learn more about custom adapters in this article : http://www.vogella.com/tutorials/AndroidListView/article.html

Implementing OnClickListener to list items of a list

I used list view to list the items of my SQLite database as follows:
listView = (ListView) findViewById(R.id.listView1);
db.open();
Cursor c = db.getAllHistory();
ArrayList<String> temparr = new ArrayList<String>();
if (c.moveToFirst()) {
do {
temparr.add(c.getString(0)+'\t'+c.getString(1)+'\t'+c.getString(2)+'\t'+c.getString(3)+'\t'+c.getString(4)+'\t');
} while(c.moveToNext());
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, temparr);
listView.setAdapter(adapter);
} else {
db.close();
}
Now I want to access the specific list item by using OnItemClickListener. How should i do it?
To get your perticular data-
Implement setOnItemClickListener()-
and position will return list's item position number:-
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
String yourData = temparr.get(position);
}
});
Just call listView.setOnItemClickListener() with your implementation of the listener.
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
// your code
// Toast.makeText(context,temparr.get(position),Toast.LENGTH_SHORT).show();
}
});
parent -> The AdapterView where the click happened.
view -> The view within the AdapterView that was clicked (this will be a view provided by the adapter)
position -> The position of the view in the adapter.
id->The row id of the item that was clicked.
You can set the listener like this:
Put this code in onCreate()
TextView disp = (TextView) findViewById(R.id.textView1);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String temp = (String) listView.getItemAtPosition(position);
disp.setText(temp);// display on screen
}
});
EDIT:
As you want to display the listItem on screen in a permenant sort of way rather than displaying a toast, the easiest way that you can do this is by adding a TextView in your layout. See the updated code
Hope this helps.

Trying to get String from ListView

My current problem is I have a ListView I'm using to display my contacts now I'd like to set the onItemClick to grab the name of the contact and set that to a TextView called p2 the code I currently have is:
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.setp2);
cursor = managedQuery(ContactsContract.Contacts.CONTENT_URI,null,null,null,null);
String[] from = new String[]{ContactsContract.Contacts._ID,ContactsContract.Contacts.DISPLAY_NAME};
int[] to = new int[]{R.id.id_text,R.id.name_text};
final SimpleCursorAdapter adapter = new SimpleCursorAdapter(setp2.this,R.layout.setp2_layout,cursor,from,to);
ListView list = (ListView)findViewById(R.id.contact_list);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
}
});
}
So basically I'm unsure of what I need to do in the onItemClick, any help appreciated!
In your onItemClick, you will get the instance of the view associated with that list item.From that view you can get the text associated with it and set it to the p2 TextView. If my understanding of your requirement is correct, the code will be something like this:
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
CharSequence name = ((TextView)view.findViewById(R.id.name_text)).getText();
//Set this to your textview in P2
tvP2.setText(name);
}
});
Set up a SimpleCursorAdapter.CursorToStringConverter and set it on the adapter, then use convertToString(Cursor cursor) to get the text in on item click :
(Cursor) simple.getItem(position)
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
cursor.moveToPosition(position);
String name = cursor.getString(cursor.getColumnIndex(
ContactsContract.Contacts.DISPLAY_NAME));
p2.setText(name);
}
});

In Android how to pass ListAdapter values to onItemClick?

I've got a functioning search interface on my app. Now I'm trying to make each search result list item clickable and display in a new activity. I've got them clickable, but I can't figure out how to pass the ListAdapter values (records) into the onItemClick method.
Here's my code so far:
private void showResults(String query) {
Cursor cursor = DBHelper.searchDB(query);
startManagingCursor(cursor);
String[] searchFrom = new String[] { DBAdapter.KEY_MAKE,
DBAdapter.KEY_YEAR, DBAdapter.KEY_MAKE,
DBAdapter.KEY_MODEL };
int[] displayHere = new int[] { R.id.rDateTV, R.id.rYearTV,
R.id.rMakeTV, R.id.rModelTV };
final SimpleCursorAdapter records = new SimpleCursorAdapter(this,
R.layout.record_2, cursor, searchFrom, displayHere);
setListAdapter(records);
DBHelper.close();
// --- Click on list item ---
ListView clickList = getListView();
clickList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//--- here's the problem: how do I pass the ListAdapter values into onItemClick. the below doesn't like .getText()
String sYear = (view.findViewById(R.id.rYearTV)).getText().toString();
String sMake = (view.findViewById(R.id.rMakeTV)).getText().toString();
String sModel = (view.findViewById(R.id.rModelTV)).getText().toString();
// -- then pass these strings to an intent to launch a new activity
}
});
// --- END click on list item ----
}
Any ideas? I'm a rookie here, so if you could show me the code, that would be AWSOME!
In OnItemClickListener.onItemClick call parent.getItemAtPosition(position). That method returns cursor which is set to the given position. Then get your data from that cursor. Don't close cursor inside OnItemClickListener.onItemClick.
for example:
ListView clickList = getListView();
clickList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Cursor c = (Cursor)parent.getItemAtPosition(position)
String sMake = c.getString(c.getColumnIndexOrThrow(DBAdapter.KEY_MAKE));//get data from cursor
...
}
});

Edit List Items in ListView

I have a listview from an SQLDatabase using custom CursorAdaptor. I would like to go back to the activity that i used to create the items when i click on them in the listview.so that i can edit the entries. But nothing happen when i implement the OnItemClick method and the getItemId() on the CursorAdapter even though am not sure i am correct there. Here is my Code:
public void onItemClick(AdapterView<?> adapview, View view, int position, long rowId) {
Cursor c = adapter.retrieveRow(rowId); // retrieve row from Database
Intent edit = new Intent(this,NewItem.class);
edit.putExtra(DBAdapter.KEY_ID, rowId);
edit.putExtra(DBAdapter.Title, c.getString(c.getColumnIndex(DBAdapter.Title)));
edit.putExtra(DBAdapter.DATE, c.getString(c.getColumnIndex(DBAdapter.DATE)));
startActivity(edit);
}
public long getItemId(int id){
return id;
}
I think you need to set an onItemClickListener on the Listview rather than trying to implement it in the Adapter class.
EXAMPLE:
mListView = (ListView)findViewbyId(R.id.whatever)
mListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position,
long rowId) {
Cursor c = adapter.retrieveRow(rowId); // retrieve row from Database
Intent edit = new Intent(this,NewItem.class);
edit.putExtra(DBAdapter.KEY_ID, rowId);
edit.putExtra(DBAdapter.Title, c.getString(c.getColumnIndex(DBAdapter.Title)));
edit.putExtra(DBAdapter.DATE, c.getString(c.getColumnIndex(DBAdapter.DATE)));
startActivity(edit);
}
});
Is this what you're doing?

Categories

Resources