- notifyDataSetChange not working from custom adapter
- 13 Answers 13
- notifyDataSetChanged not working on RecyclerView
- 8 Answers 8
- But wait, there is more.
- NotifyDataSetChanged не работает с RecyclerView
- NotifyDataSetChange не работает с пользовательским адаптером
- не работает notifyDataSetChanged для listview
- 4 ответа 4
- Всё ещё ищете ответ? Посмотрите другие вопросы с метками android listview adapter или задайте свой вопрос.
- Связанные
- Похожие
- Подписаться на ленту
notifyDataSetChange not working from custom adapter
When I repopulate my ListView , I call a specific method from my Adapter .
Problem:
When I call updateReceiptsList from my Adapter , the data is refreshed, but my ListView doesn’t reflect the change.
Question:
Why doesn’t my ListView show the new data when I call notifyDataSetChanged ?
Adapter:
found Workaround
Just to have some functional code i do now:
Works, but not how it is supposed to work.
13 Answers 13
Change your method from
So you keep the same object as your DataSet in your Adapter.
I have the same problem, and i realize that. When we create adapter and set it to listview, listview will point to object somewhere in memory which adapter hold, data in this object will show in listview.
if we create an object for adapter with another data again and notifydatasetchanged():
this will do not affect to data in listview because the list is pointing to different object, this object does not know anything about new object in adapter, and notifyDataSetChanged() affect nothing. So we should change data in object and avoid to create a new object again for adapter
As I have already explained the reasons behind this issue and also how to handle it in a different answer thread Here. Still i am sharing the solution summary here.
One of the main reasons notifyDataSetChanged() won’t work for you — is,
Your adapter loses reference to your list.
When creating and adding a new list to the Adapter . Always follow these guidelines:
Источник
notifyDataSetChanged not working on RecyclerView
I am getting data from server and then parsing it and storing it in a List. I am using this list for the RecyclerView’s adapter. I am using Fragments.
I am using a Nexus 5 with KitKat. I am using support library for this. Will this make a difference?
Here is my code: (Using dummy data for the question)
After getting data from server, parseResponse() is called.
But I don’t get the data displayed in the view. What am I doing wrong?
I don’t get any logs after this. Shouldn’t getItemCount() in adapter should be called again?
8 Answers 8
In your parseResponse() you are creating a new instance of the BusinessAdapter class, but you aren’t actually using it anywhere, so your RecyclerView doesn’t know the new instance exists.
You either need to:
- Call recyclerView.setAdapter(mBusinessAdapter) again to update the RecyclerView’s adapter reference to point to your new one
- Or just remove mBusinessAdapter = new BusinessAdapter(mBusinesses); to continue using the existing adapter. Since you haven’t changed the mBusinesses reference, the adapter will still use that array list and should update correctly when you call notifyDataSetChanged() .
Try this method:
a little time consuming, but it should work.
Just to complement the other answers as I don’t think anyone mentioned this here: notifyDataSetChanged() should be executed on the main thread (other notify methods of RecyclerView.Adapter as well, of course)
From what I gather, since you have the parsing procedures and the call to notifyDataSetChanged() in the same block, either you’re calling it from a worker thread, or you’re doing JSON parsing on main thread (which is also a no-no as I’m sure you know). So the proper way would be:
PS Weird thing is, I don’t think you get any indications about the main thread thing from either IDE or run-time logs. This is just from my personal observations: if I do call notifyDataSetChanged() from a worker thread, I don’t get the obligatory Only the original thread that created a view hierarchy can touch its views message or anything like that — it just fails silently (and in my case one off-main-thread call can even prevent succeeding main-thread calls from functioning properly, probably because of some kind of race condition)
Moreover, neither the RecyclerView.Adapter api reference nor the relevant official dev guide explicitly mention the main thread requirement at the moment (the moment is 2017) and none of the Android Studio lint inspection rules seem to concern this issue either.
But, here is an explanation of this by the author himself
I had same problem. I just solved it with declaring adapter public before onCreate of class.
at last I have called:
May this will helps you.
Although it is a bit strange, but the notifyDataSetChanged does not really work without setting new values to adapter. So, you should do:
This has worked for me.
Clear your old viewmodel and set the new data to the adapter and call notifyDataSetChanged()
In my case, force run #notifyDataSetChanged in main ui thread will fix
I always have this problem that I forget that the RecyclerView expects a new instance of a List each time you feed the adapter.
Having the «same» List (reference) means not declaring «new» even if the List size changes, because the changes performed to the List also propagates to other Lists (when they are simply declared as this.localOtherList = myList ) emphasis on the keyword being «=«, usually components that compare collections make a copy of the result after the fact and store it as «old», but not Android DiffUtil.
So, if a component of yours is giving the same List each and every time you submit it, the RecyclerView won’t trigger a new layout pass. The reason is that. AFAIR, before the DiffUtil even attempts to apply the Mayers algorithm, there is a line doing a:
I am not sure how much «good practice» does de-referencing within the same system is actually defined as «good» . Specially since a diff algorithm is expected to have a new(revised) vs old(original) component which SHOULD in theory dereference the collection by itself after the process has ended but. who knows.
But wait, there is more.
doing new ArrayList() dereferences the List, BUT for some reason Oracle decided that they should make a second «ArrayList» with the same name but a different functionality.
This ArrayList is within the Arrays class.
* * @param the class of the objects in the array * @param a the array by which the list will be backed * @return a list view of the specified array */ @SafeVarargs @SuppressWarnings(«varargs») public static List asList(T. a) < return new ArrayList<>(a); //Here >
This write-through is funny because if you:
Not only does the List dispatched obeys the dereferencing on each submission, but when the localInts variable is altered,
this alteration is also passed to the List WITHIN the RecyclerView, this means that on the next submission, the (newList == mList) will return «false» allowing the DiffUtils to trigger the Mayers algorithm, BUT the areContentsTheSame(@NonNull T oldItem, @NonNull T newItem) callback from the ItemCallback interface will throw a «true» when reaching index 1. basically, saying «the index 1 inside RecyclerView (that was supposed to be 2 in th previous version) was always 4», and a layout pass will still not perform.
Источник
NotifyDataSetChanged не работает с RecyclerView
Я получаю данные с сервера, а затем разбираю его и сохраняю в списке. Я использую этот список для адаптера RecyclerView. Я использую фрагменты.
Я использую Nexus 5 с KitKat. Для этого я использую библиотеку поддержки. Будет ли это иметь значение?
Вот мой код: (Использование фиктивных данных для вопроса)
После получения данных с сервера вызывается parseResponse() .
Но я не получаю данные, отображаемые в представлении. Что я делаю неправильно?
После этого я не получаю никаких журналов. Не следует ли снова вызывать getItemCount() в адаптере?
В вашем parseResponse() вы создаете новый экземпляр класса BusinessAdapter , но вы на самом деле его не используете, поэтому ваш RecyclerView не знает, что новый экземпляр существует.
- Вызовите recyclerView.setAdapter(mBusinessAdapter) снова, чтобы обновить ссылку адаптера RecyclerView, чтобы указать на новую.
Или просто удалите mBusinessAdapter = new BusinessAdapter(mBusinesses); , чтобы продолжить использование существующего адаптера. Поскольку вы не изменили ссылку mBusinesses , адаптер все равно будет использовать этот список массивов и должен корректно обновляться при вызове notifyDataSetChanged() .
Попробуйте этот метод:
немного времени, но он должен работать.
У меня была такая же проблема. Я просто решил это с объявлением adapter public перед onCreate класса.
Наконец я позвонил:
Пусть это поможет вам.
Просто чтобы дополнить другие ответы, поскольку я не думаю, что кто-то упомянул об этом здесь: notifyDataSetChanged() должен выполняться в основном потоке (другие notify методы RecyclerView.Adapter конечно)
Из того, что я собираю, поскольку у вас есть процедуры синтаксического анализа и вызов notifyDataSetChanged() в том же блоке, либо вы вызываете его из рабочего потока, либо выполняете разбор JSON в основном потоке (который также нет-нет, как я уверен, вы знаете). Таким образом, правильный способ:
PS Странно то, что я не думаю, что у вас есть какие-либо указания на предмет основного потока из IDE или журналов времени выполнения. Это только из моих личных наблюдений: если я вызываю notifyDataSetChanged() из рабочего потока, я не получаю обязательный Только исходный поток, который создал иерархию представлений, может коснуться своего сообщения о представлении или что-то в этом роде — он просто терпит неудачу (и в моем случае один вызов вне основного потока может даже предотвратить правильное выполнение последующих вызовов основного потока, возможно, из-за какого-то состояния гонки)
Источник
NotifyDataSetChange не работает с пользовательским адаптером
Когда я переписываю свой ListView , я вызываю определенный метод из моего Adapter .
Проблема :
Когда я вызываю updateReceiptsList из моего Adapter , данные обновляются, но мой ListView не отражает изменения.
Вопрос :
Почему мой ListView показывает новые данные, когда я вызываю notifyDataSetChanged ?
Адаптер :
Найдено обходное решение
Просто, чтобы иметь некоторый функциональный код, который я делаю сейчас:
Работает, но не так, как он должен работать.
Измените свой метод
Таким образом, вы сохраняете тот же объект, что и ваш DataSet в своем адаптере.
У меня такая же проблема, и я понимаю это. Когда мы создаем адаптер и устанавливаем его в listview, listview укажет на объект где-то в памяти, который удерживается адаптером, данные в этом объекте будут отображаться в списке.
Если мы снова создадим объект для адаптера с другими данными и notifydatasetchanged ():
Это не повлияет на данные в списке, потому что список указывает на другой объект, этот объект ничего не знает о новом объекте в адаптере, а notifyDataSetChanged () ничего не влияет. Поэтому мы должны изменить данные в объекте и не создавать новый объект для адаптера
Как я уже объяснил причины этой проблемы, а также как обрабатывать ее в другом потоке ответов здесь . Тем не менее, я разделяю резюме решения здесь.
Одна из основных причин notifyDataSetChanged() не будет работать для вас – есть,
Ваш адаптер теряет ссылку на ваш список .
При создании и добавлении нового списка в Adapter . Всегда следуйте этим рекомендациям:
- Инициализируйте arrayList , объявив его глобально.
- Добавьте список в адаптер напрямую, не проверяя нулевые и пустые значения. Установите адаптер в список напрямую (не проверяйте какое-либо условие). Адаптер гарантирует, что везде, где вы вносите изменения в данные arrayList он позаботится об этом, но никогда не потеряет ссылку.
- Всегда изменяйте данные в самом массиве (если ваши данные совершенно новы, чем вы можете вызвать adapter.clear() и arrayList.clear() прежде чем добавлять данные в список), но не устанавливайте адаптер, т. arrayList.clear() Если новые данные arrayList в список arrayList не только adapter.notifyDataSetChanged()
Надеюсь это поможет.
Возможно, попробуйте обновить ListView:
EDIT: Еще одна мысль пришла мне в голову. Для записи попытайтесь отключить кеш-представление списка:
У меня была такая же проблема с использованием ListAdapter
Я позволяю Android Studio применять методы для меня, и это то, что я получил:
Проблема в том, что эти методы не называют super реализациями, поэтому notifyDataSetChange никогда не вызывается.
Удалите эти переопределения вручную или добавьте супервызов, и он должен снова работать.
Источник
не работает notifyDataSetChanged для listview
Здравствуйте! помогите найти ошибку. не обновляется список ни в какую у меня. перерыл stackOverflow, почистил свой List
и записал новые объекты. но всё равно не работает. после ответа сервера:
4 ответа 4
Потому что Вы заполняете элемент списка только когда convertView == null. То есть единожды и в количестве, умещающемся на экране без прокрутки. Остальные данные просто игнорируются. Схематично код getView должен выглядеть так:
Тебе нужно в адаптер новый массив передать и после этого обновить адаптер сделай в адаптере метод
Попробуйте после метода getItem добавить метод:
Чтобы не возвращать позицию.
Всё ещё ищете ответ? Посмотрите другие вопросы с метками android listview adapter или задайте свой вопрос.
Связанные
Похожие
Подписаться на ленту
Для подписки на ленту скопируйте и вставьте эту ссылку в вашу программу для чтения RSS.
дизайн сайта / логотип © 2021 Stack Exchange Inc; материалы пользователей предоставляются на условиях лицензии cc by-sa. rev 2021.10.18.40487
Нажимая «Принять все файлы cookie» вы соглашаетесь, что Stack Exchange может хранить файлы cookie на вашем устройстве и раскрывать информацию в соответствии с нашей Политикой в отношении файлов cookie.
Источник