在listview中只显示来自SQLite数据库的单列名称 - Android

时间:2017-09-13 07:04:53

标签: android sqlite listview

我需要在listview中只设置名字字段值。 我查询数据并获取所有值并在列表视图中显示它们。需要只显示名字

代码,

    import c...l.Database.ItemCRUDOperations;
    import c...l.Model.Item;

    List<Item> items;

    ListView listView = (ListView) findViewById(R.id.listView);

    itemCrud = new ItemCRUDOperations(this);
    itemCrud.open();

    items = itemCrud.getAllItems(); // returns id, first name, last name ...
    // i need to only show first name in list view, currently it is showing all fields in listview
   //I tried items.getFirstName() as I have getters and setters to it but not getting the value.

    itemCrud.close();

    ArrayAdapter<Item> adapter = new ArrayAdapter<>(this,
            android.R.layout.simple_list_item_1, items);
    listView.setAdapter(adapter);

3 个答案:

答案 0 :(得分:1)

试试这段代码:

...
List<String> firstNames = new ArrayList<>();
for (Item item : items) {
    firstNames.add(item.getFirstName);
}

ArrayAdapter<Item> adapter = new ArrayAdapter<>(this,
        android.R.layout.simple_list_item_1, firstNames);
listView.setAdapter(adapter);

或者您可以在toString()类中简单地覆盖Item方法:

@Override
public String toString() {
    return getFirstName();
}

答案 1 :(得分:0)

使用此选项获取仅包含firstName的列表:

List<String> firstNamelist = new ArrayList<>();
for(Item item : items){
    firstnameList.add(item.getFirstName());
}

然后将firstNameList传递给适配器:

ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
            android.R.layout.simple_list_item_1, firstNameList);

希望它有所帮助。

答案 2 :(得分:0)

另一个答案中已经建议的最简单的选项是创建字符串列表并将其传递给适配器而不是项目列表。

另一种更通用的方法是实现自己的列表适配器,覆盖方法getView,如下所示:

class ItemListAdapter extends ArrayAdapter<Item> {

    private static class ViewHolder {
        TextView firstName;
        TextView lastName;
        // More fields ...
    }

    ItemListAdapter(Context context, List<Item> items) {
        super(context, 0, items);
    }

    @Override
    @NonNull
    public View getView(final int position, View view, @NonNull ViewGroup parent) {
        final Item item = getItem(position);

        final ViewHolder viewHolder;
        if (view == null) {
            viewHolder = new ViewHolder();
            LayoutInflater inflater = LayoutInflater.from(getContext());
            view = inflater.inflate(R.layout.item_layout, parent, false);

            viewHolder.firstName = (TextView) view.findViewById(R.id.first_name_text_view);
            view.setTag(viewHolder);
        } else {
            viewHolder = (ItemListAdapter.ViewHolder) view.getTag();
        }

        viewHolder.firstName.setText(item.getFirstName());
        return view;
    }
}

通过这种方法,您将来可以在列表项中添加更多信息。