I used the code below to retrieve json data and put it in a table. That worked. But I want to display the data in a combobox now. Right now, it is displaying the items in the dropdown in this format: ljava.lang.string #5c647e05
Can someone please tell me what I'm doing wrong? Thank you.
Hashtable response = parser.parse(reader);
java.util.List allResult = (java.util.List) response.get("AllResult");
System.out.println(allResult);
try {
String[][] data = new String[allResult.size()][4];
for (int i = 0; i < allResult.size(); i++) {
Object obj = allResult.get(i);
String result = (String) ((Hashtable) obj).get("Status");
String investorName = (String) ((Hashtable) obj).get("investorName");
if (result.equalsIgnoreCase("ok")) {
for (int j = 0; j < 4; j++) {
if (j == 0) {
data[i][j] = investorName; }
}
}
}
ComboBox investorNames = new ComboBox(data);
details.addComponent(investorNames);
System.out.println("Data here: " + data);
String[] columnNames = { "Seller's Name", "Stock Name", "Unit", "Price" };
TableModel model = new DefaultTableModel(columnNames, data, false);
Table table = new Table(model);
table.setScrollable(true);
details.addComponent(table);
} catch (Exception ex) {
ex.printStackTrace();
}
}
Try to paste in Combobox only vector of invector names not whole array of arrays. As Combobox just invokes toString() on every array (row) of matrix, that's why you got Ljava.lang.String#5c647e05 and not investor names. Something like this:
String[] comboData = new String[allResult.size()];
for (int i = 0; i < allResult.size(); i++){
...
String investorName = (String) ((Hashtable) obj).get("investorName");
comboData[i] = investorName
...
}
ComboBox investorNames = new ComboBox(comboData);
details.addComponent(investorNames);
....
ComboBox expects an array of string but you are passing to it an array of array of strings.
So those ljava.lang.string #5c647e05 that you are seeing are the 'toString' representation of an array of strings.
You need to somehow (depending on what you need to do) flatten your 'data' so that it becomes an array of strings.
Related
I'm receiving an error when opening my OpenXML created spreadsheet. The error is as follows.
repaired record : xl/worksheets/sheet.xml partial cell information
private void SavexlsExcelFile(String fullPathName)
{
using (SpreadsheetDocument document = SpreadsheetDocument.Create(fullPathName, SpreadsheetDocumentType.Workbook))
{
WorkbookPart workbookPart = document.AddWorkbookPart();
workbookPart.Workbook = new Workbook();
worksheetPart = workbookPart.AddNewPart<WorksheetPart>();
worksheetPart.Worksheet = new Worksheet();
Columns columns = new Columns();
worksheetPart.Worksheet.AppendChild(columns);
Sheets sheets = workbookPart.Workbook.AppendChild(new Sheets());
Sheet sheet = new Sheet() { Id = workbookPart.GetIdOfPart(worksheetPart), SheetId = 1, Name = "Sheet" };
sheets.Append(sheet);
workbookPart.Workbook.Save();
sheetData = worksheetPart.Worksheet.AppendChild(new SheetData());
List<List<string>> dataRow = new List<List<string>>();
List<String> dtRow = new List<String>();
Row row = new Row();
for (int i = 0; i < dataGridView1.RowCount; i++)
{
for (int j = 0; j < dataGridView1.ColumnCount; j++)
{
if (i == 0)
{
Cell dataCell = new Cell();
dataCell.DataType = CellValues.String;
CellValue cellValue = new CellValue();
cellValue.Text = dataGridView1.Columns[j].Name;
dataCell.StyleIndex = 2;
dataCell.Append(cellValue);
row.AppendChild(dataCell);
//dataColumn.Add(dataGridView1.Columns[j].Name);
}
dtRow.Add(dataGridView1.Rows[i].Cells[j].Value.ToString());
}
}
dataRow.Add(dtRow);
sheetData.AppendChild(row);
row = new Row();
foreach (List<string> datarow in dataRow)
{
row = new Row();
foreach(string dtrow in datarow)
{
row.Append(ConstructCell(dtrow, CellValues.String, 2));
}
sheetData.AppendChild(row);
}
worksheetPart.Worksheet.Save();
}
}
private Cell ConstructCell(string value, CellValues dataType, uint styleIndex = 0)
{
return new Cell()
{
CellValue = new CellValue(value),
DataType = new EnumValue<CellValues>(dataType),
StyleIndex = styleIndex
};
}
There are 2 issues here that I can see. The first is that your use of Columns is incorrect. You should use Columns if you wish to control things such as the width of a column. To use Columns correctly, you'll need to add child Column elements. For example (taken from here):
Columns columns = new Columns();
columns.Append(new Column() { Min = 1, Max = 3, Width = 20, CustomWidth = true });
columns.Append(new Column() { Min = 4, Max = 4, Width = 30, CustomWidth = true });
In your sample you could just remove the following two lines
Columns columns = new Columns();
worksheetPart.Worksheet.AppendChild(columns);
The second issue is the StyleIndex you are using; the style doesn't exist in your document because you haven't added it. The easiest thing to do here is to just remove the StyleIndex altogether.
When debugging files like this, it's always worth looking at the OpenXml Productivity Tool. You can open a generated file in the tool and validate it to see what errors you have in your file.
All the text in Excel is stored under a shared string table. You need to insert the string in shared string table:
string text = dataGridView1.Columns[j].Name;
cell.DataType = CellValues.SharedString;
if (!_spreadSheet.WorkbookPart.GetPartsOfType<SharedStringTablePart>().Any())
{
_spreadSheet.WorkbookPart.AddNewPart<SharedStringTablePart>();
}
var sharedStringTablePart = _spreadSheet.WorkbookPart.GetPartsOfType<SharedStringTablePart>().First();
if (sharedStringTablePart.SharedStringTable == null)
{
sharedStringTablePart.SharedStringTable = new SharedStringTable();
}
//Iterate through shared string table to check if the value is already present.
foreach (SharedStringItem ssItem in sharedStringTablePart.SharedStringTable.Elements<SharedStringItem>())
{
if (ssItem.InnerText == text)
{
cell.CellValue = new CellValue(ssItem.ElementsBefore().Count().ToString());
SaveChanges();
return;
}
}
// The text does not exist in the part. Create the SharedStringItem.
var item = sharedStringTablePart.SharedStringTable.AppendChild(new SharedStringItem(new Text(text)));
cell.CellValue = new CellValue(item.ElementsBefore().Count().ToString());
Why I am getting duplicate entries in my ArrayList<String[]>?
allStepsJSONStringArray contains an array of single strings in the format of JSON
I loop through and pass each JSON string to a function that writes it to a temporary internal file
I read the file
Then pass it to getStepsArray() which breaks down the JSON string and puts each entry into a String[]
Loop to add to master ArrayList - allStepsArray
for (int i = 0; i < allStepsJSONStringArray.size(); i++) {
writer.writeToInternal(allStepsJSONStringArray.get(i));
reader.readFromInternal(writer.filename);
stepsArray = reader.getStepsArray();
for (int s = 0; s < stepsArray.size(); s++) {
allStepsArray.add(stepsArray.get(s));
}
}
getStepsArray()
public ArrayList<String[]> getStepsArray() {
try {
JSONObject jObject = new JSONObject(jsonString);
JSONArray jArray = jObject.getJSONArray("steps");
String stepOrder = null;
String stepName = null;
String stepType = null;
String stepId = null;
String checklistId = null;
String checklistName = null;
for (int i = 0; i < jArray.length(); i++) {
stepOrder = jArray.getJSONObject(i).getString("order");
stepName = jArray.getJSONObject(i).getString("name");
stepType = jArray.getJSONObject(i).getString("type");
stepId = jArray.getJSONObject(i).getString("id");
checklistId = jObject.getString("checklistId");
checklistName = jObject.getString("checklistName");
stepsArray.add(new String[] {stepOrder, stepName, stepType, stepId, checklistName, checklistId});
}
} catch (Exception e) {
e.printStackTrace();
}
return stepsArray;
}
Word for word:
Because you don't seem to ever reset stepsArray. The second time you add elements to it, the previous elements will still be there and will get added to allStepsArray again.
I'm having a bit of a problem when running the code below. This code is used when a button on a gui screen is pressed. Basically the function of this button is to read text entered into 2 text fields, derive a third value from the 2, and save all 3 in a row in a table on the GUI screen, using a 2d array.
However, i get a NullPointerException when executing it at the 5th line inside the method addItem().
saleData is the 2D array with data which is in the table.
i have instantiated the temp[][] object with 1 row more than the saleData object because i need to add a row to the table, and then i make saleData=temp.
This code worked as it is in the Gui class before i tried using OOP to create a separate class for the GUI to work from.
The nullpointer exception refers to the temp object, i know this because i printed out the value of temp and it was a null.
Does anyone have any ideas?
thanks in advance.
public void addItem() {
int len = saleData.length + 1;
Object[][] temp = new Object[len][3];
for (int k = 0; k < saleData.length; k++) {
for (int i = 0; i < 3; i++) {
temp[k][i] = ((DefaultTableModel) table.getModel()).getValueAt(k, i);
}
}
tblContainer.removeComponent(table);
try {
int qty = Integer.parseInt(txtQty.getText());
String item = (String) items.getSelectedItem();
String sql = "Select Sell_price from stockInfo where parts like '" + item + "'";
double total = 0;
if (saleData.length != 1) {
for (int i = 0; i < saleData.length; i++) {
String sql2 = "Select sell_price from stockinfo where parts like '" + temp[i][1].toString() + "'";
try {
System.out.println("Check 0");
pst = conn.prepareStatement(sql2);
System.out.println("Check 1");
rs = pst.executeQuery();
System.out.println("Check 2");
while (rs.next()) {
System.out.println("Check 3");
String qt = temp[i][0].toString();
temp[i][2] = Double.parseDouble(rs.getString("sell_price")) * Integer.parseInt(qt);
System.out.println("Check 4");
}
} catch (Exception e) {
Dialog.show("Error", "Error 1: " + e, "OK", null);
}
}
}
try {
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
while (rs.next()) {
double price = Double.parseDouble(rs.getString("Sell_Price"));
total = qty * price;
try {
for (int m = 0; m < saleData.length; m++) {
for (int n = 0; n < 3; n++) {
((DefaultTableModel) table.getModel()).setValueAt(m, n, temp[m][n]);
}
}
temp[saleData.length][0] = qty;
temp[saleData.length][1] = item;
temp[saleData.length][2] = total;
saleData = temp;
table = new Table(new DefaultTableModel(saleColumns, saleData, true));
tblContainer.addComponent(table);
((TableLayout) table.getLayout()).setGrowHorizontally(true);
saleForm.revalidate();
} catch (NullPointerException e) {
}
}
} catch (SQLException e) {
Dialog.show("Error", "SQL Error Record Sale", "OK", null);
}
} catch (NumberFormatException nfe) {
Dialog.show("Error", "Please enter a valid quantity", "OK", null);
}
}
The temp array can not be null. You just created it.
temp[k][i] can be null (and should be, by the way), but that does not matter - it is being assigned a value.
If a dimension of temp would not be big enough, you'd get an ArrayIndexOutOfBoundsException
So this leaves for two things that can get to be null (if the error stems from that line, and not for example from the inside of getValueAt(k,i) ):
table
table.getModel()
Use a debugger, and it will make your life easier...
I created a registration form, that collects data from user, and display it into a Jtable, then I want to allow user to press a button to export the Jtable content to excel form. In the display table, it can show all user input, but when I export to excel, it only show columnNames and first row of data, so I want to know if I have done it wrong?
User input:
ArrayList<ArrayList<String>> list = new ArrayList<ArrayList<String>>();
String[] columnNames = new String[] {"First Name", "Last Name", "Email", "Degree", "Year", "Event"};
Object[][] tabledata = new Object[1][6];
String fn = FirstName.getText();
String ln = LastName.getText();
String em = Email.getText();
String re = ReEnter.getText();
String de = Degree.getSelectedItem().toString();
String yr = Year.getSelectedItem().toString();
String ev = EventDate.getSelectedItem().toString();
ArrayList<String> data = new ArrayList<String>();
data.add(fn);
data.add(ln);
data.add(em);
data.add(de);
data.add(yr);
data.add(ev);
list.add(data);
//Set fields to empty
FirstName.setText("");
LastName.setText("");
Email.setText("");
ReEnter.setText("");
Degree.setSelectedItem(null);
Year.setSelectedItem(null);
EventDate.setSelectedItem(null);
// print data to table
Object[][] temp = new Object[tabledata.length+1][6];
for(int i=0;i<tabledata.length;i++){
for(int j=0;j<6;j++){
temp[i][j] = tabledata[i][j];
}
temp[tabledata.length-1][0]= fn;
temp[tabledata.length-1][1]= ln;
temp[tabledata.length-1][2]= em;
temp[tabledata.length-1][3]= de;
temp[tabledata.length-1][4]= yr;
temp[tabledata.length-1][5]= ev;
}
tabledata = temp;
table.setModel(new DefaultTableModel(tabledata, columnNames));
}
}
Export data to excel:
try {
TableModel model = table.getModel();
File file = new File("member.xls");
FileWriter output = new FileWriter(file);
for(int i = 0; i <model.getColumnCount(); i++){
output.write(model.getColumnName(i) + "\t");
}
output.write("\n");
for(int k=0;k<model.getRowCount();k++) {
for(int j=0;j<model.getColumnCount();j++) {
output.write(model.getValueAt(k,j).toString()+"\t");
}
output.write("\n");
output.close();
}
}
catch(Exception e) {
e.printStackTrace();
}
![Run program] [1]: http://i.stack.imgur.com/T99L5.png
![Exported excel file][2]: http://i.stack.imgur.com/ZGy3Z.png
Check your bracketing :P
You call output.close() inside the first for-loop for printing out data. This closes the file before getting to the 2nd row and onwards.
Forgive for I am new to Android and a novice at Java. I am trying to create a dynamic list view using data from a MySQL server. However, sometimes a query returns only one result. When my adapter class parses a JSONArray with one element to a String array, I receive an ArrayIndexOutOfBoundsException. How do I avoid using an empty string in my resultArray to compensate for the exception? I don't want to use the empty string because it will still be selectable within the listview.
Parsing code:
try
{
jArray = new JSONArray(result);
// Taking a peek at the contents
Log.e("log_tag", jArray.getJSONObject(0).getString(queryID));
//For some reason if I don't do this
// I get ArrayIndexOutOfBoundsException.
if (jArray.length() == 1)
{
resultArray = new String[2];
resultArray[1] = "";
}
else
resultArray = new String[jArray.length()];
for(int i = 0; i < jArray.length(); i++)
{
resultArray[i] = jArray.getJSONObject(i).getString(queryID);
}
}
catch(JSONException e)
{
throw new NullResultFromServerException("No results from server.");
}
for(int i = 0; i < jArray.length(); i++)
{
String empty= jArray.getJSONObject(i).getString(queryID);
empty=empty.trim(); //this will remove the blank white space
if(!empty.equalsIgnoreCase(""))
resultArray[i] = empty;
}