Get value from user selection?

In my app, I'm prompting the user to select a device of type switch:
input(name: "theDevice", type: "capability.switch")

I'd then like to do something with that selection.
How do I get what the user selected for a capability?

The following does not work. Am I missing a property?
paragraph "Active Device: ${settings["theDevice"]}"

settings.theDevice is an array so try to get the first/only entry if you have multiple:false on the input
paragraph "Active Device: ${settings.theDevice[0]}"

Edit: Played around with code and my mistake when multiple:true the settings.inputName is of type DeviceWrapperList and if multiple:false then it is of type DeviceWrapper and not a list.

That should work, unless you have passed the multiple: true parameter to input() (which I think is what was really meant above? that's when it would be a List instead of a single device).

If that isn't the case, one possibility is that the value of this setting/input has not yet been saved, so reading it will return the "old" value, which could very well be nothing (e.g., if this is a new install of the app or you just never had anything selected before). Hitting "Done" will save your settings, or if you need it right away, you can use the submitOnChange: true parameter on this input to save the value right away (when the user moves selection away from this input in the UI).

Another tip: you can just use theDevice instead of settings.theDevice or settings["theDevice"], though all three should be the same. (The first saves the most typing, but I often prefer the second since it makes it clear what my object refers to and isn't "stringly typed" like the third -- not that it helps much in a language as dynamic as this one.)

1 Like

Thank you. The submitOnChange was the key.

 theDevice = "Please select"
 input(name: "theDevice", type: "capability.switch",  submitOnChange: true)                  
// Now show the user what they picked.
 paragraph "Active Device: ${settings.theDevice}"
2 Likes

Thank you. However, that seemed to cause an error "// Error: Cannot invoke method getAt() on null object".

The following works, however:

 theDevice = "Please select"
 input(name: "theDevice", type: "capability.switch",  submitOnChange: true)                  
// Now show the user what they picked.
 paragraph "Active Device: ${settings.theDevice}"

could try

if(theDevice) paragraph "Active Device: ${settings.theDevice}"
1 Like

Thanks. That's probably a better way than I ended up checking. I did:

if (settings.theDevice != null ){
   ....
}

Amounts to the same thing just a slightly different syntax.