I have one problem with my cycle for.
I parse data with JsonParser and after i use one cycle for print all data but i recive only the last result.
This is the code:
try{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
Log.d("id_Persons", "id: " + json_data.getString("id_Persons")
+ ", nome: " + json_data.getString("name")
+ json_data.getString("address")
);
stringaFinale = json_data.getString("id_Persons") + " "
+ json_data.getString("name") + " "
+ json_data.getString("address");
}
return stringaFinale;
}
catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
but, with
Log.d("id_Persons", "id: " + json_data.getString("id_Persons")
+ ", nome: " + json_data.getString("name")
+ json_data.getString("address")
);
I do not understand what is the error.
This is the screen of app
You are overwriting its value in each iteration of for loop.
Change
stringaFinale = json_data.getString("id_Persons") + " " + json_data.getString("name") + " " + json_data.getString("address");
to
stringaFinale += json_data.getString("id_Persons") + " " + json_data.getString("name") + " " + json_data.getString("address");
Note: You should initialize stringaFinale with empty string like this
String stringaFinale = "";
Update: Another nicer way is to use StringBuilder like this
// declare it before the loop
StringBuilder stringaFinale = new StringBuilder(200); // use appropriate size
//Inside the loop
stringaFinale.append(json_data.getString("id_Persons") + " " + json_data.getString("name") + " " + json_data.getString("address"));
//Get the value
stringFinale.toString();
Related
I am trying to get data from a result set into my java application so that I can display it to the user. Something I'd like to implement is a partial search function that displays multiple rows of data based on an input string. If that string appears in any serial number in the database, it pulls that entire row and adds it to a string.
res is the ResultSet
public String searchToString() {
String temp = "";
try {
while(res.next()) {
temp = res.getString("ProductCode") + " " + res.getString("SerialNum") + " "
+ res.getString("DateSold") + " " + res.getString("SoldTo") + " " + res.getString("Notes") + "\n";
}
} catch (SQLException se) {
System.out.println(se);
}
return temp;
}
I have tried changing the queries I use and figured out that the LIKE query was the best one. However, if I try outputting the string to a text area I only see one output where many more are supposed to be. I am definitely missing something from my code to tell it to continue adding the rest of the rows to the string, but I haven't come across anything on the Internet that can tell me what it is.
You are overwriting temp
//try +=
temp += res.getString("ProductCode") + " " + res.getString("SerialNum") + " "
+ res.getString("DateSold") + " " + res.getString("SoldTo") + " " + res.getString("Notes") + "\n";
}
//or temp = temp +
temp = temp + res.getString("ProductCode") + " " + res.getString("SerialNum") + " "
+ res.getString("DateSold") + " " + res.getString("SoldTo") + " " + res.getString("Notes") + "\n";
}
I know a similar question has been posted, however, the answer didn't work for me.
I am new to this RestAssured.I want to get the 'uuid' value if categories equals to 'FUNGI' and feature->features conatains 'VRA'.This is my sample json:
[{
"uuid":"e223d29b-499b-b58b-995e-654bef1aab03",
"categories":[
{
"uuid":"89d1c022-4453-5f6b-883c-46730d429b2a",
"name":"FERTI"
}
],
"minRateSi":0.0
},
{
"uuid":"93015a1b-76ac-2ca3-2bbc-5ae5480962c2",
"categories":[
{
"uuid":"61c951b1-3e47-f0a0-80d8-3d43efa339fb",
"name":"FUNGI"
}
],
"minRateSi":0.0,
"maxRateSi":7.5E-8,
"features":[
{
"id":"9b4ee6b2-ae2d-6c9a-af77-08a4b749031f",
"vraMinRate":2.0E-8,
"features":[
"VRA"
]
},
{
"id":"ec0d0f52-dd71-ebb9-0a39-831768fe4490",
"vraMinRateSi":3.0E-8,
"features":[
"VRA"
]
}
]
},
{
"uuid":"38290452-4937-4f33-c54d-7f502b84ed99",
"categories":[
{
"uuid":"2c9d8cc0-01bc-899d-6782-cf412e90fd78",
"name":"FUNGI"
}
],
"maxRateSi":1.0E-7,
"features":[
{
"id":"9b4ee6b2-ae2d-6c9a-af77-08a4b749031f",
"vraMinRateSi":6.5E-8
},
{
"cropUuid":"ec0d0f52-dd71-ebb9-0a39-831768fe4490",
"vraMinRateSi":5.0E-8
}
]}]
Woo , okay your case was pretty hard to break down, but as far as you know how to use JSONArray and JSONObject classes you will be fine.
First of all let me mention how you should approach this kind of scenarios.
I prefer using an online JSON Formatter like this one simply paste your JSON payload and you will be able to tell whether to use JSONObject or JSONArray.
Please take a note here, and check out how to parse json payloads
This code will work for you, although you need to find out the logic behind it and implement JSON parsing accordingly in your future cases.
//declaring your payload
String myJsonPayload = "[{\r\n" + " \"uuid\":\"e223d29b-499b-b58b-995e-654bef1aab03\",\r\n" +
" \"categories\":[\r\n" + " {\r\n" +
" \"uuid\":\"89d1c022-4453-5f6b-883c-46730d429b2a\",\r\n" +
" \"name\":\"FERTI\"\r\n" + " }\r\n" + " ],\r\n" +
" \"minRateSi\":0.0\r\n" + " },\r\n" + " {\r\n" +
" \"uuid\":\"93015a1b-76ac-2ca3-2bbc-5ae5480962c2\",\r\n" + " \"categories\":[\r\n" +
" {\r\n" + " \"uuid\":\"61c951b1-3e47-f0a0-80d8-3d43efa339fb\",\r\n" +
" \"name\":\"FUNGI\"\r\n" + " }\r\n" + " ],\r\n" +
" \"minRateSi\":0.0,\r\n" + " \"maxRateSi\":7.5E-8,\r\n" + " \"features\":[\r\n" +
" {\r\n" + " \"id\":\"9b4ee6b2-ae2d-6c9a-af77-08a4b749031f\",\r\n" +
" \"vraMinRate\":2.0E-8,\r\n" + " \"features\":[\r\n" +
" \"VRA\"\r\n" + " ]\r\n" + " },\r\n" + " {\r\n" +
" \"id\":\"ec0d0f52-dd71-ebb9-0a39-831768fe4490\",\r\n" +
" \"vraMinRateSi\":3.0E-8,\r\n" + " \"features\":[\r\n" +
" \"VRA\"\r\n" + " ]\r\n" + " }\r\n" + " ]\r\n" + " },\r\n" +
" {\r\n" + " \"uuid\":\"38290452-4937-4f33-c54d-7f502b84ed99\",\r\n" +
" \"categories\":[\r\n" + " {\r\n" +
" \"uuid\":\"2c9d8cc0-01bc-899d-6782-cf412e90fd78\",\r\n" +
" \"name\":\"FUNGI\"\r\n" + " }\r\n" + " ],\r\n" +
" \"maxRateSi\":1.0E-7,\r\n" + " \"features\":[\r\n" + " {\r\n" +
" \"id\":\"9b4ee6b2-ae2d-6c9a-af77-08a4b749031f\",\r\n" +
" \"vraMinRateSi\":6.5E-8\r\n" + " },\r\n" + " {\r\n" +
" \"cropUuid\":\"ec0d0f52-dd71-ebb9-0a39-831768fe4490\",\r\n" +
" \"vraMinRateSi\":5.0E-8\r\n" + " }\r\n" + " ]}]";
JSONArray json = new JSONArray(myJsonPayload);
System.out.println(json);
for (int i = 0; i < json.length(); i++) {
JSONObject object = (JSONObject) json.get(i);
// System.out.println(object); // you have each JSONObject { } contained in the
// Outer JSONArray [ ]
//Getting both uuid's since you didn't answer which one.
String uuid = object.getString("uuid");
System.out.println("\n\n Next Object - Outer UUID: " + uuid);
JSONArray categories = object.getJSONArray("categories");
System.out.println(categories);
if (((JSONObject) categories.get(0)).getString("name").equalsIgnoreCase("fungi")) {
System.out.println("\nFUNGI found!:\n");
//Getting the inner UUID
String uuidOfFungi = ((JSONObject) categories.get(0)).getString("uuid");
System.out.println("Inner UUID: " + uuidOfFungi);
} else {
System.out.println("\nFUNGI NOT FOUND (ABORTING):\n");
}
// Getting Features:
try {
JSONArray featuresObject = object.getJSONArray("features");
for (int index = 0; index < featuresObject.length(); index++) {
try {
JSONObject features = featuresObject.getJSONObject(index);
//Getting VRA
String vraFeatues = features.getJSONArray("features").getString(0);
} catch (JSONException e) {
System.out.println("No inner JSONArray in features JSONObject");
}
}
} catch (JSONException e) {
System.out.println("JSON OBJECT " + i + " HAS NO FEATURES ARRAY");
}
}
Depending again on your use-case it's up to you how you will get the JSON payload into your program.
Getting it from remote URL using Java
Passing it as an argument on java -jar execution time , which i don't really recommend
Either case, modifications need to be done in order to initialize myJsonPayload accordingly.
Hope it helped!
I'm trying to create a JSONObject as code below. But Android Studio is saying that it's null. Where is my mistake?
I tried two different ways to create it.
1st
String JSONString = "{" +
" \"retorno\": {" +
" \"empresas\": [" +
" {" +
" \"cnpj\": \"05.743.645/0001-38\"," +
" \"razao_social\": \"GISELA TRANSPORTES E DISTRIBUIDORA DE FLORES LTDA - ME\"," +
" \"endereco\": \"EST RSC-453 (ROTA DO SOL) KM 93,8\"," +
" \"bairro\": \"BAIRRO ALFANDEGA\"," +
" \"numero\": 26," +
" \"complemento\": \"\"," +
" \"telefone\": \"3462 2749\"," +
" \"celular\": \"\"," +
" \"email\": \"giselaflores#giselaflores.com.br\"" +
" }" +
" ]" +
" }" +
"}";
try {
JSONObject jsonEmpresa = new JSONObject(JSONString);
String email = jsonEmpresa.getString("email");
} catch (JSONException e) {
e.printStackTrace();
}
2nd
try {
JSONObject jsonEmpresa = new JSONObject();
jsonEmpresa.put("cnpj", "05.743.645/0001-38");
jsonEmpresa.put("razao_social", "GISELA TRANSPORTES E DISTRIBUIDORA DE FLORES LTDA - ME");
jsonEmpresa.put("endereco", "EST RSC-453 (ROTA DO SOL) KM 93,8");
jsonEmpresa.put("bairro", "BAIRRO ALFANDEGA");
jsonEmpresa.put("numero", 26);
jsonEmpresa.put("complemento", "");
jsonEmpresa.put("telefone", "3462 2749");
jsonEmpresa.put("celular", "");
jsonEmpresa.put("email", "giselaflores#giselaflores.com.br");
String email = jsonEmpresa.getString("email");
} catch (JSONException e) {
e.printStackTrace();
}
String email's value is null, it should be giselaflores#giselaflores.com.br.
When I tried to debug, I had the message jsonEmpresa: "null".
To get email value for given example, you should to do like
String JSONString = "{" +
" \"retorno\": {" +
" \"empresas\": [" +
" {" +
" \"cnpj\": \"05.743.645/0001-38\"," +
" \"razao_social\": \"GISELA TRANSPORTES E DISTRIBUIDORA DE FLORES LTDA - ME\"," +
" \"endereco\": \"EST RSC-453 (ROTA DO SOL) KM 93,8\"," +
" \"bairro\": \"BAIRRO ALFANDEGA\"," +
" \"numero\": 26," +
" \"complemento\": \"\"," +
" \"telefone\": \"3462 2749\"," +
" \"celular\": \"\"," +
" \"email\": \"giselaflores#giselaflores.com.br\"" +
" }" +
" ]" +
" }" +
"}";
try {
JSONObject jsonEmpresa = new JSONObject(JSONString);
JSONObject retorno = jsonEmpresa.getJSONObject("retorno");
JSONArray empresas = retorno.getJSONArray("empresas");
JSONObject empresa = empresas.getJSONObject(0);
String email =empresa.getString("email");
} catch (JSONException e) {
e.printStackTrace();
}
I want to achieve AutoSuggest ComboBox 2 problems I am facing
1st getting an array of id and name both want the name only.
Array i am receiving
2nd losing focus on typing the text.
Please help
database Query
public SentenceList getAutoProductList() {
return new StaticSentence(s, "SELECT "
+ "P.ID, "
+ "P.REFERENCE, "
+ "P.CODE, "
+ "P.CODETYPE, "
+ "P.NAME, "
+ "P.PRICEBUY, "
+ "P.PRICESELL, "
+ "P.CATEGORY, "
+ "P.TAXCAT, "
+ "P.ATTRIBUTESET_ID, "
+ "P.STOCKCOST, "
+ "P.STOCKVOLUME, "
+ "P.IMAGE, "
+ "P.ISCOM, "
+ "P.ISSCALE, "
+ "P.ISKITCHEN, "
+ "P.PRINTKB, "
+ "P.SENDSTATUS, "
+ "P.ISSERVICE, "
+ "P.ATTRIBUTES, "
+ "P.DISPLAY, "
+ "P.ISVPRICE, "
+ "P.ISVERPATRIB, "
+ "P.TEXTTIP, "
+ "P.WARRANTY, "
+ "P.STOCKUNITS "
+ "FROM PRODUCTS P "
+ "ORDER BY NAME", null, ProductInfoExt.getSerializerRead());
}
Auto Complete JcomboBox Code
SentenceList sentProductNames = dlSales.getAutoProductList();
m_JComboProductName.setEditable(true);
ComboBoxValModel m_jProductNameModel = new ComboBoxValModel();
editor = (JTextComponent) m_JComboProductName.getEditor().getEditorComponent();
List productList = null;
try {
productList = sentProductNames.list();
} catch (Exception e) {
}
productList.add(0, null);
m_jProductNameModel = new ComboBoxValModel(productList);
m_JComboProductName.setModel(m_jProductNameModel);
AutoCompleteDecorator.decorate(m_JComboProductName);
System.out.println("product List "+ productList);
if(m_JComboProductName.getItemCount()>0){
m_JComboProductName.setSelectedIndex(0);
}
I have a method getstaffinfo, which has 3 parameter (var_1, connection, filewriter fw), the var_1 value is read from a text file. So the method will be called as many times based on all the var_1 value passed from text file . approx ( 15000)
public static String getstaffid(String var_1, Connection connection,
FileWriter fw) throws SQLException, Exception
// Create a statement
{
String record = null;
ResultSet rs = null;
Statement stmt = connection.createStatement();
boolean empty = true;
try {
rs = stmt
.executeQuery("select username, firstname, lastname, middlename, street, city, stateorprovince, ziporpostalcode, countryorregion, fax, phone, extension, mobile, pager, title, primaryemail, secondaryemail, officename, description, comments, suspendeddate, userdata, employeeid, createuser, updateuser, createdate, updatedate, employeetype, servicedeskticketnumber, startdate, enddate, manager, businessapprover, technicalapprover, delegate, location, jobcodes, customproperty1, customproperty2, customproperty3, customproperty4, customproperty5, customproperty6, customproperty7, customproperty8, customproperty9, customproperty10 from globalusers where username = '"+ var_1 + "'");
ResultSetMetaData metaData = rs.getMetaData();
int columns = metaData.getColumnCount();
ArrayList<String> records = new ArrayList<String>();
while (rs.next()) {
empty = false;
//record = rs.getString(1) + " " + rs.getString(2) + " " + rs.getString(3) + " " + rs.getString(4) + " " + rs.getString(5) + " " + rs.getString(6) + " " + rs.getString(7) + " " + rs.getString(8) + " " + rs.getString(9) + " " + rs.getString(10) + " " + rs.getString(11) + " " + rs.getString(12) + " " + rs.getString(13) + " " + rs.getString(14) + " " + rs.getString(15) + " " + rs.getString(16) + " " + rs.getString(17) + " " + rs.getString(18) + " " + rs.getString(19) + " " + rs.getString(20) + " " + rs.getString(21) + " " + rs.getString(22) + " " + rs.getString(23) + " " + rs.getString(24) + " " + rs.getString(25) + " " + rs.getString(26) + " " + rs.getString(27) + " " + rs.getString(28) + " " + rs.getString(29) + " " + rs.getString(30) + " " + rs.getString(31) + " " + rs.getString(32) + " " + rs.getString(33) + " " + rs.getString(34) + " " + rs.getString(35) + " " + rs.getString(36) + " " + rs.getString(37) + " " + rs.getString(38) + " " + rs.getString(39) + " " + rs.getString(40) + " " + rs.getString(41) + " " + rs.getString(42) + " " + rs.getString(43) + " " + rs.getString(44) + " " + rs.getString(45) + " " + rs.getString(46) + " " + rs.getString(47);
for (int i = 1; i <= columns; i++) {
String value = rs.getString(i);
records.add(value);
}
for (int j = 0; j < records.size(); j++) {
record = records.get(j) + ",";
}
fw.append(record);
}
/*fw.append(rs.getString(1));
fw.append(',');
fw.append(rs.getString(2));
fw.append(',');
fw.append(rs.getString(3));
fw.append('\n'); */
} finally {
fw.flush();
rs.close();
stmt.close();
}
return record;
}
As you can see, am executing a query for 47 values, which could be null or it can have some value.
Then i iterate through this 47 column, take the value and store it to an array list. Then i iterate the array list and write all the values to the string record with comma seperated value. Which is written to a csv file.
But it does not work fine. Any inputs would be appreciated...
You may have already solved the problem. Just let you know that I tried to use your code just now and found the issue was here:
record = records.get(j) + ",";
You should use something like this:
record = record + records.get(j) + ",";
Also change String to StringBuffer will improve the performance.
You didn't write the exact problem you face, but there is one for sure: you never write a line break into the file, so all data gets in one line.
while (rs.next()) {
... // your code, with the for loops
fw.append(record); //writing out the line, from your code
fw.append("\r\n"); //line break -- add this line
} //this is the end of the "while(rs.next())" loop
...