Assign text to JLabels from ArrayList - java

I'm not actually sure how to ask this question because its very confusing. I have a java app that has a MVC structure, which gets data from a database. I retrieve String ArrayList of data from a JDBC query. It contains information about Competitors in a race (eg: Name, Race_no, Start_Time, Swim_Time, Bike_Time, Finish_Time etc). The list size will vary week to week depending on the number of the competitors who raced that week. I have no problem getting the data from the database, but when I pass the information to the controller to pass to the view, I am having trouble assigning the data to a JLabel. So far the data is sent as one large array so I need to somehow split the array up in blocks of 12 (which is how many JLabels are required to be set for each competitor). I then set each of those 12 JLabels into its own JPanel ArrayList - then dynmically add to one JPanel for printing. My question is, how do I split the ArrayList to get the first 12, then the second lot of 12, etc.. I have tried doing a nested loop and set the size to 12, but of course that only gets the first 12 everytime. Maybe I need to store the data from the JDBC result set as something else.. I really need some guidance on this as have been stuck for days.
nb: I had this working as one large method in the data handler class, where I would use the while(rs.next()) to do all the work, but because of the MVC structure, I need to break the code up: This is the desired outcome:
EDIT:
I have implement this code which give me the desired output, but now having trouble assigning the JLabel variables with the data in the [j] loop:
<pre>
public void getRaceLabels()
{
ArrayList<String[]> raceLabels = dh.getRaceTimeLabels();
//System.out.println(raceLabels);
for (int i = 0; i < raceLabels.size(); i++)
{
String[] element = (String[]) raceLabels.get(i);
//System.out.println(element);
for (int j = 0; j < element.length; j++)
{
System.out.print(element[j]+" ,");
}
System.out.println("break");
}
</pre>

Create yourself a POJO which represents the basic information you need for a single record.
When loading the data from the database, load this data into the POJO.
Now, for each panel, you just need to pass it a single object, meaning you can now get away with using a simple iterator instead

Related

How to create a dynamic array with 2 different data types

I need to create a dynamic array with data from a Excel spreadsheet using Apache-POI and Selenium.
My goal is to be able to create a dynamic array with 2 data types(int and String's)to be called to be inputted into a text field using Selenium WebDriver. I have already gotten the information to be hardcoded, however I'd like to be able to not rely on the workbook to increase the speed of my program.
General structure:
for(int i = 0; i < sheet1.getLastRowNum(); i++) {
string cell[i] = formatter.formatCellValue(sheet1.getRow(i).getCell(0)
}
The errors I get are, "Syntax Error on token "i", delete this token" and also "Type mismatch: Cannot convert from "String" to "String[]"
Would it work if you stored everything in the array as a string? You could just use String.valueOf() to convert the cell value to a string, and if you need to get it back later on as an int you could use Integer.parseInt().
You can make an array of Objects, but that could cause more trouble than it's worth. You could be adding an object into it which has a type you never accounted for, which could cause you problems later on down the line.

List with Delimited Values Performance

I'm pulling a List (ArrayList) of data that represents a single row from a database view. While each column normally has a single value, some columns have a delimited String value, such as this:
CompanyID CompanyName ContactIDs Contacts
49 Test Company 5;9 Alice;Bob
Currently, I'm pulling a sub-list of the first values, and then parsing the rest with String.split(), but I'm worried about performance, especially when I'm loading several hundred of these objects at a time. Here is my method:
public void loadFromData(List data) {
getCompany().load(data.subList(0, 2));
//Pulls 49 and Test Company and loads it into a Company object
getContacts().clear();
//getContacts() retrieves an ArrayList of Contact objects
String[] contactIds = ((String)data.get(2)).split(";");
String[] contactNames = ((String)data.get(3)).split(";");
List data = new ArrayList();
for (int i = 0; i < companyCategoryIds.length; i++) {
data.clear();
data.add(contactIds[i]);
data.add(getCompany().getCompanyId());
data.add(contactNames [i]);
getContacts().add(new Contact().load(data));
}
}
Is there a better way to go about doing this? Or is this probably the most efficient way to divvy up the List that I'm given?
Assuming that I cannot change the List itself, the joining via ';' is done server-side on the database before I get it.
Thanks in advance!
Well, String.split() is the most straightforward way, but it does use regex and it can be a bit slow if you do that a lot. However, since you're doing database access (which is a lot slower), I wouldn't worry about it just yet. Run a profiler to see whether you actually have a problem, before trying to get rid of String.split(). Optimization is not something you do just because you feel that something is slow.

Choices for combobox in a repeat

I've got a view that contains documents with various questions I want answered about Purchase Orders.
Using a repeat, I list all the questions. There are a few different kinds of questions, so I only render the answer field that I need based on the FieldType column value. I want to pull the choices for a combobox from the DialogChoices field on the question document.
I'm currently getting the choices showing as plain text on the next line after the empty combobox instead of as the selectItems. Where is my code going wrong?
<xp:comboBox id="comboBox1">
<xp:this.rendered><![CDATA[#{javascript:rowData.getColumnValue("FieldType") == "Dialog Box"; }]]></xp:this.rendered>
<xp:selectItems>
<xp:this.value><![CDATA[#{javascript:var doc:NotesDocument = rowData.getDocument();
var choicesVector:java.util.Vector= doc.getItemValue("DialogChoices");
var choices = [];
// loop through the vector, doing push into the array
for (i=0; i<choicesVector.size(); i++) {
choices.push (choicesVector.elementAt(i))
};
return choices;}]]>
</xp:this.value>
</xp:selectItems>
</xp:comboBox>
Strange, but a test database with the code above does not seem to give me strange results. Maybe it is because the data is in fact not an Vector but just a string?
Here are some tips :
The first thing you could change in your code is the loop to get all the data out of your field. Since the value property of a combobox already expects an array or vector you can change the code to something like:
<xp:this.value><![CDATA[#{javascript:var doc:NotesDocument = rowData.getDocument();
return doc.getItemValue("DialogChoices");
}]]>
</xp:this.value>
But it would be even better to remove the getDocument call at all. If possible you can add a column to the view are you are using for the repeat's datasource. In this column you get the data from the field directory. This way you can use the viewentry's getColumnValue() which is a performance optimization. Something like:
<xp:selectItems>
<xp:this.value><![CDATA[#{try{
return rowData.getColumnValue("DialogChoices");
}catch(e){// do something }]]>
</xp:this.value>
</xp:selectItems>

Having problems with storing variable in classes

Please see ifmy logic is correct i do not know how to implement what i am trying to do. I am a beginner in java.
Game is a class which stores the Name and the Steps of that user after the game is complete.
[ First Method ]
private game[] gameArray = new game[10];
for(int i = 0; i <gameArray.length;i++){
gameArray[i].setName(nameTxt.getText());
gameArray[i].setpSteps(stepsCount);
}
By Clicking History Button they will get the previous 10 people's name and steps.
JOptionPane.showMessageDialog(null,
"Player's Name No. of Steps"+
"\n"+gameArray[i].toString());
-The Problem:
1) This code limits to only previous 10 results is there anyway i can get all the previous results
2) This code is not working!
[ Second Method - This is also not working! ]
private game[] gameArray = new game[10];
// Storing the name of player[i]
gameArray[i].setName(nameTxt.getName());
// Storing the number of steps player[i] took.
gameArray[i].setpSteps(stepsCount);
//Displaying previous 10 players name and steps
JOptionPane.showMessageDialog(null,
"Player's Name No. of Steps"+
"\n"+gameArray[i].toString());
Some points:
you can't directly convert an array to a String through toString() because it isn't supported in Java, you should use Arrays.toString(..)
Java arrays have static size, if you want to store the whole history you will need a dynamic data structure as an ArrayList<Game> or a LinkedList<Game>
name of classes should be capitalized (Game, not game)
without knowing the internals of your Game class it's impossible to tell what is not working and why it is not working, we don't even know what it is supposed to do exactly

Extra bytes appended to values returned by HBase TableMapper

I am working with a large set of data stored in HBase. Many of the values stored in my columns are actually "vectors" of data -- multiple values. The way I've set out to handle storing multiple values is through a ByteBuffer. Since I know the type of data stored in every column in my column families, I have written a series of classes extending a base class that wraps around ByteBuffer and gives me an easy set of methods for reading individual values as well as appending additional values to the end. I have tested this class independently of my HBase project and it works as expected.
In order to update my database (nearly every row is updated in each update), I use a TableMapper mapreduce job to iterate over every row in my database. Each of my mappers (in my cluster, there are six), loads the entire update file (rarely more than 50MB) into memory and then updates each row id as it iterates over it.
The problem I am encountering is that every time I pull a data value out of the Result object, it has 4 bytes appended to the end of it. This makes things difficult for my update because I am not sure whether to expect this "padding" to be an extra 4 bytes every time or whether it could balloon out to something larger/smaller. Since I am loading this into my ByteBuffer wrapper, it is important that there is no padding because that would cause there to be gaps in my data when I appended additional data points to it which would make it impossible to read them out later without error.
I've written up a test to confirm my hypothesis by creating a test table and class. The table only has one data point per column (a single double -- I have confirmed that the length of the bytes going in is 8) and I have written the following code to retrieve and examine it.
HTable table = new HTable("test");
byte[] rowId = Bytes.toBytes("myid");
Get get = new Get(rowId);
byte[] columnFamily = Bytes.toBytes("data");
byte[] column = Bytes.toBytes("column");
get.addColumn(columnFamily, column);
Result = table.get(get);
byte[] value = result.value();
System.out.printlin("Value size: " + value.length);
double doubleVal = Bytes.toDouble(value);
System.out.println("Fetch yielded: " + doubleVal);
byte[] test = new byte[8];
for (int i = 0; i < value.length - 4; i++)
blah[i] = value[i];
double dval = Bytes.toDouble(test);
System.out.println("dval: " + dval);
table.close()
Which results in:
Value size: 12
Fetch yielded: 0.3652
dval: 0.3652
These values are to be expected.
Any thoughts on how to tackle this problem? I'm aware of the existence of serialization engines like Avro but I'm trying to avoid using them for the time being and my data is so straightforward that I feel as though I shouldn't have to.
EDIT: I've continued onward, truncating my data by the greatest common multiple of my data type size. In my experience, these extra bytes are exclusively appended to the end of my byte[] array. I've made a few classes that handle this automatically in a rather clean manner, but I'm still curious as to why this might be happening.
I had a similar problem when importing data using MapReduce into HBase. There were junk bytes appended to my rowkeys, due to this code:
public class MyReducer extends TableReducer<Text, CustomWritable, Text> {
protected void reduce(Text key, Iterable<CustomWritable> values, Context context) throws IOException, InterruptedException {
// only get first value for the example
CustomWritable value = values.iterator().next();
Put put = new Put(key.getBytes());
put.add(columnFamily, columnName, value.getBytes());
context.write(outputKey, put);
}
}
The problem is that Text.getBytes() returns the actual byte array from the backend (see Text) and the Text object is reused by the MapReduce framework. So the byte array will have junk chars from previous values it held. This change fixed it for me:
Put put = new Put(Arrays.copyOf(key.getBytes(), key.getLength()));
If you're using Text as your value type in your job somewhere, it could be doing the same thing.
Is it a jdk7 vs. jdk6 issue? Are you in two different jvm versions?
could be related to something a playorm user ran into
https://github.com/deanhiller/playorm/commit/5e6ede13477a60c2047daaf1f7a7ce55550b0289
Dean

Categories

Resources