Skip to content Skip to sidebar Skip to footer

Android Listview Not Refreshing After Notifydatasetchanged With Data As Map

I used list adapter with map values as data. When I use adapter.notifyDataSetChanged(); the data in the list not updating. But if I replace the Map with ArrayList everything workin

Solution 1:

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

publicclassCategoryAdapterextendsBaseAdapter {
ArrayList<Category> list = newArrayList<Category>();
Context context;

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

@OverridepublicintgetCount() {
    return list.size();
}

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

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

    LayoutInflaterinflater= (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    if (convertView == null) {
        convertView = inflater.inflate(R.layout.category_list_item, null);
        handler = newViewHandler();
        handler.name = (TextView) convertView.findViewById(R.id.name);
        handler.count = (TextView) convertView.findViewById(R.id.count);
        convertView.setTag(handler);
    } else {
        handler = (ViewHandler) convertView.getTag();
    }
    Categorycategory= 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()

privatevoidloadCategories() {
sampleDB = openOrCreateDatabase(AppConstants.DB_NAME, MODE_PRIVATE,
        null);
CursormenuCursor= sampleDB.rawQuery("select * from menu", null);

categories.clear();
while (menuCursor.moveToNext()) {
    Stringmenu= menuCursor.getString(menuCursor
            .getColumnIndex("name"));
    Stringid= menuCursor.getString(menuCursor.getColumnIndex("id"));
    Categorycategory=newCategory(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();
}

Solution 2:

Post a Comment for "Android Listview Not Refreshing After Notifydatasetchanged With Data As Map"