Get name of ListView item

老子叫甜甜 提交于 2019-12-10 12:17:46

问题


I can't get name of ListView item by click. I fill data from database with SimpleCursorAdapter, and when I click on item I want to get item name, but I recive data like this

android.content.ContentResolver$CursorWrapperInner@4054b988.

How I can get text from it?

There is m click listener:


protected void onListItemClick(ListView l, View v, int position, long id) {
    super.onListItemClick(l, v, position, id);
    Object object = this.getListAdapter().getItem(position);
    String item = object.toString();
    Log.i( TAG, "Name: " + item );
}


回答1:


Actually you got what you've called. Every object has a default toString() method which will return a String describe its class name and position in memory and that's the result you got there. You have to override this method to have a meaningful return value. For example, by casting Object to a meaningful object of your own

class Item{
    private String name;
    public void setName(String name){
        this.name = name;
    }
    public String getName(){
        return name;
    }
    public String toString(){
        return name; 
    }
}
protected void onListItemClick(ListView l, View v, int position, long id) {
    super.onListItemClick(l, v, position, id);
    Object object = this.getListAdapter().getItem(position);
    Item item = (Item) object;
    String name = item.getName() \\ or = item.toString(); it's the same
    Log.i( TAG, "Name: " + name );
}



回答2:


You can do it in one line of code instead

String str = listDishes.getItemAtPosition(arg2).toString();

where listDishes is the ListView that sets the adapter...



来源:https://stackoverflow.com/questions/7344816/get-name-of-listview-item

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!