How to refresh an Android ListView
after adding/deleting dynamic data?
相关问题
- How can I create this custom Bottom Navigation on
- Bottom Navigation View gets Shrink Down
- How to make that the snackbar action button be sho
- Listening to outgoing sms not working android
- How to create Circular view on android wear?
相关文章
- android开发 怎么把图片放入drawable的文件夹下
- android上如何获取/storage/emulated/下的文件列表
- androidStudio有个箭头不认识
- SQLite不能创建表
- Windows - Android SDK manager not listing any plat
- Animate Recycler View grid when number of columns
- Why is the app closing suddenly without showing an
- Android OverlayItem.setMarker(): Change the marker
Please ignore all the
invalidate()
,invalidateViews()
,requestLayout()
, ... answers to this question.The right thing to do (and luckily also marked as right answer) is to call
notifyDataSetChanged()
on your Adapter.Troubleshooting
If calling
notifyDataSetChanged()
doesn't work all the layout methods won't help either. Believe me theListView
was properly updated. If you fail to find the difference you need to check where the data in your adapter comes from.If this is just a collection you're keeping in memory check that you actually deleted from or added the item(s) to the collection before calling the
notifyDataSetChanged()
.If you're working with a database or service backend you'll have to call the method to retrieve the information again (or manipulate the in memory data) before calling the
notifyDataSetChanged()
.The thing is this
notifyDataSetChanged
only works if the dataset has changed. So that is the place to look if you don't find changes coming through. Debug if needed.ArrayAdapter vs BaseAdapter
I did find that working with an adapter that lets you manage the collection, like a BaseAdapter works better. Some adapters like the ArrayAdapter already manage their own collection making it harder to get to the proper collection for updates. It's really just an needless extra layer of difficulty in most cases.
UI Thread
It is true that this has to be called from the UI thread. Other answers have examples on how to achieve this. However this is only required if you're working on this information from outside the UI thread. That is from a service or a non UI thread. In simple cases you'll be updating your data from a button click or another activity/fragment. So still within the UI thread. No need to always pop that runOnUiTrhead in.
Quick Example Project
Can be found at https://github.com/hanscappelle/so-2250770.git. Just clone and open the project in Android Studio (gradle). This project has a MainAcitivity building a
ListView
with all random data. This list can be refreshed using the action menu.The adapter implementation I created for this example ModelObject exposes the data collection
Code from the MainActivity
More Information
Another nice post about the power of listViews is found here: http://www.vogella.com/articles/AndroidListView/article.html