SQLite delete not actually deleting - android

I have a SQLite database that I am saving user selected data to. This data will be visible in a listview and if you long click on the data it will delete that item. This is working as I see the item disappear from the listview, but when I restart the application and all the listview items are brought back in from the database, everything that was deleted is coming back. I am using this statement:
public void deleteAlarmEntry(int pos){
Log.i("Deleting item from pos: ", String.valueOf(pos));
db.delete(MySQLHelper.TABLE_NAME, MySQLHelper.ID_COL + "='" + pos + "'", null);
}
I can see the statement being called in the logs. Is there a better way to make sure that the statement is executing correctly? Is something wrong here?
Here is my removeItem method called in the MainActivity on long click of the listview item:
public void removeItem(int position) {
alarmItemArray.remove(position);
dataSource.deleteAlarmEntry(position);
alarmAdapter.notifyDataSetChanged();
}
The dataSource.deleteAlarmEntry() calls the above database remove.
Also, on application startup I am bringing the entries into a temp arraylist and then parsing the time to get the adapter arraylist like so:
dataSource = new WeatherDataSource(this);
dataSource.open();
ArrayList<AlarmEntry> alarmEntries = (ArrayList<AlarmEntry>) dataSource.getAllWeatherEntries();
alarmItemArray = getTimeFromEntries(alarmEntries);
alarmAdapter = new ArrayAdapter<String>(this,
R.layout.activity_alarm_item, R.id.time, alarmItemArray);
lv = (MyListView) findViewById(R.id.listview);
lv.setAdapter(alarmAdapter);
Here is the database's getAllWeatherEntries:
public List<AlarmEntry> getAllWeatherEntries(){
List<AlarmEntry> weatherEntry = new ArrayList<AlarmEntry>();
Cursor cursor = db.query(MySQLHelper.TABLE_NAME, cols, null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
AlarmEntry m = cursorToEntry(cursor);
weatherEntry.add(m);
Log.i("Get all weather entries", m.getTime());
cursor.moveToNext();
}
cursor.close();
return weatherEntry;
}

You're just passing everything from that item to your query.
In OnContextMenuItemSelected you will need to do something similar to the below; you will need to change the parameters of your deleteAlarmEntry to receive a string instead of an int.
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
String selectedID;
// adapter is the Adapter from creating the listview
selectedID = String.valueOf(adapter.getItemId(info.position));
deleteAlarmEntry(selectedID);
}
You will also need to modify the db.delete to return a number, ie int result = db.delete() per the function. http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html
EDIT:
you may want to use OnItemLongClickListener instead of OnLongClickListener
http://developer.android.com/reference/android/widget/AdapterView.OnItemLongClickListener.html
lv.setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
String id = String.valueOf(alarmAdapter.getItemId(position);
removeItem(id);
}
});
SECOND EDIT:
Try this for cursoradapter, i'd recommend using a simple cursor adapter:
http://developer.android.com/reference/android/widget/SimpleCursorAdapter.html
String[] from = new String[]{"time"}; //enter your time column name here
int[] to = new int[]{R.id.time};
Cursor cursor = db.query(MySQLHelper.TABLE_NAME, cols, null, null, null, null, null);
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,R.layout.activity_alarm_item, cursor, from, to);
lv.setAdapter(adapter);

use,
public void deleteAlarmEntry(int pos) {
db.delete(MySQLHelper.TABLE_NAME, MySQLHelper.ID_COL + "=?", new String[]{pos + ""});
}

Related

Loading two SQL columns into a listview but only need to display the first column Android

I am using an sqllite database to store two columns which are phonename and phonenumber. I am using an arrayList to iterate through the data and display the phonename in a listview which is working, but I also need to iterate through the phonenumber column under the same listview as well. I only need the phonename to be showing in the listview.
This is for when the user has selected the item in the listview, it shows the selected phonename and phonenumber, which at the moment it is only currently showing the phonename and showing blank for phonenumber for obvious reasons.
DataDBAdapter
public long insert(String phonename, String phonenumber)
{
ContentValues cv = new ContentValues();
cv.put(COl_MYTABLE_PHONENAME,phonename);
cv.put(COL_MYTABLE_PHONENUMBER,phonenumber);
return mDB.insert(TBL_MYTABLE,null,cv);
}
//---------------------------------------------------------------------------
// Iterating through the database
//---------------------------------------------------------------------------
public ArrayList<String> getAllRowsAsList()
{
Cursor csr = mDB.query(TBL_MYTABLE,null,null,null,null,null,null);
ArrayList<String> rv = new ArrayList<>();
while (csr.moveToNext())
{
rv.add(csr.getString(csr.getColumnIndex(COl_MYTABLE_PHONENAME)));
}
return rv;
}
SelectModemFragment
private void manageListView(Context context)
{
thelist = dbHelper.getAllRowsAsList(); // Extract the list, just the phone names
// Only setup the adapter and the ListView if the adapter hasn't been setup
if(arrayAdapter == null)
{
// Instantiate the adapter
arrayAdapter = new ArrayAdapter<>(context,android.R.layout.simple_list_item_1,thelist); //<<<<<<<<<< list included
display_contacts1.setAdapter(arrayAdapter); //<<<<<<<<<< Tie the adpater to the ListView
// Set the ListViews OnItemClick Listener
display_contacts1.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
String namedisplay = arrayAdapter.getItem(position); //<<<<<<<<<< this gets the phone name
namedisplay = arrayAdapter.getItem(position);
Toast.makeText(view.getContext(), namedisplay + " Selected for Communication", Toast.LENGTH_SHORT).show();
Toast.makeText(view.getContext(), phoneNo, Toast.LENGTH_SHORT).show();
}
});
}
Issue
using ArrayAdapter only allows a a single item to be passed, thus unless you resort to complicated/messy/inefficient methods ArrayAdapter is only really suitable for a single value.
Fix
You could use an ArrayList where your_object has members for all the required values. i.e phonenumber and phonename. Noting that unless you use a Custom Adapter that you should override the the toString method to extract the data that you want to be displayed, as that is what a standard ArrayAdapter uses.
Alternative (use a CursorAdapter)
An alternative would be to use a Cursor Adapter (e.g. SimpleCursorAdapter), you can then return the Cursor and use it directly. However, a CursorAdapter REQUIRES a column specifically name _id (BaseColumns._ID can be used).
One of the clear advantages of a Cursor adapter is the the 4th paremmter passed to the onItemClick/onItemLongClick is the id of the row (if used correctly) allowing a single value to then get/update/delete/pass the respective selected row.
As such I'd recommend a Cursor Adapter for a ListView and hence the more comprehensive answer.
You may think I don;t have such a column. However, you can use the normally hidden rowid column and dynamically create a column named _id.
You could have a method, in the database helper (DataDBAdapter) such as :-
public Cursor getAllRowsAsCursor()
{
String[] columns = new String[]{"rowid AS " + BaseColumns._ID,"*"}
return = mDB.query(TBL_MYTABLE,null,null,null,null,null,null)
}
The ManageList method could then be :-
private void manageListView(Context context) {
myCursor = dbhelper.getAllRowsAsCursor();
// Only setup the adapter and the ListView if the adapter hasn't been setup
if(arrayAdapter == null)
{
// Instantiate the adapter
arrayAdapter = new SimpleCursorAdapter(context,android.R.layout.simple_list_item_1,myCursor,new String[]{DataAdapter.COl_MYTABLE_PHONENAME},newint[]{android.R.id.text1},0);
display_contacts1.setAdapter(arrayAdapter); //<<<<<<<<<< Tie the adpater to the ListView
// Set the ListViews OnItemClick Listener
display_contacts1.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
String namedisplay = arrayAdapter.getItem(position); //<<<<<<<<<< this gets the phone name
String phonenumber = myCursor,getString(myCursor.getColumnIndex(DataAdapter.COL_MYTABLE_PHONENUMBER);
Toast.makeText(view.getContext(), namedisplay + " Selected for Communication", Toast.LENGTH_SHORT).show();
Toast.makeText(view.getContext(), phonenumber, Toast.LENGTH_SHORT).show();
}
});
} else {
arrayAdapter.swapCursor(myCursor);
}
Notes
MyCursor would be declared as a class variable e.g. Cursor MyCursor;
Instaed of
ArrayAdapter<String> arrayAdapter; you would have
SimpleCursorAdapter arrayAdapter;
The above is in-principle code and has not been tested, so there may be errors and/or omissions.
Working Example
The following is the code based upon the code from the previous question asked (which this appears to follow on from). It has two ListViews the old and a new one that uses a SimpleCursorAdapter. Clicking an item display phone number and also id. Lon Clicking an Item deletes that item (refreshing both ListViews).
DataDBAdapter.java has two new methods (so add these) :-
//<<<<<<<<<< ADDED
public Cursor getAllRowsAsCursor() {
return mDB.query(TBL_MYTABLE,null,null,null,null,null,null);
}
public int delete(long id) {
String whereclause = COL_MYTABLE_ID + "=?";
String[] whereargs = new String[]{String.valueOf(id)};
return mDB.delete(TBL_MYTABLE,whereclause,whereargs);
}
SelectModemFragment.java is now :-
public class SelectModemFragment extends Fragment {
private SelectModemViewModel mViewModel;
ListView display_contacts1;
ArrayAdapter<String> arrayAdapter;
ArrayList<String> thelist;
DataDBAdapter dbhelper;
//<<<<<<<<<< ADDED
ListView display_contacts2;
SimpleCursorAdapter sca;
Cursor MyCursor;
public static SelectModemFragment newInstance() {
return new SelectModemFragment();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.select_modem_fragment, container, false);
display_contacts1 = view.findViewById(R.id.lv001); //<<<<<<<<<< top listview ArrayAdapter<String>
display_contacts2 = view.findViewById(R.id.lv002);
dbhelper = new DataDBAdapter(view.getContext());
AddSomeData();
manageListView(view.getContext());
manageListView2();
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mViewModel = ViewModelProviders.of(this).get(SelectModemViewModel.class);
// TODO: Use the ViewModel
}
//Sets up the ListView if not already setup
private void manageListView(Context context) {
thelist = dbhelper.getAllRowsAsList(); //<<<<<<<<<< extract the list (just the phone names) from the database
// Only setup the adapter and the ListView if the adapter hasn't been setup
if (arrayAdapter == null) {
// Instantiate the adapter
arrayAdapter = new ArrayAdapter<>(context,android.R.layout.simple_list_item_1,thelist); //<<<<<<<<<< list included
display_contacts1.setAdapter(arrayAdapter); //<<<<<<<<<< Tie the adpater to the ListView
// Set the ListViews OnItemClick Listener
display_contacts1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String name = arrayAdapter.getItem(position); //<<<<<<<<<< this gets the phone name
Toast.makeText(view.getContext(),"You clicked the phone named " + name,Toast.LENGTH_SHORT).show();
}
});
} else {
//<<<<<<<<<< MODIFIED to cope with changes (needs to rebuild the array within the adpater)
arrayAdapter.clear();
for (String s: thelist) {
arrayAdapter.add(s);
}
arrayAdapter.notifyDataSetChanged();
}
}
//<<<<<<<<<< ADDED FOR CursorAdapter
private void manageListView2() {
MyCursor = dbhelper.getAllRowsAsCursor();
if (sca == null) {
sca = new SimpleCursorAdapter(
getContext(),
android.R.layout.simple_list_item_1,
MyCursor,
new String[]{DataDBAdapter.COl_MYTABLE_PHONENAME},
new int[]{android.R.id.text1},
0
);
display_contacts2.setAdapter(sca);
display_contacts2.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(view.getContext(),
"You Clicked the phone name " +
MyCursor.getString(MyCursor.getColumnIndex(DataDBAdapter.COl_MYTABLE_PHONENAME)) +
". The phonenumber is " +
MyCursor.getString(MyCursor.getColumnIndex(DataDBAdapter.COL_MYTABLE_PHONENUMBER)) +
". The ID (as passed) is " + String.valueOf(id) +
". The ID (from Cursor) is " + String.valueOf(MyCursor.getLong(MyCursor.getColumnIndex(DataDBAdapter.COL_MYTABLE_ID)))
,
Toast.LENGTH_SHORT).show();
}
});
//<<<<<<<<<< EXTRA delete row on long click
display_contacts2.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
dbhelper.delete(id);
manageListView2();
manageListView(getContext());
return true;
}
});
} else {
sca.swapCursor(MyCursor);
}
}
// Add some testing data (only if none already exists)
private void AddSomeData() {
if (DatabaseUtils.queryNumEntries(dbhelper.getWritableDatabase(),DataDBAdapter.TBL_MYTABLE) < 1) {
dbhelper.insert("Phone 1", "0000000000");
dbhelper.insert("Phone 2", "1111111111");
}
}
#Override
public void onResume() {
super.onResume();
manageListView2();
manageListView(getContext());
}
#Override
public void onDetach() {
super.onDetach();
MyCursor.close();
}
}

Get ID from database onClick ListView

I'm using SQLite in my app. I have a listView which is populated with values from the database.
When I click on an item from the listview, I go to another page, and I would like ( with an intent), to transfer the ID FROM THE DATABASE. The problem is that I'm only transfering the ID from the position of my listView, which is wrong. For example, let's say I have :
ID Name
1 David
2 Joseph
My listView will display both names. But if I delete David, the ID i'm getting when i click in Joseph is 1 and not 2 . And that's the problem !
So : I want to retrieve the ID from my database and not from my listView when I click on an item
Here's my method in my helper : UPDATED !
public Cursor getAllCours()
{
String Query = ("select ID as _id, nom from " + TABLE_COURS);
Open();
Cursor cursor = db.rawQuery(Query, null);
return cursor;
}
And how I display it in my Activity :
Cursor cursor = dbhelper.getAllCours();
String[] from = { "nom" }; int[] to = { android.R.id.text1 };
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, cursor, from, to, 0);
lv.setAdapter(adapter);
And finally, my listviewClickListener :
lv.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//I THINK THE ERROR IS HERE !
long itemid= lv.getItemIdAtPosition(i);
int id= (int)itemid;
String a =lv.getItemAtPosition(i).toString();
Intent b = new Intent(AffichageCours.this,AffichageNotes.class);
Bundle args = new Bundle();
args.putString("nom_cours",a);
args.putInt("id",id);
b.putExtras(args);
startActivity(b);
}
});
}
My TABLE_COURS columns:
private static final String TABLE_COURS = "cours";
private static final String COLONNE_IDCOURS = "ID";
private static final String COLONNE_COURS = "nom";
private static final String CREATE_COURS ="CREATE TABLE cours " +
"("+COLONNE_IDCOURS+" INTEGER PRIMARY KEY AUTOINCREMENT , "
+COLONNE_COURS+" TEXT NOT NULL)";
How i delete with my Context Menu :
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
switch(item.getItemId())
{
case R.id.supprimer:
dbhelper.deleteCours(lv.getItemAtPosition(info.position).toString());
adapter.remove(adapter.getItem(info.position)); //the error is here..
adapter.notifyDataSetChanged();
return true;
Thank you guys !
I think the problem is that you are asking for the Id of the row in the ListView not the actual data that row is holding up. In the onItemClick method change this:
long itemid= lv.getItemIdAtPosition(i);
For this:
String courId = adapter.getItem(i);
The key here is to try to get the data from the ArrayAdapter not directly from the ListView.
You should have use Java Objects so it will be easy for you.
Suppost you have stored Contacts in dataBase(contains fields: Name, Mobile and Address). So create a POJO for that:
class Contacts{
private String name;
private String mobile;
private String address;
//write getters and setters
}
Then, whenever you are accessing database fetch all contacts you want to show and store in ArrayList<Contacts> mContactList;
And then pass this list in your ListView's adapter to show data in listView.
CustomAdapter adapter = new CustomAdapter(context, layoutResource, mContactList);
Then you can retrieve the object on clicking a particular list item on the basis of position;
lv.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Contacts contact = mContactList.get(i);
// now you can do whatever you want;
}
});
Since you are not using a custom adapter, why dont you try this inside onItemClickListener
String idThatYouWant = listeCours.get(i).getId();

setOnItemClickListener on ListView how to show database values

I have a ListView with Contact info(name, phone number) so i want when i click in the contact name i want to show its name and phone number in a dialog box (which a have a code for it already) which is:
public void ShowMessage(String titulo,String msg){
AlertDialog.Builder dialogo = new AlertDialog.Builder(this);
dialogo.setMessage(msg);
dialogo.setTitle(titulo);
dialogo.setNeutralButton("OK", null);
dialogo.show();
}
Then i have seen about the setOnItemClickListener but when i try to put this up in my .java file it doens't even suggest the code, does anyone know why or how to do it?
EDIT:
//LISTVIEW database CONTATO
ListView user = (ListView) findViewById(R.id.lvShowContatos);
//String = simple value ||| String[] = multiple values/columns
String[] campos = new String[] {"nome", "telefone"};
list = new ArrayList<String>();
Cursor c = db.query( "contatos", campos, null, null, null, null, null);
c.moveToFirst();
String lista = "";
if(c.getCount() > 0) {
while(true) {
list.add(c.getString(c.getColumnIndex("nome")).toString());
if(!c.moveToNext()) break;
}
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, list);
user.setAdapter(adapter);
that is the code of my listview/adapter
OBS: better if you can explain (no tuts link (better if possible))
(I see that you are processing a Cursor yourself and using an ArrayAdapter, understand that a SimpleCursorAdapter does this for you. See my note below.)
Anyway, change your Cursor into a class variable and try adding this in onCreate():
user.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
c.moveToPosition(position);
String nome = c.getString(c.getColumnIndex("nome"));
String telefone = c.getString(c.getColumnIndex("telefone"));
showMessage(nome, telefone);
}
});
You aren't specific on how the title and message correlate to the contact's name, so I made that part up.
A class variable is simply a variable defined in a place that makes it visible to the entire class. For example this turns c into a class variable so you can use it in onItemClick():
public class MyActivity extends Activity {
Cursor c;
public void onCreate(...) {
...
c = db.query( "contatos", campos, null, null, null, null, "nome");
...
}
}
Understand that you can simplify how you read your contacts:
list = new ArrayList<String>();
Cursor c = db.query("contatos", campos, null, null, null, null, "nome");
int nameIndex = c.getColumnIndex("nome");
while(c.moveToNext()) {
list.add(c.getString(nameIndex));
}
I made a couple changes:
You only need to fetch the index of the "nome" column once, it won't change unless you change the Cursor.
moveToFirst() returns true if there is data to read and false if not.
This is faster to write and faster to run than your existing method.
A SimpleCursorAdapter is the standard adapter to bind data from your Cursor to a ListView. This will give you the same results as your original method, but with much less code.
How to use a SimpleCursorAdapter:
Cursor c = db.query("contatos", campos, null, null, null, null, "nome");
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1, c,
new String[] {"nome"}, new int[] {android.R.id.text1});
user.setAdapter(adapter);
Assuming the adapter used in your ListView has a custom type (I'll call it ContactInfo), the following should work.
getListView().setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// Get String provided to this particular row
ContactInfo info = getListView().getAdapter().getItem(position);
// Construct title, message etc from information within info
showMessage("Contact Info", info);
}
});

Move to another activity by click on listview item, android

I tried to make an android app, that populate some data from sqlite database to a list view
using ArrayAdapter.
The list where I store data is like this:
private String[] allUserColumns = { MySQLiteHelper.COLUMN_USERID,
MySQLiteHelper.COLUMN_USERNAME };
I want to move to another activity passing the ID related to user name by click at a listview item.
I know that I should use setOnItemClickListener method
but actually I don't know how to do that.
I mean how to get the ID, and how to set the setOnItemClickListener Method to make such task.
please any one can help me with a specific code ?
i have done this with this way
first fire query like
public Cursor columnValues() throws SQLException{
Cursor mCursor = db.query(Player_Table,
new String[] {Player_Name,_id},null,null, null, null, null);
//Cursor mCursor = mDb.rawQuery("Select",null);
if (mCursor != null)
{
mCursor.moveToFirst();
}
return mCursor;
}
then receive like this
ArrayList<String> first = new ArrayList<String>();
ArrayList<String> id_list = new ArrayList<String>();
cursor = dbm.columnValues();
cursor.moveToFirst();
startManagingCursor(cursor);
for(int i=0;i<cursor.getCount();i++){
// Received values of player name
// from player table
String reciv = cursor.getString(cursor.getColumnIndex(DBManager.Player_Name));
String P_id= cursor.getString(cursor.getColumnIndex(DBManager._id));
first.add(reciv);
id_list.add(P_id);
cursor.moveToNext();
}
//ARRAY OF ID
String[] _id = id_list.toArray(new
String[id_list.size()]);
player.setAdapter(new ArrayAdapter<String>
(this,android.R.layout.simple_list_item_1 , first));
player.setOnItemClickListener(Activity.this);
and then the click listener
#Override
public void onItemClick(AdapterView arg0, View arg1, int position,
long id) {
i = new Intent(Add_Modify_Delete_Player.this,
ModifyDeletePlayer.class);
System.out.println(_id[position]);
i.putExtra("Id", _id[position]);
startActivity(i);
}

onListItemClick, what statement do I need to get the value?

i can add to a db and list as a listview.
When I click a list item using onListItemClick, what statement do I
need to get the value?
Thanks in advance.
public class Main extends ListActivity {
private static String[] FROM = { _ID, DESCRIPTION, UN };
private static String ORDER_BY = DESCRIPTION + " ASC";
private static int[] TO = {R.id.itemrowid, R.id.itemdescription, R.id.itemun };
private EventsData events;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
events = new EventsData(this);
try {
Cursor cursor = getEvents();
showEvents(cursor);
} finally {
events.close();
}
**public void onListItemClick(ListView parent, View v, int position, long id) {
// What statement to put here to get the value of _ID,DESCRIPTION, UN
// selected**?
}
private Cursor getEvents() {
// Perform a managed query. The Activity will handle closing
// and re-querying the cursor when needed.
SQLiteDatabase db = events.getReadableDatabase();
Cursor cursor = db.query(TABLE_NAME, FROM, null, null, null,
null, ORDER_BY);
startManagingCursor(cursor);
return cursor;
}
private void showEvents(Cursor cursor) {
// Set up data binding
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
R.layout.item, cursor, FROM, TO);
setListAdapter(adapter);
}
First, you need to obtain item at clicked position:
Cursor cursor = getListAdapter().getItem(position);
Then you can get data from this cursor (I don't know what types do you use, so just for example it will be int and String):
int id = cursor.getInt(cursor.getColumnIndex(_ID));
String description = cursor.getString(cursor.getColumnIndex(DESCRIPTION));
See documentation for Cursor's available methods.
Adding to sergey answer you can also directly see what View was clicked and use findViewById() to find the components, therefore, the values you want.
This is just an alternative being the method Sergey much less 'patchy'

Categories

Resources