Reputation: 1142
I'm adding multiple bytes array from each row, that means I need to append all of them to a variable. But this prints a empty byte array because it can't be changed. What I can do to append more bytes?
ResultSet rs = stmt.executeQuery(query);
int matchesLength = 0;
try {
boolean b = rs.last();
if (b) {
matchesLength = rs.getRow();
}
}
catch (SQLException e) {
e.printStackTrace();
}
byte[] matches = new byte[118 * matchesLength];
while ( rs.next() ) {
String matchId = rs.getString("id");
String matchTitle = rs.getString("title");
String matchDescription = rs.getString("description");
int matchPlayers = rs.getInt("max_players");
int matchMaxPlayers = rs.getInt("max_players");
String matchHostId = rs.getString("host_id");
short matchPlayersShort = (short) matchPlayers;
byte[] matchPlayersBytes = ByteBuffer.allocate(2).putShort(matchPlayersShort).array();
short matchMaxPlayersShort = (short) matchMaxPlayers;
byte[] matchMaxPlayersBytes = ByteBuffer.allocate(2).putShort(matchMaxPlayersShort).array();
byte[][] match = {
String.format("%1$-" + 32 + "s", matchId).getBytes(),
String.format("%1$-" + 22 + "s", matchTitle).getBytes(),
String.format("%1$-" + 44 + "s", matchDescription).getBytes(),
matchPlayersBytes,
matchMaxPlayersBytes,
String.format("%1$-" + 16 + "s", matchHostId).getBytes()
};
// global offset variable, for each array copy
combineBytes(match, matches);
}
Upvotes: 1
Views: 1043
Reputation: 550
Why not to create a class for encapsulate each row?
public class Match{
private String matchId;
private String matchTitle;
private String matchDescription;
etc....
set and get for all variables;
public byte[] getBytes(){
here a logic to transform this attributes in a array of bytes
}
}
Then you create a ArrayList matchList that will be filled in the rs.next() loop.
Then you will just need:
while(rs.next()){
match = new Match();
match.setBlabla(rs.get(value));
....all sets
list.add(match);
}
when you send it through socket to your clients you just read the list and do your logic with the bytes.
Lets supose you have a list of 10 rows and you want it as bytes.
ArrayList<Match> matchList = new ArrayList<Match>();
Match m;
while(rs.next()){
m = new Match();
m.set // one set for each attribute getting the value from rs.get
matchList.add(m);
}
Now for send it:
for(Match m : matchList){
byte[] bytesToSend = m.getBytes(); //you defined this method
send(bytesTosend) //one match send for time
}
IF you want to send all matches togheter, you have to do a loop to calculate the total bytes in the list because each Match in the list will have a diferent size in bytes (description changes, title chantes etc)
Upvotes: 1