Skip to content
Advertisement

Switch listener in ListView giving wrong results

Here is my Array adapter. It assigns each switch button in the list with a listener that is dependant on the id given by the database (passed using devices.id). But for some reason, the switch listener is getting the correct states from the switches.

For debugging purpose, I’m just using the same on change listener regardless of the state. So whether I turn it ON or OFF, it runs the same function.

My problem is sometimes when I turn ON 1st switch, 7th switch is turned ON, n when I turn ON the 2nd switch, 8th switch is turned ON. There’s something wrong I’m doing, but I cant really figure out. The 6th, 7th and 8th switches don’t work properly.

You can see in the LCD, When I turn ON the switches in order, it must give me the output “12345678”. But its not. Instead it gives “12345112”.

Edit: Answer given by Emil Adz works. Gives me output “12345678”. But I have one problem. If I turn ON switch1, scroll down till its not visible and scroll up, the switch resets to OFF. Why is it so?

Wireless Controller Screenshot Wireless Controller Screenshot LCD Output

JavaScript

devices is an object of Devices.java

JavaScript

Advertisement

Answer

Try it like this:

JavaScript

Basically for some reason I encountered this problem several times. When you use convertView then all the list is going insane. Be aware of the fact that it derives performance but I didn’t find a proper solution for this problem. What more when the list is not that big it doesn’t change much.

UPDATE: First take a look at this guide:

Multi-clickable ListView

As with the check box state there you will see:

JavaScript

So in your case after this code:

JavaScript

you should add something like:

JavaScript

and in your onCheckedChanged persist the state changes.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement