android_one
android_one

Reputation: 425

how does cursor know which item is clicked in listview?

I have a activity displaying call logs in a ListView. The adapter used here to populate listview extends CursorAdapter. Listview is set to onItemClickListener(..). My Question is whenever an item is clicked how does cursor get the data? how does cursor know which position is clicked and need to get data from clicked position only? I have provided a code snippnet.

public class CallLog extends Activity
{
   ListView mListView;
   Cursor cursor;

   //other variables


   public void OnCreate()
   {
        setContentView(R.layout.calllog);

        //SQLiteDatabaseInstance db
        cursor = db.query(...parameters to get all call logs...);
        mListView.setOnItemClickListener(this);
   }

   public void OnItemClick( // all arguments... )
   {
         //there is a column name 'NAME' in call log table in database 
         String name = cursor.getString(cursor.getColumnIndex(Database.NAME))

         //here name is obtained of the clicked item.
   }

Cursor is a result set. how does the cursor know which item is clicked? What can be the methods implicitly called by cursor that gives it position of clicked item?

If there are any links of similar question then pls provide.

I hope I am able to make you understand the question. Thank you

Upvotes: 4

Views: 1531

Answers (4)

TwinStar
TwinStar

Reputation: 21

You should use cursor.moveToposition(position) inside function to get to the position of that clicked item. After that you apply this and when you will click on any item, the cursor will be set on that item and then you can use that particular item for your operation.

Upvotes: 1

deepa
deepa

Reputation: 2494

     mListView..setOnItemClickListener(new OnItemClickListener() {

    @Override
    public void onItemClick(AdapterView<?> arg0,
        View view, int position, long id) {
        // here position gives the which item is clicked..

        }
    });

Additionally check this link for ListView ListView and ListActivity

It may help you..

Upvotes: 0

jtt
jtt

Reputation: 13541

Specifically it is NOT the Cursor that knows who clicked on what. This is actually handled by the Adapter. The adapter is used to group elements together and allow abstraction as such that they can be handled in a uniform way.

Any form of list, always has an adapter, and this is exactly why the adapter works so well. If you look at a Custom Listview with a Custom Adapter, you'll see exactly how this is done.

Example:

http://android.vexedlogic.com/2011/04/02/android-lists-listactivity-and-listview-ii-%E2%80%93-custom-adapter-and-list-item-view/

Upvotes: 1

Nataliia.dev
Nataliia.dev

Reputation: 2972

Try this:

    @Override
   public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//move cursor to clicked row
     cursor.moveToPosition(position);
}

Upvotes: 2

Related Questions