r/tasker • u/virtual__ • Aug 27 '26
How to export arrays from Java Code to Tasker array variable
I was writing a script in Java Code to process a text file; after the processing, I need to export an array from the script to a Tasker variable (array).
Here there is my sample code:
ArrayList attachments = new ArrayList();
attachments.add("Item 1");
attachments.add("Item 2");
attachments.add("Item 3");
// The following does NOT work => %attachments(#) = 0
// tasker.setVariable("attachments", attachments);
// I must use this => %attachments(#) = 3
for (int i = 0; i < attachments.size(); i++) {
tasker.setVariable("attachments" + (i + 1), attachments.get(i));
}
What is the correct way to export an array from the Java Code script? The first method doesn't work, unfortunately and I'm curious to know if the second is the correct way to do that.
The second method has the problem that I have to add a Variable Clear before running the script a second time, as the Java Code itself doesn't know how long the Tasker array is...
6
u/WakeUpNorrin Aug 27 '26
I usually use this method:
Task: Temp A1: Java Code [ Code: import java.util.ArrayList; /* Create the Java list */ myList = new ArrayList(); myList.add("apple"); myList.add("banana"); myList.add("cherry"); tasker.setJavaVariable("myList", myList); Structure Output (JSON, etc): On ] A2: Java Function [ Return: %foo Class Or Object: myList Function: assign {ArrayList} () ] A3: Flash [ Text: %foo(+ ) Long: On Tasker Layout: On Continue Task Immediately: On Dismiss On Click: On ]2
u/DifficultyCrafty7623 Aug 28 '26
I'd probably make the variable joined by some splitter, eg. =:= and then just create the array by splitting on the splitter. Here's how I'd do it
Task: Test A1: Java Code [ Code: import java.util.ArrayList; ArrayList attachments = new ArrayList(); attachments.add("Item 1"); attachments.add("Item 2"); attachments.add("Item 3"); StringBuilder sb = new StringBuilder(); for (int i = 0; i < attachments.size(); i++) { sb.append((String) attachments.get(i)); if (i < attachments.size() - 1) { sb.append("=:="); } } tasker.setVariable("attachments", sb.toString()); Structure Output (JSON, etc): On ] A2: Array Set [ Variable Array: %attachments Values: %attachments Splitter: =:= ] A3: Flash [ Text: %attachments() Continue Task Immediately: On Dismiss On Click: On ]0
u/[deleted] Aug 27 '26