Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
428 views
in Technique[技术] by (71.8m points)

android - How to get the item id in an onItemClick handler

I have a category table with two columns category_id and name. I have created a data helper class named CategoryDataHelper. I have a method named getCategoryCursor() of that helper class which fetches the id and the name from the category table and returns the cursor. Using that cursor, I have used SimpleCursorAdapter to display the 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 an OnItemClickListener and send an Intent with the category_id of the selected category. How can I get the id in the onItemClick() method?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

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

or use "category_id" or whatever the name of your column is in place of CategoryDataHelper.ID.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...