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?
Related
I have an activity which show a list. The list is populated from data taken from a sqlite database. I'm using a simpleCursorAdapter. When an item in the list is clicked I want go to another activity page to show more details about the list item clicked. For that I need the _id(primary key) of the clicked list item which is given in the database, so that I can query the database with that id and show more details in the next activity that loads when user clicks the list item.By using onItemClickListener, How to do this??? I appreciate any suggestions. Thanks in advance!
Set _id(primary key) as ID for list item:Adapter of data
Adapter:
#Override
public long getItemId(int position) {
return position;//you can return your ID
}
Activity:
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//id == getItemId(int position);
}
});
also do:
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//listView.getAdapter().getItem(position) -> getId;
}
});
You can pass the Id with an intent to the next activity:
Intent intent = new Intent(this, your_next_activity.class);
intent.putExtra("ID", id);
startActivity(intent);
Then get the value inside the next activity (EDIT):
Intent intent = getIntent();
int id= intent.getIntExtra("ID", 0);
Then You have the ID and You can query the database:
Cursor c = yourDBHelper.getAllDetailsMethod(); //method inside Your db-helper that gives You the cursor
int rows = c.getCount();
c.moveToFirst();
for(int i=0;i<rows;i++){
int db_id = c.getInt(0) //this belongs to the place where Your id is inside the db
if(db_id==id){
//here You can get all details you need
break;//stop quering
}else{
c.moveToNext();
}
}
But to give You a good solution it will be good if You show us what You have done until now.
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));
}
});
I have a listview linked to a sqlite database. I have 3 items in the database, but everytime I click on the second and third value it gives me the same result as the very first value in the record set. How do I move through subsequent items in the recordset? Here is the code:
DBAdapter db = new DBAdapter(this);
db.open();
lv = (ListView)findViewById(R.id.list);
//Get cursor for list items
cursor = db.getAllChannels();
lv.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
//String cText = lv.getItemAtPosition(position).toString();
//retrieve database values
Toast.makeText(getApplicationContext(), cursor.getString(cursor.getColumnIndex(DBAdapter.KEY_STATIONURL)), Toast.LENGTH_SHORT).show();
}
});
When the adapter is already populated using a cursor, you should refrain from acquiring data using the cursor fed to the adapter. Instead use getItem(int position) which should return a cursor that is already pointed to the correct item in your list. Your code would then look like this:
lv.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
//retrieve database values
Cursor tempCursor = getItem(position);
Toast.makeText(getApplicationContext(), tempCursor.getString(tempCursor.getColumnIndex(DBAdapter.KEY_STATIONURL)), Toast.LENGTH_SHORT).show();
}
});
You can go a step further and override your CursorAdapter's getItem(position) so that it returns a Data* object wherein you just need to getKeyStationUrl()* to get the value that you need.
So I've got a ListView (using a ListActivity) that I'm populating from a SQLiteDatabase. I'm trying to attach the ID (PK) of the row to the view, so that onListItemClick of each list item, I can do stuff with that ID.
I've read that arbitrary data can be set to a View using setTag and retrieved with getTag(I haven't actually had this work successfully yet, so this may be the problem). Here's a pared down version of what I'm using (for simplicity/brevity):
public class Favorites extends ListActivity {
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
FavoritesDB db = FavoritesDB.getInstance(this);
Cursor c = db.fetchFavorites();
startManagingCursor(c);
String[] columns = new String[] { "_id" };
int[] to = new int[] { R.id.word };
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.favorite, c, columns, to);
adapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
view.setTag(cursor.getInt(0));
return true;
}
});
setListAdapter(adapter);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Object wordID = v.getTag();
Toast.makeText(getBaseContext(), "ID=" + wordID, 1).show();
}
}
The ListView is being populated, and the Toast does show up, but it's always "ID=null", so apparently the ID isn't being set in the ViewBinder call to setTag(or isn't being retrieved property with getTag).
This depends on your implementation of R.layout.favorite. If you have this layout contains a parent view with child TextViews for e.g. the tag you set is for the TextViews while the View v received from the onListItemClick() is the parent View. You need to make sure that you receive the tag for the same view you set by using:
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Object wordID = v.getChild(0).getTag();
Toast.makeText(getBaseContext(), "ID=" + wordID, 1).show();
}
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.
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Cursor cursor = adapter.getCursor();
cursor.moveToPosition(position);
String id = cursor.getString(cursor.getColumnIndex("primary key field name in database");
Toast.makeText(getBaseContext(), "ID=" + id, 1).show();
}
NOTE :
your adapter must be declared as a SimpleCursorAdapter other wise you should downcast it.
I learn work with Android. I started to create a project with Contacts.
I insert contacts into the SQLite database and then I put them from the database and show them in ListView. Thats OK. But I would like to click on an item in the List and then to edit the item. Therefore I need to get somehow the ID of the item and work with it...I do not know if it is clear...As you can see, in the function onItemClick() , there is running a new activity ...and in the new activity, I need the ID of the item in order to work with it.
public class ContactList extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.seznam_kontaktu2);
SQLInsert info = new SQLInsert(this);
info.open();
ArrayList<String> data = info.getDataArrayList(); //It returns Array of "Lastname, Name" which is shown in the List
info.close();
ListView lv1 = (ListView) findViewById(R.id.ListView01);
lv1.setAdapter (new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, data));
lv1.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
startActivity(new Intent("net.johnyho.cz.EDITOVATKONTAKT"));
}
});
}
One option that has worked for me is to create a custom ArrayAdapter class along with a custom AdapterItem class. We store the id on our AdapterItem, and return it using our custom ArrayAdapter.
MyAdapterItem might look something like ...
public class MyAdapterItem implements Comparable
{
public String name;
public long rowId;
public MyAdapterItem()
{
rowId = -1L;
name = "";
}
public MyAdapterItem(long _rowId, String _name)
{
rowId = _rowId;
name = _name;
}
public int compareTo( Object o )
{
return toString().compareTo(o.toString());
}
public String toString()
{
return name;
}
}
Our custom ArrayAdapter, MyAdapter, then overrides getItemId(). It reads and returns the stored row id (making the assumption it is working with elements of MyAdapterItem). The other methods on ArrayAdapter will continue to work with our custom class - the toString method is used by the list for display purposes, and by providing a compareTo method the list knows how to sort the values.
public class MyAdapter<MyAdapterItem> extends ArrayAdapter
{
public MyAdapter(Context context, int resourceId)
{
super(context, resourceId);
}
#Override
public long getItemId( int position )
{
MyAdapterItem item = (MyAdapterItem)this.getItem(position);
return item.rowId;
}
}
Back in your Activity's onCreate the OnItemClickListener now provides the correct row id in the "id" parameter.
What is not shown is the new implementation of info.getDataArrayList() - it must be modified to create new MyAdapterItem objects instead of simple Strings.
ArrayList<MyAdapterItem> data = info.getDataArrayList();
ListView lv1 = (ListView) findViewById(R.id.ListView01);
lv1.setAdapter( new MyAdapter<MyAdapterItem>(this, android.R.layout.simple_list_item_1, data) );
lv1.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View view, int position, long id)
{
// do whatever - the value in "id" is supplied by getRowId on our adapter
}
});
Also, if you attach a context menu to your ListView, the MenuItem objects passed into your Activity's onContextItemSelected method will also return the correct row id.
#Override
public boolean onContextItemSelected(MenuItem item)
{
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
long rowId = info.id;
// do something with the id
}
public void onItemClick(AdapterView arg0, View arg1, int arg2, long arg3) {
startActivity(new Intent("net.johnyho.cz.EDITOVATKONTAKT"));
}
hi i dont know what are the column names of your application.but for example id is your primary key identifier then move cursor to arg2 postion and get the value of _id and then pass it to startActivity and it will work.first thing apply SQLiteOpenHelper class its easy for use then apply this.