Android ListView not refreshing after notifyDataSetChanged with data as Map

守給你的承諾、 提交于 2019-12-01 23:25:12

You must add a method to your CategoryAdapter to change the instance's list, like so

public class CategoryAdapter extends BaseAdapter {
ArrayList<Category> list = new ArrayList<Category>();
Context context;

public CategoryAdapter(Context context, Map<String, Category> categories) {
    this.context = context;
    list.clear();
    list.addAll(categories.values());
}

@Override
public int getCount() {
    return list.size();
}

//ADD THIS METHOD TO CHANGE YOUR LIST
public void addItems(Map<String, Category> categories){
    list.clear();
    list.addAll(categories.values());
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    final ViewHandler handler;

    LayoutInflater inflater = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    if (convertView == null) {
        convertView = inflater.inflate(R.layout.category_list_item, null);
        handler = new ViewHandler();
        handler.name = (TextView) convertView.findViewById(R.id.name);
        handler.count = (TextView) convertView.findViewById(R.id.count);
        convertView.setTag(handler);
    } else {
        handler = (ViewHandler) convertView.getTag();
    }
    Category category = list.get(position);
    handler.name.setText(category.getMenuName());
    handler.count.setText(category.getCount() + "");
    if (category.getCount() <= 0) {
        handler.count.setVisibility(View.INVISIBLE);
    } else {
        handler.count.setVisibility(View.VISIBLE);
    }

    return convertView;
}
}

and change your loadCategories like so (note that I call the addItems() before notifyDataSetChanged()

private void loadCategories() {
sampleDB = openOrCreateDatabase(AppConstants.DB_NAME, MODE_PRIVATE,
        null);
Cursor menuCursor = sampleDB.rawQuery("select * from menu", null);

categories.clear();
while (menuCursor.moveToNext()) {
    String menu = menuCursor.getString(menuCursor
            .getColumnIndex("name"));
    String id = menuCursor.getString(menuCursor.getColumnIndex("id"));
    Category category = new Category(menu, id);
    categories.put(id, category);
}
menuCursor.close();

//ADD CALL TO addItems TO UPDATE THE LIST OF THE categoryAdapter instance
categoryAdapter.addItems(categories);
categoryAdapter.notifyDataSetChanged();
}

have you tried saying:

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