onCheckedChanged called automatically - android

I have a switch in a recyclerview and data is displayed in the recyclerview after retrieving data from DB. When the recyclerview is opened I read DB and if a field in DB is "Y" I enable the switch or else I disable the switch.
Now the problem is along with it the onCheckedchanged listener is also called, I want the onCheckedChanged to be called only when user sets the switch manually.
On opening the recyclerview below is executed:
holder.enabledisable.setChecked(messengerRecord.get_is_valid().equalsIgnoreCase("Y"));
ViewHolder class:
public class viewHolder extends RecyclerView.ViewHolder implements CompoundButton.OnCheckedChangeListener{
public SwitchCompat enabledisable;
public viewHolder(View v) {
enabledisable = (SwitchCompat) v.findViewById(R.id.enabledisable);
enabledisable.setOnCheckedChangeListener(this);
...................................
...................................
OncheckedChanged method which is called when the recyclerView is just opened:
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Log.v("ranjith","called oncheckedchanged");
MessengerRecord rec;
rec = dbHelper.getRecord(descview.getText().toString());
switch (buttonView.getId()) {
case R.id.enabledisable:
if (isChecked) {
rec.set_is_valid("Y");
dbHelper.updateRecord(rec);
}
}
In Layout file:
<android.support.v7.widget.SwitchCompat
android:layout_marginRight="16dp"
android:layout_marginEnd="16dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:focusable="false"
android:id="#+id/enabledisable"
android:layout_alignRight="#+id/textview_to"
android:layout_alignEnd="#+id/textview_to"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"/>

It's weird all of us have this problem but not official Google answer to this simple problem.
The MOST simple it's to check:
buttonView.isPressed()
If true, means the user clicked the view.
No global variables are needed.

Try this
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (buttonView.isPressed()) {
... //returns true, if user clicks the switch button
}}

I've ended up using this subclass of SwitchCompat to avoid this issue. This way I don't need boilerplate code where I'm using this class.
Whenever you need to change the checked without firing the listener, use setCheckedSilent instead of setChecked:
import android.content.Context;
import android.os.Parcelable;
import android.support.v7.widget.SwitchCompat;
import android.util.AttributeSet;
/**
* Created by emanuel on 30/5/16.
*/
public class Switch extends SwitchCompat {
private OnCheckedChangeListener listener;
public Switch(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
public void setOnCheckedChangeListener(OnCheckedChangeListener listener) {
this.listener = listener;
super.setOnCheckedChangeListener(listener);
}
#Override
public void onRestoreInstanceState(Parcelable state) {
super.setOnCheckedChangeListener(null);
super.onRestoreInstanceState(state);
super.setOnCheckedChangeListener(listener);
}
public void setCheckedSilent(boolean checked) {
super.setOnCheckedChangeListener(null);
super.setChecked(checked);
super.setOnCheckedChangeListener(listener);
}
}
onRestoreInstanceState was triggering the listening also, when set in the onViewCreated method and you are going back to a previous fragment.
Hope it works for you!

Since RecyclerView is recycling views, a previously attached OnCheckedChangeListener can be triggered when setting checked value for the Switch of the new item.
When binding new data to an item:
switch.setOnCheckedChangeListener(null) // remove any existing listener from recycled view
switch.isChecked = [true/false] // will no longer trigger any callback to listener
switch.setOnCheckedChangeListener { btnView, isChecked ->
// do exiting stuff
}

This works for me:
boolean selected = preferences.isChecked();
yourCheckBox.setOnCheckedChangeListener(new
CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (buttonView.isPressed()) {
preferences.setChecked(isChecked);
} else {
yourCheckBox.setChecked(selected);
}
}
});

Kotlin Developers:
checkboxXYZ.setOnCheckedChangeListener { btnView, isChecked ->
if (btnView.isPressed) {
}
}

use a global boolean variable and when read a data from DB set it "true" and after check(if) in onCheckChange set it "false" again. in first of onCheckChange method check if this variable is false execute codes else return(default value of this variable must be false ) ;
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(!isSourceDB){
Log.v("ranjith","called oncheckedchanged");
MessengerRecord rec;
rec = dbHelper.getRecord(descview.getText().toString());
switch (buttonView.getId()) {
case R.id.enabledisable:
if (isChecked) {
rec.set_is_valid("Y");
dbHelper.updateRecord(rec);
}
}//end if
isSourceDB = false; }// end oncheckedchange

If you are changing state in adapter then
holder.rawManageDriverLayoutBinding.rawManageDriverSwitch.setOnCheckedChangeListener(null);
before setOnCheckedChangeListener.

I faced the same problem inside ViewPager screen for fragments. When we switch between fragments, onCheckedChanged Listener is called again and again.
If anyone still looking for this problem, please try it.
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (buttonView.isInTouchMode()) {
... //Your code will come here.
}
}

Only solution is to use the method isPressed() in the listener

Related

onCheckedChanged is called whenever viewHolder is recycled

I am writing a todo list application and, in particular, I want the value of the checkBox to be stored in the database every time it is changed.
I set this feature by adding setOnCheckedChangeListener in onBindViewHolder
#Override
public void onBindViewHolder(#NonNull TodosAdapter.TodoViewHolder holder, int position)
{
Todo todo = todoList.get(position);
holder.todoTV.setText(todo.getText());
holder.todoTV.setChecked(todo.isDone()); //isDone is a boolean that indicates whether the checkBox has been selected or not
holder.todoTV.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
dbManager.allDao().setTodoIsDone(todo.getTodoId(), isChecked); //sets the isDone attribute of the database
todo.setDone(isChecked);
}
});
}
The problem is that onCheckedChanged is also called when the viewHolder is recycled and in these cases it returns isChecked = false;
I found the solution here:Android setOnCheckedChangeListener calls again when old view comes back.
Just use the buttonView.isShown() method:
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(buttonView.isShown()) {
dbManager.allDao().setTodoIsDone(todo.getTodoId(), isChecked); //sets the isDone attribute of the database
todo.setDone(isChecked);
}
}

Android uncheck select all checkbox on Recycler item uncheck

I have recycler view items with Checkbox component and implemented common "Check All" button. When I "uncheck" the button in list item, I want to "uncheck" common "Select All" Checkbox outside the recycler view.
I having issue in accessing the common "Select All" Checkbox in Adapter.
In my adapter class added below code,
private class UserViewHolder extends RecyclerView.ViewHolder {
public TextView title;
public CheckBox commonCheckbox, itemCheckbox;
public UserViewHolder(View view) {
super(view);
itemCheckbox=view.findViewById(R.id.itemcheckbox);
title=view.findViewById(R.id.title);
commonCheckbox = view.findViewById(R.id.commoncheckbox);
}
}
In onBindViewHolder, I implemented the following checked listener,
userViewHolder.itemCheckbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked){
userViewHolder.commonCheckbox.setChecked(false);
}
}
});
But, commonCheckbox showing null pointer exception. Thanks in advance.
The view holder would be holding the layout of the recycled views items yes, so the Id wouldn’t not show as “incorrect” as you have an ID with that name, but the view that it is looking for the ID In is not the same view that the common check box is in, that would be why it is returning null.
I believe the easiest solution would be to pass in a Listener to the viewholder and call a method from the listener to uncheck the common check box when your onCheckChanged listener is called
Finally, I achieved using the interface approach.
Adapter class code below,
//Interface class
public interface OnDataChangeListener{
public void onDataChanged(int size);
}
//Listener discussion
OnDataChangeListener mOnDataChangeListener;
public void setOnDataChangeListener(OnDataChangeListener onDataChangeListener){
mOnDataChangeListener = onDataChangeListener;
}
//Set listener
userViewHolder.itemCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked){
mOnDataChangeListener.onDataChanged(homeworkdate.size());
}
}
});
In activity class code below,
classAdapter.setOnDataChangeListener(new classAdapter.OnDataChangeListener() {
#Override
public void onDataChanged(int size) {
commonCheckbox.setChecked(false);
}
});

Android RecyclerView : notifyDataSetChanged() IllegalStateException

I'm trying to update the items of a recycleview using notifyDataSetChanged().
This is my onBindViewHolder() method in the recycleview adapter.
#Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {
//checkbox view listener
viewHolder.getCheckbox().setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//update list items
notifyDataSetChanged();
}
});
}
What I want to do is update the list items, after I check a checkbox. I get an illegal exception though: "Cannot call this method while RecyclerView is computing a layout or scrolling"
java.lang.IllegalStateException: Cannot call this method while RecyclerView is computing a layout or scrolling
at android.support.v7.widget.RecyclerView.assertNotInLayoutOrScroll(RecyclerView.java:1462)
at android.support.v7.widget.RecyclerView$RecyclerViewDataObserver.onChanged(RecyclerView.java:2982)
at android.support.v7.widget.RecyclerView$AdapterDataObservable.notifyChanged(RecyclerView.java:7493)
at android.support.v7.widget.RecyclerView$Adapter.notifyDataSetChanged(RecyclerView.java:4338)
at com.app.myapp.screens.RecycleAdapter.onRowSelect(RecycleAdapter.java:111)
I also used notifyItemChanged(), same exception. Any secret way to update to notify the adapter that something changed?
You should move method 'setOnCheckedChangeListener()' to ViewHolder which is inner class on your adapter.
onBindViewHolder() is not a method that initialize ViewHolder.
This method is step of refresh each recycler item.
When you call notifyDataSetChanged(), onBindViewHolder() will be called as the number of each item times.
So If you notifyDataSetChanged() put into onCheckChanged() and initialize checkBox in onBindViewHolder(), you will get IllegalStateException because of circular method call.
click checkbox -> onCheckedChanged() -> notifyDataSetChanged() -> onBindViewHolder() -> set checkbox -> onChecked...
Simply, you can fix this by put one flag into Adapter.
try this,
private boolean onBind;
public ViewHolder(View itemView) {
super(itemView);
mCheckBox = (CheckBox) itemView.findViewById(R.id.checkboxId);
mCheckBox.setOnCheckChangeListener(this);
}
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(!onBind) {
// your process when checkBox changed
// ...
notifyDataSetChanged();
}
}
...
#Override
public void onBindViewHolder(YourAdapter.ViewHolder viewHolder, int position) {
// process other views
// ...
onBind = true;
viewHolder.mCheckBox.setChecked(trueOrFalse);
onBind = false;
}
You can just reset the previous listener before you make changes and you won't get this exception.
private CompoundButton.OnCheckedChangeListener checkedListener = new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//Do your stuff
});;
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
holder.checkbox.setOnCheckedChangeListener(null);
holder.checkbox.setChecked(condition);
holder.checkbox.setOnCheckedChangeListener(checkedListener);
}
Using a Handler for adding items and calling notify...() from this Handler fixed the issue for me.
I don't know well, but I also had same problem. I solved this by using onClickListner on checkbox
viewHolder.mCheckBox.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (model.isCheckboxBoolean()) {
model.setCheckboxBoolean(false);
viewHolder.mCheckBox.setChecked(false);
} else {
model.setCheckboxBoolean(true);
viewHolder.mCheckBox.setChecked(true);
}
notifyDataSetChanged();
}
});
Try this, this may help!
protected void postAndNotifyAdapter(final Handler handler, final RecyclerView recyclerView, final RecyclerView.Adapter adapter) {
handler.post(new Runnable() {
#Override
public void run() {
if (!recyclerView.isComputingLayout()) {
adapter.notifyDataSetChanged();
} else {
postAndNotifyAdapter(handler, recyclerView, adapter);
}
}
});
}
Found a simple solution -
public class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
private RecyclerView mRecyclerView;
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
mRecyclerView = recyclerView;
}
private CompoundButton.OnCheckedChangeListener checkedChangeListener
= (compoundButton, b) -> {
final int position = (int) compoundButton.getTag();
// This class is used to make changes to child view
final Event event = mDataset.get(position);
// Update state of checkbox or some other computation which you require
event.state = b;
// we create a runnable and then notify item changed at position, this fix crash
mRecyclerView.post(new Runnable() {
#Override public void run() {
notifyItemChanged(position));
}
});
}
}
Here we create a runnable to notifyItemChanged for a position when recyclerview is ready to handle it.
When you have the Message Error:
Cannot call this method while RecyclerView is computing a layout or scrolling
Simple, Just do what cause the Exception in:
RecyclerView.post(new Runnable() {
#Override
public void run() {
/**
** Put Your Code here, exemple:
**/
notifyItemChanged(position);
}
});
At first I thought Moonsoo's answer (the accepted answer) wouldn't work for me because I cannot initialize my setOnCheckedChangeListener() in the ViewHolder constructor because I need to bind it each time so it gets an updated position variable. But it took me a long time to realize what he was saying.
Here is an example of the "circular method call" he is talking about:
public void onBindViewHolder(final ViewHolder holder, final int position) {
SwitchCompat mySwitch = (SwitchCompat) view.findViewById(R.id.switch);
mySwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
data.delete(position);
notifyItemRemoved(position);
//This will call onBindViewHolder, but we can't do that when we are already in onBindViewHolder!
notifyItemRangeChanged(position, data.size());
}
}
});
//Set the switch to how it previously was.
mySwitch.setChecked(savedSwitchState); //If the saved state was "true", then this will trigger the infinite loop.
}
The only problem with this, is that when we need to initialize the switch to be on or off (from past saved state, for example), it is calling the listener which might call nofityItemRangeChanged which calls onBindViewHolder again. You cannot call onBindViewHolder when you are already in onBindViewHolder], because you cannot notifyItemRangeChanged if you are already in the middle of notifying that the item range has changed. But I only needed to update the UI to show it on or off, not wanting to actually trigger anything.
Here is the solution I learned from JoniDS's answer that will prevent the infinite loop. As long as we set the listener to "null" before we set Checked, then it will update the UI without triggering the listener, avoiding the infinite loop. Then we can set the listener after.
JoniDS's code:
holder.checkbox.setOnCheckedChangeListener(null);
holder.checkbox.setChecked(condition);
holder.checkbox.setOnCheckedChangeListener(checkedListener);
Full solution to my example:
public void onBindViewHolder(final ViewHolder holder, final int position) {
SwitchCompat mySwitch = (SwitchCompat) view.findViewById(R.id.switch);
//Set it to null to erase an existing listener from a recycled view.
mySwitch.setOnCheckedChangeListener(null);
//Set the switch to how it previously was without triggering the listener.
mySwitch.setChecked(savedSwitchState); //If the saved state was "true", then this will trigger the infinite loop.
//Set the listener now.
mySwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
data.delete(position);
notifyItemRemoved(position);
//This will call onBindViewHolder, but we can't do that when we are already in onBindViewHolder!
notifyItemRangeChanged(position, data.size());
}
}
});
}
your CheckBox item is in changing drawable when you call notifyDataSetChanged(); so this exception would be occurred.
Try call notifyDataSetChanged(); in post of your view. For Example:
buttonView.post(new Runnable() {
#Override
public void run() {
notifyDataSetChanged();
}
});
Why not checking the RecyclerView.isComputingLayout() state as follows?
public class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
private RecyclerView mRecyclerView;
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
mRecyclerView = recyclerView;
}
#Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {
viewHolder.getCheckbox().setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (mRecyclerView != null && !mRecyclerView.isComputingLayout()) {
notifyDataSetChanged();
}
}
});
}
}
While item is being bound by the layout manager, it is very likely that you are setting the checked state of your checkbox, which is triggering the callback.
Of course this is a guess because you did not publish the full stack trace.
You cannot change adapter contents while RV is recalculating the layout. You can avoid it by not calling notifyDataSetChanged if item's checked state is equal to the value sent in the callback (which will be the case if calling checkbox.setChecked is triggering the callback).
Use onClickListner on checkbox instead of OnCheckedChangeListener, It will solve the problem
viewHolder.myCheckBox.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (viewHolder.myCheckBox.isChecked()) {
// Do something when checkbox is checked
} else {
// Do something when checkbox is unchecked
}
notifyDataSetChanged();
}
});
I ran into this exact issue! After Moonsoo's answer didn't really float my boat, I messed around a bit and found a solution that worked for me.
First, here's some of my code:
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
final Event event = mDataset.get(position);
//
// .......
//
holder.mSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
event.setActive(isChecked);
try {
notifyItemChanged(position);
} catch (Exception e) {
Log.e("onCheckChanged", e.getMessage());
}
}
});
You'll notice I'm specifically notifying the adapter for the position I'm changing, instead of the entire dataset like you're doing. That being said, although I can't guarantee this will work for you, I resolved the problem by wrapping my notifyItemChanged() call in a try/catch block. This simply caught the exception, but still allowed my adapter to register the state change and update the display!
Hope this helps someone!
EDIT: I'll admit, this probably is not the proper/mature way of handle the issue, but since it doesn't appear to be causing any problems by leaving the exception unhandled, I thought I'd share in case it was good enough for someone else.
Before notifyDataSetChanged() just check that with this method: recyclerView.IsComputingLayout()
Simple use Post:
new Handler().post(new Runnable() {
#Override
public void run() {
mAdapter.notifyItemChanged(mAdapter.getItemCount() - 1);
}
}
});
simply use isPressed() method of CompoundButton in onCheckedChanged(CompoundButton compoundButton, boolean isChecked)
e.g
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
... //your functionality
if(compoundButton.isPressed()){
notifyDataSetChanged();
}
} });
mostly it happen beacause notifydatasetchanged calling onCheckedchanged event of checkbox and in that event again there is notifydatasetchanged.
to solve it you can just check that checkbox is checked by programatically or user pressed it. there is method isPressed for it.
so wrap whole listner code inside isPressed method. and its done.
holder.mBinding.cbAnnual.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if(compoundButton.isPressed()) {
//your code
notifyDataSetChanged();
}
});
I suffered with this problem for hour and this is how you can fix it.
But before you began there are some conditions to this solution.
MODEL CLASS
public class SelectUserModel {
private String userName;
private String UserId;
private Boolean isSelected;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserId() {
return UserId;
}
public void setUserId(String userId) {
UserId = userId;
}
public Boolean getSelected() {
return isSelected;
}
public void setSelected(Boolean selected) {
isSelected = selected;
}
}
CHECKBOX in ADAPTER CLASS
CheckBox cb;
ADAPTER CLASS CONSTRUCTOR & LIST OF MODEL
private List<SelectUserModel> userList;
public StudentListAdapter(List<SelectUserModel> userList) {
this.userList = userList;
for (int i = 0; i < this.userList.size(); i++) {
this.userList.get(i).setSelected(false);
}
}
ONBINDVIEW [Please use onclick in place of onCheckChange]
public void onBindViewHolder(#NonNull final StudentListAdapter.ViewHolder holder, int position) {
holder.cb.setChecked(user.getSelected());
holder.cb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int pos = (int) view.getTag();
Log.d(TAG, "onClick: " + pos);
for (int i = 0; i < userList.size(); i++) {
if (i == pos) {
userList.get(i).setSelected(true);
// an interface to listen to callbacks
clickListener.onStudentItemClicked(userList.get(i));
} else {
userList.get(i).setSelected(false);
}
}
notifyDataSetChanged();
}
});
}
This is happening because you're probably setting the 'listener' before you configure the value for that row, which makes the listener to get triggered when you 'configure the value' for the checkbox.
What you need to do is:
#Override
public void onBindViewHolder(YourAdapter.ViewHolder viewHolder, int position) {
viewHolder.mCheckBox.setOnCheckedChangeListener(null);
viewHolder.mCheckBox.setChecked(trueOrFalse);
viewHolder.setOnCheckedChangeListener(yourCheckedChangeListener);
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
holder.textStudentName.setText(getStudentList.get(position).getName());
holder.rbSelect.setChecked(getStudentList.get(position).isSelected());
holder.rbSelect.setTag(position); // This line is important.
holder.rbSelect.setOnClickListener(onStateChangedListener(holder.rbSelect, position));
}
#Override
public int getItemCount() {
return getStudentList.size();
}
private View.OnClickListener onStateChangedListener(final RadioButton checkBox, final int position) {
return new View.OnClickListener() {
#Override
public void onClick(View v) {
if (checkBox.isChecked()) {
for (int i = 0; i < getStudentList.size(); i++) {
getStudentList.get(i).setSelected(false);
}
getStudentList.get(position).setSelected(checkBox.isChecked());
notifyDataSetChanged();
} else {
}
}
};
}
I had the same problem using the Checkbox and the RadioButton. Replacing notifyDataSetChanged() with notifyItemChanged(position) worked. I added a Boolean field isChecked to the data model. Then I updated the Boolean value and in onCheckedChangedListener, I called notifyItemChanged(adapterPosition). This might not be the best way, but worked for me. The boolean value is used for checking whether the item is checked.
override fun bindItemViewHolder(viewHolder: RecyclerView.ViewHolder, position: Int) {
var item: ThingChannels = items[position]
rowActionBinding.xCbChannel.text = item.channelType?.primaryType
rowActionBinding.xTvRoomName.text = item.thingDetail?.room?.name
rowActionBinding.xCbChannel.isChecked = item.isSelected
rowActionBinding.xCbChannel.tag = position
rowActionBinding.xCbChannel.setOnClickListener {
setSelected(it.tag as Int)
if (onItemClickListener != null) {
onItemClickListener!!.onItemClick(position, null)
}
}
}
None of the past answers solve the problem!
The problem with past answers
All of them either avoid the problem by swallowing the change (i.e. not notifying the adapter of the change) if the user is scrolling, which just means that if the user was scrolling when the change was ready, they will never see the change. Or, they suggest using recylerView.post() which just postpones the problem.
The answer
Option #1
Stop the scrolling and then notify the adapter:
recyclerView.stopScroll()
val copy = workingList.toList()
//prevent IndexOutOfBoundsException: Inconsistency detected... (https://stackoverflow.com/questions/41054959/java-lang-indexoutofboundsexception-inconsistency-detected-invalid-view-holder)
workingList.clear()
recyclerViewAdapter?.notifyDataSetChanged()
//set display to correct data
workingList.addAll(copy)
recyclerViewAdapter?.notifyItemRangeInserted(0, workingList.size)
Option #2
For a better user experience, you can let them continue scrolling and listen for when they stop scrolling in order to update the UI, but this method should only be used if you do not plan on writing a function that will accept different RecyclerView instances, because if you add multiple listeners to the same RecyclerView which are all trying to be updated, the app will crash:
if(recyclerView.scrollState != RecyclerView.SCROLL_STATE_IDLE) //notify RecyclerView
else recyclerView.addOnScrollListener(object: RecyclerView.OnScrollListener() {
override fun onScrollStateChanged(
recyclerView: RecyclerView,
newState: Int
) {
if(newState == RecyclerView.SCROLL_STATE_IDLE) {
//notify RecyclerView...
val copy = workingList.toList()
//prevent IndexOutOfBoundsException: Inconsistency detected... (https://stackoverflow.com/questions/41054959/java-lang-indexoutofboundsexception-inconsistency-detected-invalid-view-holder)
workingList.clear()
recyclerViewAdapter?.notifyDataSetChanged()
//set to display correct data
workingList.addAll(copy)
recyclerViewAdapter?.notifyItemRangeInserted(0, workingList.size)
}
})
Note: you can use option #2 even if you are writing a util function by keeping a list of previously registered instances and not add a listener if it has already been registered, but it is not "clean coding" to rely on state in a library/util class.
For me problem occurred when I exited from EditText by Done, Back, or outside input touch. This causes to update model with input text, then refresh recycler view via live data observing.
The Problem was that cursor/focus remain in EditText.
When I have deleted focus by using:
editText.clearFocus()
Notify data changed method of recycler view did stop throwing this error.
I think this is one of the possible reason/solutions to this problem. It is possible that this exception can be fixed in another way as it can be caused by totally different reason.

Access the button in parent view from a switch android

I have an issue accessing the view from the parent of a compoundbutton.
((Switch) convertView.findViewById(R.id.push_switch)).setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (rowItem.getPush().equals("N")) {
rowItem.setFollow(true);
rowItem.setPush("Y");
setFollowTickGreen(rowItem, convertView);
}
else if (rowItem.getPush().equals("Y")) {
rowItem.setPush("N");
}
}
});
This code shows my switch button but I need to get access to convertView to change something else when this button is pressed.
This is being done inside an adapter, so the switch code is in the getView function but the setFollowTickGreen is outside of that function.
I can't set convertView as final as it changes throughout the getView function.
I understand that the compoundButton is the switch but the switch is at the same level that I want to access a Button.
Is there a general way of doing this?
This would be similar for other situations, as well as compoundbuttons I assume.
Thanks.
Does this help..
final View tmpConvertView=convertView;
((Switch) convertView.findViewById(R.id.push_switch)).setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (rowItem.getPush().equals("N")) {
rowItem.setFollow(true);
rowItem.setPush("Y");
setFollowTickGreen(rowItem, tmpConvertView);
}
else if (rowItem.getPush().equals("Y")) {
rowItem.setPush("N");
}
}
});

How to implement a CheckBox's onTouchEvent

How do you implement this onTouchEvent? It should fire when the user checks or unchecks the CheckBox widget.
CheckBox checkBox = new CheckBox(activity);
checkBox.setText("Don't present me information again.");
checkBox.onTouchEvent(.....);
The CheckBox widget (and any other widget that extends CompoundButton) has a method setOnCheckedChangeListener, which is the bit you're lacking (you probably don't want to use onTouchEvent in this case).
This example should replace the final line of code in your snippet:
checkBox.setOnCheckedChangeListener( new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if ( isChecked ) {
// do some stuff
}
}
});
what you need in your case is this
checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
if ( isChecked )
{
Toast.makeText(yourActivity.this,"CheckBox is Checked ..",3000).show();
}
else{
Toast.makeText(yourActivity.this,"CheckBox is Unchecked ..",3000).show();
}
}
});

Categories

Resources