How to get item id in onItemClick handler

I have a category table with two columns category_idand name. I created a data helper class with a name CategoryDataHelper. I have a method with the name of getCategoryCursor()this helper class that retrieves the identifier and name from the category table and returns the cursor. Using this cursor, I used SimpleCursorAdapterto display a list of categories. It is working fine.

public class Categories extends ListActivity  {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        categoryDataHelper = new CategoryDataHelper(getApplicationContext());
        Cursor categoryCursor  = categoryDataHelper.getCategoryCursor();
        ListAdapter adapter = new SimpleCursorAdapter (
                this,  
                android.R.layout.simple_list_item_1,
                categoryCursor,                                              
                new String[] { CategoryDataHelper.NAME },           
                new int[] {android.R.id.text1});  

        // Bind to our new adapter.
        setListAdapter(adapter);

        list = getListView();
        list.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // Here I want the category_id  
            }
        });
    }    
}

Now I want to implement OnItemClickListenerand send Intent from the category_idselected category. How can I get the id in a method onItemClick()?

+5
source share
4 answers

, . , , .

Cursor cursor = ((SimpleCursorAdapter) adapterView).getCursor();
cursor.moveToPosition(position);
long categoryId = cursor.getLong(cursor.getColumnIndex(CategoryDataHelper.ID));

"category_id" , CategoryDataHelper.ID.

+17

, ... !!! ... , :

Intent myIntent = new Intent(Clientes.this, Edc.class);
Cursor cursor = (Cursor) adapter.getItem(position);
myIntent.putExtra("CLIENTE_ID", cursor.getInt(cursor.getColumnIndex("_id")));
startActivity(myIntent);

(EDC).... :

int _clienteId = getIntent().getIntExtra("CLIENTE_ID", 0);
+2

inItemclick:

categoryCursor.moveToPosition(position);

?

+1

Using the SimpleCursorAdapterfunction onItemClickpasses in the database identifier for the selected item. So the solution is just

long category_id = id
+1
source

All Articles