sorry for stupid question. But really interesting and incomprehensible. In this session discussed about notifyDataSetChanged() method.
From documentation for this method - "called when the data set being observed has changed, and which when read contains the new state of the data". My English bad and I do not understand all. But I right if guess that method called when I need refresh ListView with new data set?
If I'm right then I'm confused. In the past and my first program I played with contacts api of android. And run some processing in an asynctask. At this time appeared dialog with progress bar and in the background, you could see how the state of ListView changed in real time. Data for ListView row changed via BindView.
Why? So I'm in something wrong. Explain please.
As i read it, BindView is only used with cursors, which are a specific type of a data set basically. You can have alternative data sets, there is for example an ArrayListAdapter in the API which uses an ArrayList as its dataset. In case that data set changes, notifyDataSetChanged() will have to be called to notify the list view that its bounds will have to be recalculated and its views have to be redrawn (and probably some more).
If you decide to write your own and create the possibility to modify the data shown in the list view through an adapter (one could imagine adding method like addObject(SomeObject o) in your home made adapter for example), then you'd call notifyDataSetChanged() in that method.
Similarly if you have a deleteObject(SomeObject x), if the remaining data set is larger than zero you'd call notifyDataSetChanged() or when the remaining data set is empty you'd call notifyDataSetInvalidated() which in turn will to some extra stuff like setting the so called empty view in the list if you have one specified.
Related
I am doing a side project of making an app (with Java since I already know it). I have a recyclerview which loads some data via the room database library. The elements of the recyclerview are clickable.
My problem is I want the user to be able to sort the recyclerview so that the most recently accessed items go to the top.
My original idea was to assign the entities to have two variables - a String list_name which also serves as the id, and an Int order_of_access. Also, in my ViewModel I have a getAllLists method which returns a livedata list. I have an onChanged listener in the fragment activity which nicely updates the recyclerview when data is added/removed.
When the user adds a new list, it is assigned an order_of_access of the listsize (+1). But when the user deletes a group of lists, or clicks on a list, I want to update the order_of_access, say with an updateOrderAccess method.
Do you think this is the best way of doing what I want?
Where should I place updateOrderAccess and how would you recommend it be written? Since the method getAllLists returns livedata, it is tempting to put updateOrderAccess in an observer in the fragment (in onChanged) - but this will obviously create an infinite loop. It seems more in the correct philosophy to put it in the ViewModel, but then how would you suggest the updateOrderAccess method to be written? I'm having some trouble conceptualising what I need.
I hope the question is not too vague - I will update it if you need more details.
Where should I place updateOrderAccess and how would you recommend it
be written?
I am so sure that you must write it in the view model, as long as updateOrderAccess() is editing the list which is observable then you have andexpose by that the ui state then you have to put it in view model, and the observers will be notified ( in this case it is recycle view) and it will redraw the list in the order you offered.
note: do not you ever update the state(ui data) outside the state holder so you implement UDF (unidirectional Data Flow) pattern.
see the references below to read more about UDF so you never get confused where to declare your functions by letting the architicture lead you:
Guide to app architecture
ui layer
state holders and ui state
Do you think this is the best way of doing what I want?
i am not very sure that i got exactly what your app do, but it seems like you want to re-order the elements of recycle view depending on the ui event (click) or data change (deleting or adding new element), now you have two choices:
if the order is very importnat to you that much you want to keep it even if the app has been destroyed
then you have to add a field in the room entity represent the ordering (let us call it order) and whenever the user click on the recycle view you have to update the rooms field "order" which is "flow" or "liveData" or any observable type, that will tell the view model that there is a changing in the data, now the view model have to re-order the new data by the field "order" and pass it to the recycle view to show it.
if your app do not have to save the order changes after the app been destroyed
then you can simply do that:
create list which is called "orderedList" you will put the list items in it by the right order, and another list called "unorderlist" which have getAllLists
for the first case where the ordering is being changed by user click, you
can declare a function in viewModel then use it in the ui
controller (your activity or fragment), so whenever the list item is
clicked this function just re-order the orderedList elements ( which
is observable, so the changes reflect on the ui ) just by change the
clicked item position to the front of the list.
for the second case where the ordering changes by data changes like
add or delet a list item in the database, then you have to compare
the legnth of orderlist and unorderlist legnth, if unorderList is
longer then it is an add situation else it is a delete situation, in
adding case just add the last item of unorderList to the orderList,
else you have to check the deleted item and delete it from
orderList.
I'm new to all of this and was making good progress but I have hit a brick wall with working out how to do the next thing. I am using Kotlin and have a Fragment with an associated Recyclerview Adapter. I would like to set OnClick (On or Off) against items in a row depending upon a value in the Fragment which could change at any time.
My adapter works fine to show and update the array of data and also to implement OnClick.
I have tried sending a data element via a constructor which changed in the fragment but always showed as the initial setting in the adapter. The same with trying to call a method.
Many other questions touch on the issue but only show snippets of code, and it seems that I'm not advanced enough to get them working successfully in my code.
Could anyone please provide a pointer to a working set of Kotlin code that includes parsing a variable from fragment to adapter - perhaps in Git or a tutorial. I'm sure that if I can study a working program I can move forward. Thank you.
It would have been better if you had included your Adapter and Fragment code in the question, that would have helped us in understanding how you have setup everything and what data model are you passing to adapter.
But looking at your question, one solution that comes to my mind is to add an enabled boolean in your data model that is displayed in the ViewHolder. Using this you can set view.clickable = model.enabled. Now whenever your "value in the Fragment" changes you can update this list and let the adapter rebind items.
Note that the above solution is when you want to selectively enable/disable clicks on individual items. If you want to do this for all items at once, it's better to create a variable in adapter that you can change from the Fragment, and inside the clickListener you can check the value of that adapter variable. If it's false, just return out of the click listener. Something like,
view.setOnClickListener {
if(adapterValue) {
// handle Click
}
}
If this approach doesn't help, I would ask you to add more context in your question and show what you have done so far.
To update a Listview we can do following two things:
1) Create a new ArrayAdapter and bind it to ListView everytime the data is updated.
this.listView.setAdapter(new ArrayAdapter(getActivity(), data));
or
2) Update the contents of ArrayAdapter which is already binded to listview:
this.arrayadapter.clear();
for (Data item : data)
this.arrayadapter.add(item);
this.arrayadapter.notifyDataSetChanged();
So which method is more expensive?
The way you are doing it, the second one is definitely more expensive. ArrayAdapter calls notifyDataSetChanged() internally in clear() as well as in add(). You could change it to
this.arrayadapter.setNotifyOnChange(false);
this.arrayadapter.clear();
for (Data item : data)
this.arrayadapter.add(item);
this.arrayadapter.setNotifyOnChange(true);
this.arrayadapter.notifyDataSetChanged();
But even if you it this way, both calls contain a synchronized block which makes them slow. So even though you are creating a new ArrayAdapter in the first method, I would say it is faster.
You could further optimize it by using a custom adapter with a setItems(data) method that just replaces the internal data list.
I'd becareful with the accepted answers final conclusion. While SimonSays makes valid points about the iteration and adding...there's a lot that happens with setting a new adapter he fails to recognize. Which makes it hard to say if it's actually any better then the suggested for...each approach.
Setting a new adapter will cause the ListView to flush out all it's recycled view's. It'll also have to re-measure all the new views coming in...which leads to the getView() being called 3-4 times per item for several of the positions...if not all positions. (Varies with platform). So even though there's a sync block on adding, you'll probably see the getView method invoked far less times with possibility of using recycled views.
Basically, knowing which is better is hard and depends greatly on use case. I'd vote to stick with the for...each approach simply for better readability.
In my application I am fetching the data from a web service in XML format, and parsing it and showing the data in listview. The problem is that if the web service contains 5000 objects then it takes a lot of time to display the data.
Can it be possible to show some data in listview and fetch the data at the same time at the end of the list.
Please provide me some sample code.
If you use convertView in your ListAdapter´s getView method it should not matter how many items you have in the list since the Views are beeing reused.
If your Listadapter takes an array of som sort you could add items to the array continuosly and call
mListAdapter.notifyDataSetChanged();
every time new data is added to the list.
By Using AsyncTask you can do this easily as each object is being fetched can be shown in listview using publishProgress() method while also updating user about what percentage of data hasbeen loaded.
Update:
By the way according to your situation the tool below which is developed by commonsware https://stackoverflow.com/users/115145/commonsware will suits you best...
https://github.com/commonsguy/cwac-endless
cwac-endless: Provides the EndlessAdapter, a wrapper for an existing ListAdapter that adds "endless list" capability. When the user scrolls to the bottom of the list, if there is more data for this list to be retrieved, your code gets invoked in a background thread to fetch the new rows, which then get seamlessly attached to the bottom of the list.
Currently, I'm using AsyncTask to handle Http connection and retrieve data as JSON format.
Loading all data is trivial but it consumes too much time, so I decided to switch to load 10 items at a time using LIMIT OFFSET (mysql).
Next I set up the event onScroll for my list view to create a new AsyncTask each time user scroll. However, from what I read, AsyncTask is stored in a thread pool which is limited 5 threads at a time, so I'm not sure this is a right approach. I'm newbie to client/server app, so could I anyone give me an advice on this issue? Any related article, documentation would be greatly appreciated.
Here are few useful links for it,
Android: Implementing progressbar and "loading..." for Endless List like Android Market
Endless Listview with current Async Task
Android Endless List
http://www.androidguys.com/2009/10/21/tutorial-autogrowing-listview/
http://mylifewithandroid.blogspot.com/2010/03/progressively-loading-listviews.html
In simple steps,
As user scrolls – detect the end of the list 1)Display a progress
notification 2)Ask for update 3)Receive update (asynchronously) and
extend list
A typical approach would be e.g. to load 25 initially and then have a footer in the list that displays e.g. the current count and the total count and upon pressing loads another 25 and so on. That would be a paged sort of loading.
When you do that you have to keep the current position and notify the adapter that the list has changed.
If you are using a ListView, I believe I can safely assume that you must be using some sort of ListAdapter. Instead of starting a new AsyncTask in the onScroll event, you should maintain just one single AsyncTask to retrieve data from the server, add that data to the ListAdapter dataset and then call notifyDatasetChanged on the ListAdapter.
The ListAdapter and ListView will take care of the rest.