Send Byte from jComboBox - java

I have a jComboBox with these values:
String[] preset = { "1", "2", "3", "4", "5" };
So if "1" is selected then i want to add a byte to my OutputStream.
byte preset1 = 0X01;
based on the selection in the combobox. I thought it might be this but it gives a NullPointerException.
byte preset = (byte)setPresetcomboBox.getSelectedItem();
try {
byte[] command = {(byte) startTx, address, setPreset, 0x00, preset, endTx, 0x0F};
TwoWaySerialComm.SerialWriter sw = new TwoWaySerialComm.SerialWriter(
twoWaySerCom.serialPort.getOutputStream());
sw.out.write(command);
} catch (IOException e) {
e.printStackTrace();
}
What am i doing wrong here? Apologies if this is obvious, this is my first ever project.

This was solved by changing
String[] preset = { "1", "2", "3", "4", "5" };
to
Byte[] preset = { 1, 2, 3, 4, 5};
making the combobox like this:
setPresetcomboBox = new JComboBox<Byte>(preset);
and my action performed:
byte _preset = (Byte)setPresetcomboBox.getSelectedItem();

Related

Java - Read data from a json with the JSON library according to an object

I have a JSON with some data and I would like to print as follows
10 REGISTER 1, KP SUM 2081,606
20 REGISTER 2 CH SUM 0,22
Where the general sum is calculated by the total sum of the items according to the code.
Following the rule, first multiply the quantity by the unit and then add all the items that have the same code.
Example:
code 10
SUM = 0,0200000 * 7,40 + 10,0000000 * 200,31 + 0,5690000 * 40,19 + 0,7890000 * 70,33
The same goes for the other codes that appear in JSON
My JSON
[
{
"code": 10,
"description": "REGISTER 1",
"unity": "KP",
"typeItem": "I",
"itemCode": 1,
"descriptionItem": "ITEM",
"unityItem": "UN",
"quantity": "0,0200000",
"valueUnity": "7,40"
},
{
"code": 10,
"description": "REGISTER 1",
"unity": "KP",
"typeItem": "I",
"codeItem": 2,
"descriptionItem": "ITEM 2",
"unityItem": "UN",
"quantity": "10,0000000",
"valueUnity": "200,31"
},
{
"code": 10,
"description": "REGISTER 1",
"unity": "KP",
"typeItem": "I",
"codeItem": 88248,
"descriptionItem": "ITEM 3",
"unityItem": "H",
"quantity": "0,5690000",
"valueUnity": "40,19"
},
{
"code": 10,
"description": "REGISTER 1",
"unity": "KP",
"typeItem": "I",
"codeItem": 88267,
"descriptionItem": "ITEM 4",
"unityItem": "N",
"quantity": "0,7890000",
"valueUnity": "70,33"
},
{
"code": 20,
"description": "REGISTER 2",
"unity": "CH",
"typeItem": "I",
"codeItem": 1,
"descriptionItem": "ITEM 1",
"unityItem": "H",
"quantity": "30,0000000",
"valueUnity": "0,17"
},
{
"code": 20,
"description": "REGISTER 2",
"unity": "CH",
"typeItem": "I",
"codeItem": 2,
"descriptionItem": "ITEM 2",
"unityItem": "H",
"quantity": "3,0000000",
"valueUnity": "0,07"
}
]
My class Java
public class MyJson {
#SerializedName("code")
#Expose
private Integer code;
#SerializedName("description")
#Expose
private String description;
#SerializedName("unity")
#Expose
private String unity;
#SerializedName("typeItem")
#Expose
private String typeItem;
#SerializedName("codeItem")
#Expose
private Integer codeItem;
#SerializedName("descriptionItem")
#Expose
private String descriptionItem;
#SerializedName("unityItem")
#Expose
private String unityItem;
#SerializedName("quantity")
#Expose
private String quantity;
#SerializedName("valueUnity")
#Expose
private String valueUnity;
private Double total;
}
My Program
public static void main(String[] args) {
Gson gson = new Gson();
try {
File jsonFile = new File("C:\\my_json.json");
InputStreamReader reader = new InputStreamReader(new FileInputStream(jsonFile), "UTF-8");
BufferedReader jsonBuffer = new BufferedReader(reader);
MyJson[] myJsonArray = gson.fromJson(jsonBuffer, MyJson[].class);
BigDecimal valueUnity = BigDecimal.ZERO;
BigDecimal sumTotal = BigDecimal.ZERO;
//
Set<MyJson> list = new HashSet<>();
for(MyJson myJson : myJsonArray) {
if(checkStringNullOrEmpty(myJson.getQuantity()) && checkStringNullOrEmpty(myJson.getValueUnity())) {
if(myJson.getCode().equals(myJson.getCode())) {
String value1 = myJson.getQuantity().replaceAll( "," , "." ).trim();
String value2 = myJson.getValueUnity.replaceAll( "," , "." ).trim();
BigDecimal quantity = new BigDecimal(value1);
BigDecimal valueUnit = new BigDecimal(value2);
valueUnity = quantity.multiply(valueUnit);
somaTotal = sumTotal.add(valueUnity);
String resultado = String.format(Locale.getDefault(), "%.2f", valueUnity);
String sumTotal2 = String.format(Locale.getDefault(), "%.2f", sumTotal);
myJson.setTotal(new Double(sumTotal2.replaceAll( "," , "." ).trim()));
list.add(myJson);
}
}
}
for(MyJson myJson : list) {
StringBuilder builer = new StringBuilder();
builer.append(myJson.getCode()).append(" ");
builer.append(myJson.getDescription().toUpperCase()).append(" ");
builer.append(myJson.getUnity().toUpperCase()).append(" ");
builer.append(myJson.getTotal());
System.out.println(builer.toString());
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static boolean checkStringNullOrEmpty(String value) {
if(!value.isEmpty()) {
return true;
} else {
return false;
}
}
Exit program
The calculation is being done wrong when using the Set
10 REGISTER 1, KP SUM 130,33
20 REGISTER 2 CH SUM 439,18
You cannot keep track of multiple running totals (i.e. one for each code) using one total. Instead you will need one total for each different code.
I would recommend that you use a Map<Integer, MyJson> for this purpose. This would store a number of MyJson objects which you could look up by their code. When handling each MyJson object, you check to see if you already have a MyJson object with the same code: if you do then you add to its total, otherwise you add your MyJson object to the map.
Get rid of your Set<MyJson> variable (which you have somewhat confusingly named list) and replace it with the following
Map<Integer, MyJson> jsonsByCode = new LinkedHashMap<>();
(You can use a HashMap<> instead of a LinkedHashMap<> here: I chose to use a LinkedHashMap<> because it keeps its entries in the same order they were inserted into it.)
Then, replace all lines from somaTotal = sumTotal.add(valueUnity); to list.add(myJson); with
if (jsonsByCode.containsKey(myJson.getCode())) {
// We've seen this code before, so add the value
// to the total.
MyJson matchingJson = jsonsByCode.get(myJson.getCode());
matchingJson.setTotal(matchingJson.getTotal() + valueUnity.doubleValue());
} else {
// First time seeing this code, so set its total
// and add it to the map.
myJson.setTotal(valueUnity.doubleValue());
jsonsByCode.put(myJson.getCode(), myJson);
}
(Note that BigDecimal values such as valueUnity have a .doubleValue() method on them, which is the easiest way to convert them to a double.)
Then, in the for loop below, where you are printing out the values, replace list with jsonsByCode.values().
I made these changes to your program and it generated the following output:
10 REGISTER 1 KP 2081.60648
20 REGISTER 2 CH 5.31
Incidentally, your code also contains the following if statement:
if(myJson.getCode().equals(myJson.getCode())) {
// ....
}
You are comparing myJson.getCode() against itself, so this condition will always be true (unless of course myJson.getCode() returns null, in which case you get a NullPointerException). You can just get rid of this check, it doesn't do anything useful.

JSON Unterminated object at character android

I have a .json file that contains JSON data. I created this file by simply Ctrl + C and Ctrl + V (from server output) Here's part of my file
[{
"ID": "109",
"objectTypeID": "1",
"names": [{
"ID": 1,
"code": "lt",
"value": "Trak\u0173 salos pilis "
}, {
"ID": 2,
"code": "en",
"value": "Trakai Island Castle"
}, {
"ID": 3,
"code": "ru",
"value": "\u0422\u0440\u0430\u043a\u0430\u0439\u0441\u043a\u0438\u0439 \u0437\u0430\u043c\u043e\u043a"
}, {
"ID": 4,
"code": "de",
"value": "Kasteel van Trakai"
}],
"descriptions": [{
"ID": 1,
"code": "lt",
"value": "<div><strong>Paslap\u010di\u0173 m\u0117g\u0117jams ir ieškotojams<\/strong><\/div>\r\n\r\n<div>Tiems, kurie domisi istorija, kurie m\u0117gsta paslaptingas vietoves, \u012f Trakus atkeliauti b\u016btina. Trak\u0173 pilis yra vienas labiausiai turist\u0173 lankom\u0173 objekt\u0173 Lietuvoje......"
}]
}]
I have saved this file with utf-8 encoding
As you can see there are lot of Unicode Characters and html elements like <div>, <strong> and so on....
Now I want to parse this file. Here's my java/android code
private String getJSONString(File file){
try {
FileInputStream is = new FileInputStream(file.getAbsolutePath());
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
return new String(buffer, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private void object_parser(File file){
String jsonString = getJSONString(file);
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(jsonString);
Log.d("OBJECTS_LIST_AAA", jsonArray.toString());
} catch (JSONException e) {
Log.d("OBJECTS_LIST_ERROR", e.getMessage()); // print error
e.printStackTrace();
}
}
}
and I get this error Unterminated object at character 5641 of [{"ID":"109","objectTypeID":"1","names":[{"ID":1,"code":"lt","value":"Trak\u0173 salos pilis "},......
I think that formating is missing in this file.
Your Every "Restaurant "Avilys"" like data are invalid, You have to replace all of them with "Restaurant Avilys" as a single String value quoted with only two quotation marks. There are many similar cases like these as well. And note that the part you posted is clearly valid and can be parsed easily, Here is no such errors.

How to grab inner JSON map

Im trying to get specific values from the map.
I need to get value assigned to "leaguePoints", "tier", "rank", for
"queueType": "RANKED_SOLO_5x5" && "playerOrTeamName": "Invicterr".
I added code I try below.
I think I need to iterate entries:[], but I have no idea how to to this.
Im a total JSON newbie, and Java begginer.
Map:
"32303008": {
"queue": "RANKED_SOLO_5x5",
"name": "Sejuani's Berserkers",
"entries": [
{
"isHotStreak": false,
"isFreshBlood": false,
"leagueName": "Sejuani's Berserkers",
"miniSeries": {
"progress": "LWN",
"target": 2,
"losses": 1,
"timeLeftToPlayMillis": 0,
"wins": 1
},
"isVeteran": false,
"tier": "PLATINUM",
"lastPlayed": 0,
"playerOrTeamId": "21747474",
"leaguePoints": 100,
"rank": "V",
"isInactive": false,
"queueType": "RANKED_SOLO_5x5",
"playerOrTeamName": "sunchasee",
"wins": 127
},
{
"isHotStreak": false,
"isFreshBlood": false,
"leagueName": "Sejuani's Berserkers",
"isVeteran": false,
"tier": "PLATINUM",
"lastPlayed": 1389198358615,
"playerOrTeamId": "32303008",
"leaguePoints": 64,
"rank": "V",
"isInactive": false,
"queueType": "RANKED_SOLO_5x5",
"playerOrTeamName": "Invicterr",
"wins": 462
}
],
"tier": "PLATINUM"
}
My code:
for (Map.Entry<String, League> entry : leagues.entrySet())
{
try
{
if(Integer.parseInt(entry.getKey()) == 32303008)
{
System.out.println(entry.getKey() + "|" + entry.getValue());
}
}
catch(Exception e){}
}
I would recommend using something like JSON Simple. This will convert your JSON to a Java object that will be more simple to work with.
Pseudocode:
Map jsonMain = JSONParser.parse(myJSONSourceString);
Map numberedEntry = (Map)(jsonMain.get("3203008"));
List entries = (List)(numberedEntry.get("entries"));
for (int i = 0; i < entries.size(); i++) {
Map theEntry = (Map)(entries.get(0));
String queueType = (String)(theEntry.get("queueType"));
String playerOrTeamName = (String)(theEntry.get("playerOrTeamName"));
if (queueType.equals("RANKED_SOLO_5x5") && (playerOrTeamName.equals("Invicterr")) {
Number leaguePoints = (Number)(theEntry.get("leaguePoints"));
int leaguePointsValue = leaguePoints.intValue();
String tier = (String)(theEntry.get("tier"));
String rank = (String)(theEntry.get("rank"));
// Do something with the values
break;
}
}
The precise types and method names (and whether casting is needed) will depend on which JSON kit you use.

Inserting object with different values in a ArrayList

I have a JFrame where I insert some informations, these informations I send to a object called "macro". When I hit a JButton "macro" is insert in a ArrayList, called "listaJFP". When I enter with the first informations like, name "Murilo", id "1", and hit the button, my ArrayList receives the correct information, but when I try to insert another name like "Joao", id "2", my ArrayList receives in the first index [0] Joao, 2, and second index[1] Joao, 2. Instead of [0]Murilo,1 and [1]Joao,2. I looked for this problem and I saw someone talking about the reference of the object, in other words, when I change the values of my object "macro" at the same time the values of my ArrayList are changed. Can someone help me, please ? Thanks for the attention !
This is in my class JFramePrincipal:
Macro macro = new Macro();
private List<Macro> listaJFP = new ArrayList<Macro>();
This is in my JButton actionPerformed:
listaJFP.add(macro);
JFrameTabela jfT = new JFrameTabela(listaJFP);
I will try to put more code:
public class JFramePrincipal extends javax.swing.JFrame {
private List<Macro> listaJFP = new ArrayList<Macro>();
Macro macro = new Macro();
String[] arrayNodeName;
String[] listaVelocidade = new String[]{"1024", "1984"};
String[] listaSlot = new String[]{"2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13"};
String[] listaModule86x0 = new String[]{"0", "1"};
String[] listaModule8609 = new String[]{"3", "4"};
String[] listaPort = new String[]{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23"};
String[] listaPortFeGe = new String[]{"0", "1", "2", "3", "4", "5", "6", "7"};
String[] nodeType = new String[]{"8609", "8630", "8660"};
private void jButtonGerarMacroActionPerformed(java.awt.event.ActionEvent evt) {
try {
if (jCheckBoxFSP.isSelected() == true) {
macro.setVpnName(jFormattedTextFieldFSP.getValue().toString());
} else if (jCheckBoxSP.isSelected() == true) {
macro.setVpnName(jFormattedTextFieldSP.getValue().toString());
}
macro.velocidade = jComboBoxVelocidade.getSelectedItem().toString();
if (jTextVLAN.isEnabled() == true) {
int vlanInt;
boolean ok = false;
vlanInt = Integer.parseInt(jTextVLAN.getText());
do {
if (vlanInt >= 1 && vlanInt <= 4094) {
macro.vlan = jTextVLAN.getText();
gerar();
jButtonExecutarMacro.setEnabled(true);
} else {
JOptionPane.showMessageDialog(null, "VLAN deve ser maior do que 0 e menor do que 4094", "Mensagem", JOptionPane.ERROR_MESSAGE);
jTextVLAN.grabFocus();
jButtonExecutarMacro.setEnabled(false);
}
} while (ok);
} else {
macro.vlan = null;
gerar();
jButtonExecutarMacro.setEnabled(true);
jButtonGerarMacro.setEnabled(false);
}
private void jButtonExibirResultadoActionPerformed(java.awt.event.ActionEvent evt) {
if(jCheckBoxE1.isSelected() == true){
listaJFP.add(macro);
Macro macro = new Macro();
JFrameTabela jfT = new JFrameTabela(listaJFP);
}
Did you make sure to create a new Macro for every input from GUI
You have to Create a new Macro like this
public void actionPerformed(ActionEvent e){
Macro macro = new Macro();
listaJFP.add(macro);
}
// so it create a totally new Macro object everytime
Edit: After OP edit with more code
You need to create to new Macro inside to the first ActionPerformed because that's where you're manipulating the data. And why do you have two different actionperformed for a similar task?

How to manipulate an array similar to an ORDER BY clause in SQL?

My data has been placed into an array, but unfortunately not in the order I want it in...
String[][] databaseToArray = {
//{"Name", "Channel", "Description", "Amount", "isReady"},
{"John", "Nick", "likes", "2", "yes" },
{"Drew", "MTV", "dislikes", "4", "no" },
{"Fred", "CNN", "okay", "3", "no" },
{"Beth", "Fox", "valid", "1", "yes" }
};
How do I manipulate this array so that when I loop through it the order is by the amount , similar to SELECT * FROM "databaseToArray" ORDER BY "Amount" aka
String[][] reorganizedArray = {
//{"Name", "Channel", "Description", "Amount", "isReady"},
{"Beth", "Fox", "valid", "1", "yes" },
{"John", "Nick", "likes", "2", "yes" },
{"Fred", "CNN", "okay", "3", "no" },
{"Drew", "MTV", "dislikes", "4", "no" }
};
You'll want to pass a Comparator to the Arrays.sort method. I haven't done Java in 5 years, but it should be easily doable. Maybe someone can clean up this example I'm about to write, since I'm pretty certain I'll get something wrong.
String[][] databaseToArray = {
//{"Name", "Channel", "Description", "Amount", "isReady"},
{"John", "Nick", "likes", "2", "yes" },
{"Drew", "MTV", "dislikes", "4", "no" },
{"Fred", "CNN", "okay", "3", "no" },
{"Beth", "Fox", "valid", "1", "yes" }
};
Arrays.sort(databaseToArray, new Comparator<String[]>() {
public int compare(String[] a, String[] b) {
return a[3].compareTo(b[3]);
}
});
I found the sort method on the processing website, but this is only for One-Dimensional Arrays...
http://processing.org/reference/sort_.html
float[] a = { 3, 5, 2, 4, 1 };
a = sort(a);
println(a);
// Prints 1, 2, 3, 4, 5

Categories