[SOLVED] Split a string into array/list


(Using OH2)
I tried to split a String type Item’s state without success.

[ERROR] [ntime.internal.engine.ExecuteRuleJob] - Error during the execution of rule 'Main': 0

I have done some logging and realised that the wrong code snippet is this one:

val buffer = RuleTap.state.toString.split(".")
tapBeHour = Integer::parseInt(buffer.get(0))
tapBeMin = Integer::parseInt(buffer.get(1))
tapKiHour = Integer::parseInt(buffer.get(2))
tapKiMin = Integer::parseInt(buffer.get(3))

Something with the get() method I think.
(the last 4 are global variables initialised with an integer value)
I have 2 imports if it matters:

import java.lang.*
import java.util.*

My Item:

String RuleTap

(I have set a value something like “”)

Any help would be appreciated?

tapBeHour = Integer::parseInt(RuleTap.state.toString.split(".").get(0))
tapBeMin = Integer::parseInt(RuleTap.state.toString.split(".").get(1))
tapKiHour = Integer::parseInt(RuleTap.state.toString.split(".").get(2))
tapKiMin = Integer::parseInt(RuleTap.state.toString.split(".").get(3))

You don’t need the import for java.lang. You get those classes without importing them.

You should not import *. Just import the classes you are already using. In the code you’ve posted, you are not actually using anything from java.util so don’t need that import either.

I don’t think the error is with the get but with what the get is getting.,

Are you certain that there are four elements in the result of the split?

if(buffer.size != 4) logWarn("test", "Buffer has too many or too few elements! " + buffer.size)

Are you certain that the results are all parse able numbers?

buffer.forEach[ num | logInfo("test", "\"" + num + "\"") ]

There should be no spaces or other stray characters between the " " in the logs.

Thanks for the help.
Wierd but the problem was the character ‘.’ , so changed the separator to ‘,’

val buffer = RuleTap.state.toString.split(",")


The string you pass to split is a regular expression. . means any character in regular expressions. So I bet it split into zero elements because each and every character matched.

To use . or any other regular expression special character you just need to escape it.

val buffer = RuleTap.state.toString.split("\.")

An older discussion but I stumbled across it. Maybe the solution will help others. The dot must be masked and this solution works for me (note 2x backslash is needed with NO spaces in-between - the Blockquote in this forum will remove the second backslash automatically).

val buffer = RuleTap.state.toString.split("\ \ .")

1 Like

@Kasi2 Thank you, this solved the problem for me!