Problem with ArrayList variable adding things twice

2

I have a simple report with the following SQL

SELECT id FROM TABLE

Results: 1, 2, 3, 4

I have a variable "AList" of type ArrayList (Value Class Name), Calculation is System, Initial Value Expression is "new ArrayList()", Increment Type is None and Reset Type is Report. The Expression for this is $V{AList}.add($F{id})

All I want this ArrayList to do is keep adding new ids with each row. So when I have the $F{id} and $V{AList} in the detail band, I expect to see something like this

id AList
1 [1]
2 [1,2]
3 [1,2,3]
4 [1,2,3,4]

But what I see is this

id AList
1 [1]
2 [1,2]
3 [1,2,3,3]
4 [1,2,3,3,4,4]
Why, after the second row, does the value repeat itself twice?
max_max_mir's picture
Joined: Jul 21 2010 - 9:03am
Last seen: 3 months 1 day ago

1 Answer:

1

It has been almost exactly one year  since you asked this question, but I think I've found a solution.

In your expression editor, use the following ternary expression for $V{Variable_1}

$V{Variable_1}.size() < $V{REPORT_COUNT} ? $V{Variable_1}.add($F{myField}) : null

What is happening in that code snippet is as follows:

$V{Variable_1} is a variable of type java.util.ArrayList, with Initial Value Expression of new ArrayList(). Using the .size() function of the ArrayList class, the ternary expression checks if your array has as many elements as there are rows in the resultset, defined by $V{REPORT_COUNT}. If the condition holds, then the next value is added to the array using .add(), if not it returns null. The calculation function is set to System, Reset Type is Report , and Increment Type is None.

The elements of the newly created array can be accessed via the .get() method, i.e. $V{Variable_1}.get( n ), where n is the zero-based index of the element you want to access. (You should note that you don't necessarily have to use a field as your value; you can use integers, strings, etc.)

Now, I am at a loss for a reason why this unusual behavior of adding entries multiple times was occurring, but I do know that calling the .add() function of ArrayList returns a Boolean value of true when the value is added successfully to the list, and false otherwise. So perhaps a combination of your expression returning a Boolean and the list not having $V{REPORT_COUNT} as an upper bound somehow caused this erroneous result. Either way, I hope this answer helps you or anybody else stumbling across this page, especially since it solves a difficulty that I had long been having with JasperReports.

Thanks,

Jorge Longoria,

Data Analyst and Report Developer.

jlongoria's picture
Joined: Aug 21 2015 - 8:03am
Last seen: 7 months 1 week ago
Feedback