I'm having a problem with my ListView (using CursorAdapter). When I call getListView().getLastVisiblePosition() I am receiving -1. This is a problem since my list is populated with items. Additionally, getListView().getFirstVisiblePosition() always returns 0, no matter where I am scrolled on the list. Any ideas?
It has something to do with startManagingCursor
#Override
public void changeCursor(Cursor cursor) {
super.changeCursor(cursor);
MyActivity.this.mCursor = cursor;
//startManagingCursor(MyActivity.this.mCursor);
}
If I comment out startManagingCursor, everything works fine. I've also tried adding stopManagingCursor() before changing the Cursor and still have the same problem.
This is because the moment you call getListView().getLastVisiblePosition() the listview is not rendered. You can add the call to the view's message queue like this:
listview.post(new Runnable() {
public void run() {
listview.getLastVisiblePosition();
}
});
Even I faced the same problem. The thing is that, getLastVisiblePosition() works only when you are in the first element of your listview and for the rest you will get null being returned. So what I did is that, I made a small calculation to find out the exact view position which I have mentioned below,
int LastPos=(mylist.getLastVisiblePosition()-mylist.getFirstVisiblePosition());
This returns the exact last position without a doubt.
My guess is that your getItem(int position) and getItemId(int position) methods aren't defined correctly in your adapter.
Related
I’m some kind of new working with RecyclerView and I have noticed lately on one of the tutorials that they use RecyclerView.NO_POSITION with smoothScrollToPosition().
Here's the example:
private RecyclerView mRecyclerView;
private int mPosition = RecyclerView.NO_POSITION;
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
if (mPosition == RecyclerView.NO_POSITION) mPosition = 0;
mRecyclerView.smoothScrollToPosition(mPosition);
}
But I don’t know exactly what NO_POSITION or this smoothScrollToPosition() actually do? Also I tried to search official doc, other essays or checking other guys questions here. Unfortunately, none helped me.
Can anyone explain what their purpose/why do we need to use them?
NO_POSITION is a constant whose value is -1, it basically means that when don't you find the position of the model in the underlying dataset the return value of this method will be NO_POSITION.
smoothScrollToPostion(value) tells your view to go to that particular position in the recyclerView.
NO_POSITION is an int with -1 value;
smoothScrollToPosition() will scroll the RecyclerView to the requested position.
According to the API docs:
RecyclerView.NO_POSITION is a constant value -1.
And in case of getBindingAdapterPosition() method NO_POSITION is used for when item has been removed from the adapter, RecyclerView and/or Adapter.notifyDataSetChanged() has been called after the last layout pass or the ViewHolder has already been recycled.
smoothScrollToPosition starts a smooth scroll to an adapter position. If the adapter position is RecyclerView.NO_POSITION, then it means something went wrong, and it might even throw an exception in your code, so be careful!
I have a list with 13 items (although items may be added or removed), positions 0-12. When the fragment containing the RecyclerView is first shown, only positions 0 through 7 are visible to the user (position 7 being only half visible). In my adapter I Log every time a view holder is binded/bound (idk if grammar applies here) and record its position.
Adapter
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
Log.d(TAG, "onBindViewHolder() position: " + position);
...
}
From my Log I see that positions 0-7 are bound:
I have a selectAll() method that gets each ViewHolder by adapter position. If the returned holder is NOT null I use the returned holder to update the view to show it's selected. If the returned holder IS null I call selectOnBind() a method that flags the view at that position update to show it's selected when it's binded rather than in real time since it's not currently shown:
public void selectAll() {
for (int i = 0; i < numberOfItemsInList; i++) {
MyAdapter.ViewHolder holder = (MyAdapter.ViewHolder)
mRecyclerView.findViewHolderForAdapterPosition(i);
Log.d(TAG, "holder at position " + i + " is " + holder);
if (holder != null) {
select(holder);
} else {
selectOnBind(i);
}
}
}
In this method I Log the holder along with its position:
So up to this point everything seems normal. We have positions 0-7 showing, and according to the Log these are the positions bound. When I hit selectAll() without changing the visible views (scrolling) I see that positions 0-7 are defined and 8-12 are null. So far so good.
Here's where it gets interesting. If after calling selectAll() I scroll further down the list positions 8 and 9 do not show they are selected.
When checking the Log I see that it's because they are never bound even though they were reported to be null:
Even more confusing is that this does not happen every time. If I first launch the app and test this it may work. But it seems to happen without fail afterwards. I'm guessing it has something to do with the views being recycled, but even so wouldn't they have to be bound?
EDIT (6-29-16)
After an AndroidStudio update I cannot seem to reproduce the bug. It works as I expected it to, binding the null views. If this problem should resurface, I will return to this post.
This is happening because:
The views are not added to the recyclerview (getChildAt will not work and will return null for that position)
They are cached also (onBind will not be called)
Calling recyclerView.setItemViewCacheSize(0) will fix this "problem".
Because the default value is 2 (private static final int DEFAULT_CACHE_SIZE = 2; in RecyclerView.Recycler), you'll always get 2 views that will not call onBind but that aren't added to the recycler
In your case views for positions 8 and 9 are not being recycled, they are being detached from the window and will be attached again. And for these detached view onBindViewHolder is not called, only onViewAttachedToWindow is called. If you override these function in your adapter, you can see what I am talking.
#Override
public void onViewRecycled(ViewHolder vh){
Log.wtf(TAG,"onViewRecycled "+vh);
}
#Override
public void onViewDetachedFromWindow(ViewHolder viewHolder){
Log.wtf(TAG,"onViewDetachedFromWindow "+viewHolder);
}
Now in order to solve your problem you need to keep track of the views which were supposed to recycled but get detached and then do your section process on
#Override
public void onViewAttachedToWindow(ViewHolder viewHolder){
Log.wtf(TAG,"onViewAttachedToWindow "+viewHolder);
}
The answers by Pedro Oliveira and Zartha are great for understanding the problem, but I don't see any solutions I'm happy with.
I believe you have 2 good options depending on what you're doing:
Option 1
If you want onBindViewHolder() to get called for an off-screen view regardless if it's cached/detached or not, then you can do:
RecyclerView.ViewHolder view_holder = recycler_view.findViewHolderForAdapterPosition( some_position );
if ( view_holder != null )
{
//manipulate the attached view
}
else //view is either non-existant or detached waiting to be reattached
notifyItemChanged( some_position );
The idea is that if the view is cached/detached, then notifyItemChanged() will tell the adapter that view is invalid, which will result in onBindViewHolder() getting called.
Option 2
If you only want to execute a partial change (and not everything inside onBindViewHolder()), then inside of onBindViewHolder( ViewHolder view_holder, int position ), you need to store the position in the view_holder, and execute the change you want in onViewAttachedToWindow( ViewHolder view_holder ).
I recommend option 1 for simplicity unless your onBindViewHolder() is doing something intensive like messing with Bitmaps.
When you have large number of items in the list you have passed to recyclerview adapter you will not encounter the issue of onBindViewHolder() not executing while scrolling.
But if the list has less items(I have checked on list size 5) you may encounter this issue.
Better solution is to check list size.
Please find sample code below.
private void setupAdapter(){
if (list.size() <= 10){
recycler.setItemViewCacheSize(0);
}
recycler.setAdapter(adapter);
recycler.setLayoutManager(linearLayoutManager);
}
I think playing with view is not a good idea in recyclerview. The approach I always use to follow to just introduce a flag to the model using for RecyclerView. Let assume your model is like -
class MyModel{
String name;
int age;
}
If you are tracking the view is selected or not then introduce one boolean to the model. Now it will look like -
class MyModel{
String name;
int age;
boolean isSelected;
}
Now your check box will be selected/un-selected on the basis of the new flag isSelected (in onBindViewHolder() ). On every selection on view will change the value of corresponding model selected value to true, and on unselected change it to false. In your case just run a loop to change all model's isSelected value to true and then call notifyDataSetChanged().
For Example, let assume your list is
ArrayList<MyModel> recyclerList;
private void selectAll(){
for(MyModel myModel:recyclerList)
myModel.isSelected = true;
notifyDataSetChanged();
}
My suggestion, while using recyclerView or ListView to less try to play with views.
So in your case -
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
holder.clickableView.setTag(position);
holder.selectableView.setTag(position);
holder.checkedView.setChecked(recyclerList.get(position).isSelected);
Log.d(TAG, "onBindViewHolder() position: " + position);
...
}
#Override
public void onClick(View view){
int position = (int)view.getTag();
recyclerList.get(position).isSelected = !recyclerList.get(position).isSelected;
}
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int position = (int)buttonView.getTag();
recyclerList.get(position).isSelected = isChecked;
}
Hope it will help you, Please let me know if you need any further explanation :)
So I think you question is answered below by #Pedro Oliveira. The main sense of RecycleView, that he using special algorithms for caching ViewHolder in any time. So next onBindViewHolder(...) may not work, for ex. if view is static, or something else.
And about your question you think to use RecycleView for dynamic changed Views. DON'T DO IT! Because RecycleView invalidates views and has caching system, so you will have a lot of problems.
Use LinkedListView for this task!
I'm working on a note taking app. I add a note, and it get's added to the bottom of the list. As the last assertion in the espresso test, I want to make sure that the ListView displays a listItem that has just been added. This would mean grabbing the last item in the listView. I guess you might be able to do it in other ways? (e.g. get the size of adapted data, and go to THAT position? maybe?), but the last position of the list seems easy, but I haven't been able to do it. Any ideas?
I've tried this solution, but Espresso seems to hang. http://www.gilvegliach.it/?id=1
1. Find the number of elements in listView's adapter and save it in some variable. We assume the adapter has been fully loaded till now.:
final int[] numberOfAdapterItems = new int[1];
onView(withId(R.id.some_list_view)).check(matches(new TypeSafeMatcher<View>() {
#Override
public boolean matchesSafely(View view) {
ListView listView = (ListView) view;
//here we assume the adapter has been fully loaded already
numberOfAdapterItems[0] = listView.getAdapter().getCount();
return true;
}
#Override
public void describeTo(Description description) {
}
}));
2. Then, knowing the total number of elements in listView's adapter you can scroll to the last element:
onData(anything()).inAdapterView(withId(R.id.some_list_view)).getPosition(numberOfAdapterItems[0] - 1).perform(scrollTo())
I have a recycler view and I want to perform click on one of its items.
Here is my code:
mRecyclerView.findViewHolderForAdapterPosition(2).itemView.performClick();
It works fine when the item is visible, but when it is not visible i'm getting a null pointer exception
also i tried scroll to position before perform click but i got same result
Any idea on how to solve this issue?
I have solved my problem with this code
mRecyclerView.getLayoutManager().scrollToPosition(17);
search_list.postDelayed(new Runnable() {
#Override
public void run() {
mRecyclerView.findViewHolderForAdapterPosition(17).itemView.performClick();
}
}, 50);
There is a slight delay for the viewholder to be created. Thus if the item is clicked before viewholder is created an NPE would occur
Unfortunately for you, this is working as intended. When a child View is scrolled out of the boundaries of a RecyclerView, the child View is often reused to display another item for another position in the list, hence you will get a null View for the position that is no longer displayed.
What you can do is implement a getItem() on the RecyclerView.Adapter to retrieve the item for that position. Not sure if that satisfies your requirements though.
It is recommended to use a listener to wait for the drawing to complete,
Then perform the operation you want.
recyclerView.getViewTreeObserver().addOnGlobalLayoutListener(
new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
// At this point the layout is complete
recyclerView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
});
I'm working on an application that primarily consists of a list view. It's backed up by my own custom array adapter whose size changes every 5 seconds. If I scroll through the list view as the array adapter changes from a greater size to a lesser size, I get an out of bounds exception. It makes sense to me why this occurs (since I'm scrolling at a position beyond the new array size), but I was wondering if there was a good way to debug it. I can't seem to come to a clear conclusion, and I was wondering if I could get some help.
I update the adapter using the following asyncTask...
public class myTask extends AsyncTask<Void, Void, Void>{
#Override
protected Void doInBackground(Void... params) {
while(isRunning){
myData.clear();
getData();
publishProgress();
SystemClock.sleep(5000);
}
return null;
}
protected void onProgressUpdate(Void...progress){
listAdapter.notifyDataSetChanged();
}
}
myData is the ArrayList that supports listAdapter and getData() is the function that populates myData with the relevant info that will eventually be displayed in my list view.
Is there a good way to tackle this problem?
Regards
Are you using a custom adapter?
Perhaps in your getViewTypeCount() and getItemViewType(int position) it is going out of bounds there. The view type count should be from (0, n] but the item view type should be [0, n).
E.g. view type count should be 2
But the view types should be 0 and 1, not 1 and 2.
try to override the getCount() function of the adapter class:
#Override
public int getCount() {
return [list that contains data].size();
}
Have you tried resetting the user to either the top of the list or as close as possible when the list changed sizes?
Sorry, maybe is not the answer for the question, but having that infinite loop seems for me that is not the correct way, even if it´s an async task.
I would try to use the an AlarmManager or a Timer.
With that said, seems what you have is a race condition, take into account that it´s not immediately when you ask for data, or a specific position and rebuild the views.
Cheers,
Francisco.