This is my code which I am using but when I am trying to print dataArray object, then data is not show in JTable. Which model properties of table to print Object array values can used and how?
public class ShowAddressForm extends javax.swing.JFrame {
Object data[][];
Object dataArray[][];
int count = 0;
String st;
public ShowAddressForm(String fname , String str) {
super(fname);
st = str;
initComponents();
fillTable();
}
public void fillTable()
{
int count = 0;
String str;
try
{
BufferedReader br = new BufferedReader(new FileReader("D:\\JavaPrograms\\Contact Management System\\InputFiles\\AddressFile"));
while((str = br.readLine()) != null)
{
count++;
}
br.close();
} catch (Exception e)
{
}
Object id;
Object name;
data = new Object[count][7];
int i = 0 , j = 0 , m;
try
{
BufferedReader buffrea = new BufferedReader(new FileReader("D:\\JavaPrograms\\Contact Management System\\InputFiles\\AddressFile"));
while((str = buffrea.readLine()) != null)
{
StringTokenizer token = new StringTokenizer(str , "*");
int n = token.countTokens();
id = token.nextElement();
name = token.nextElement();
String strNameLow = name.toString().toLowerCase();
String strNameUpp = name.toString().toUpperCase();
if(strNameLow.startsWith(st.toLowerCase()) || strNameUpp.startsWith(st.toUpperCase()))
{
data[i][0] = id;
data[i][1] = name;
for(j = 2 ; j < n ; j++)
{
data[i][j] = token.nextElement();
}
i = i + 1;
}
}
buffrea.close();
} catch(IOException ioe){
System.out.println("Error : " + ioe.toString());
}
dataArray = new Object[i][7];
for(int a = 0 ; a < i ; a++)
{
for(int b = 0 ; b < 7 ; b++)
{
dataArray[a][b] = data[a][b];
}
}
//Here is the code to print dataArray object which i used but it is not working, when i am run my program it is print "[Ljava.lang.Object;#1cc2e30" in table's first cell[0][0] position
DefaultTableModel model = (DefaultTableModel)this.data_table.getModel();
model.addRow(dataArray);
}
I filled data in a JTable like this. You might want to give it a try adapting it to your code. Variable and stuff are in spanish, just replace them with what you need. In my case it's a table with 4 columns representing a date, a score, duration and max viewers.
private void fillJTable(){
//creating data to add into the JTable. Here you might want to import your proper data from elsewhere
Date date = new Date();
UserReplay rep1 = new UserReplay(date, 12, 13,14);
UserReplay rep2 = new UserReplay(date, 2,34,5);
ArrayList<UserReplay> usuaris = new ArrayList<>();
usuaris.add(rep1);
usuaris.add(rep2);
//----Filling Jtable------
DefaultTableModel model = (DefaultTableModel) view.getTable().getModel();
model.addColumn("Fecha");
model.addColumn("Puntuación");
model.addColumn("Tiempo de duración");
model.addColumn("Pico máximo de espectadores");
for (int i = 0; i < usuaris.size(); i++){
Vector<Date> fecha = new Vector<>(Arrays.asList(usuaris.get(i).getDate()));
Vector<Integer> puntuacion = new Vector<>(Arrays.asList(usuaris.get(i).getPuntuacion()));
Vector<Integer> tiempo = new Vector<>(Arrays.asList(usuaris.get(i).getTiempo()));
Vector<Integer> espectadors = new Vector<>(Arrays.asList(usuaris.get(i).getTiempo()));
Vector<Object> row = new Vector<Object>();
row.addElement(fecha.get(0));
row.addElement(puntuacion.get(0));
row.addElement(tiempo.get(0));
row.addElement(espectadors.get(0));
model.addRow(row);
}
}
Here are for loopand for (Element link : links)loopings .
I want to store every elements title to line[]
What should I do ?
String[] line = new String[100];
for (int i = 0; i < numberOfResultpages; i++) {
......
for (Element link : links) {
String title = link.text();
String url = link.absUrl("href");
url = URLDecoder.decode(url.substring(url.indexOf('=') + 1, url.indexOf('&')), "UTF-8");
if (!url.startsWith("http")) {
continue; //
}
System.out.println("Title: " + title);
line[ numberOfResultpages ]=title; //I don't know how to store every title element into line here
// }
}
}
Update
numberOfResultpages is not the maximum size of the array
a numberOfResultpages can have many elementtitle
String[] line = new String[numberOfResultpages * links.size()]; // assign adequate size to line array.
int idx = 0;
for (int i = 0; i < numberOfResultpages; i++) {
...
for (Element link : links) {
...
line[idx++]=title;
Try By using ArrayList:
List<Strng> list=new ArrayLst<String>();
for (int i = 0; i < numberOfResultpages; i++) {
.........
//Every thing same
//add like this, ArrayList is Dynamic in Size
list.add(title);
} }
I am trying to paginate rows of a table inside my servlet using hibernate.But once I click on the desire index of the page it always gives me only the first set of row of the table.
My servlet code:
int pageIndex = 0;
int totalNumberOfRecords = 0;
int numberOfRecordsPerPage = 5;
String sPageIndex = request.getParameter("pageIndex");
if (sPageIndex == null) {
pageIndex = 1;
} else {
pageIndex = Integer.parseInt(sPageIndex);
}
int s = (pageIndex * numberOfRecordsPerPage) - numberOfRecordsPerPage;
List<ProductHasSize> phs = ses.createCriteria(ProductHasSize.class)
.setFirstResult(s)
.setMaxResults(numberOfRecordsPerPage)
.list();
for (ProductHasSize pro : phs) {... some html content here...}
List<ProductHasSize> phs1 = ses.createCriteria(ProductHasSize.class)
.setProjection(Projections.rowCount()).list();
Iterator i = phs1.iterator();
if (i.hasNext()) {
Object o = i.next();
totalNumberOfRecords = Integer.parseInt(o.toString());
}
int noOfPages = totalNumberOfRecords / numberOfRecordsPerPage;
if (totalNumberOfRecords > (noOfPages * numberOfRecordsPerPage)) {
noOfPages = noOfPages + 1;
}
for (int j = 1; j <= noOfPages; j++) {
String myurl = "products.jsp?pageIndex=" + j;
String active = j == pageIndex ? "active" : "";
pagination = pagination + "<li class='" + active + "'>" + j + "</li>";
}
Thanks in advance.
Try to replace:
if (i.hasNext()) {
With:
while(i.hasNext()) {
And write the while loop like this:
while(i.hasNext()) {
Object o = i.next();
totalNumberOfRecords += Integer.parseInt(o.toString());
int noOfPages = totalNumberOfRecords / numberOfRecordsPerPage;
if (totalNumberOfRecords > (noOfPages * numberOfRecordsPerPage)) {
noOfPages = noOfPages + 1;
}
}
I have a JSP page that runs a database query and serializes the results to JSON. The object that I am serializing is this:
class DataObject {
private int iTotalRecords;
private int iTotalDisplayRecords;
private String sEcho;
private ArrayList<String> columns;
private ArrayList<ArrayList<String>> data;
//getter and setter methods
public void setColumns( ArrayList<String> cols ) {
columns = cols;
}
public void setTotalDisplayRecords( int _numrecs ) {
iTotalDisplayRecords = _numrecs;
}
public void setTotalRecords( int _numrecs ) {
iTotalRecords = _numrecs;
}
public void setData( ArrayList<ArrayList<String>> _data ) {
data = _data;
}
public void setEcho( String _echo ) {
sEcho = _echo;
}
#Override
public String toString() {
return "DataObject [iTotalRecords=" + iTotalRecords +
", iTotalDisplayRecords=" + iTotalDisplayRecords +
", sEcho=" + sEcho +
", columns=" + columns +
", data=" + data + "]";
}
public DataObject() {
this.sEcho = "1";
this.iTotalDisplayRecords = 0;
this.iTotalRecords = 0;
this.columns = new ArrayList<String>();
this.data = new ArrayList<ArrayList<String>>();
}
}
I have simplified the page, the JSP (which still produces blank JSON) is shown below:
String queryOvr = "select 'error' as Input_Parameters";
String sEcho = "0";
LOG.error("db_json_test.jsp - QUERY: " + queryOvr);
int rowCount=0;
int totalCount=0;
Statement stmt = null;
ResultSet returnData = null;
Connection conn = null;
try {
conn = DatabaseUtilities.getConnection(); //proprietary connection pool of host application
stmt = conn.createStatement();
returnData = stmt.executeQuery(queryOvr);
ResultSetMetaData rsmd = returnData.getMetaData();
DataObject dObj = new DataObject();
ArrayList<String> headerRow = new ArrayList<String>();
int colCount = rsmd.getColumnCount();
// write column names
for (int i=0; i<colCount; i++) {
String headerName = rsmd.getColumnName(i+1);
if ("".equals(headerName)) {
headerName = "Column-" + String.valueOf(i+1);
}
LOG.error("db_json_test.jsp - HEADER: " + headerName);
headerRow.add(headerName);
}
dObj.setColumns(headerRow);
// write data
ArrayList<ArrayList<String>> dataArray = new ArrayList<ArrayList<String>>();
while ( returnData.next() ) {
rowCount++;
ArrayList<String> dataRow = new ArrayList<String>();
for (int i=0; i<colCount; i++){
String dbData = returnData.getString(i+1);
LOG.error("db_json_test.jsp - DATA: row: " + headerRow.get(i) + ", value: " + dbData);
dataRow.add(dbData);
}
dataArray.add(dataRow);
totalCount++;
}
dObj.setData(dataArray);
dObj.setEcho(sEcho);
dObj.setTotalRecords(totalCount);
dObj.setTotalDisplayRecords(rowCount);
LOG.error("db_json_test.jsp - OBJ: " + dObj.toString());
Type typeResults = new TypeToken<DataObject>(){}.getType();
Gson gson = new Gson();
String json = gson.toJson(dObj, typeResults);
LOG.error("db_json_test.jsp - JSON: " + json);
//gson.toJson(dObj, typeResults, response.getWriter());
response.setStatus(HttpServletResponse.SC_OK);
response.getWriter().write(json);
response.getWriter().flush();
response.getWriter().close();
}
catch (Throwable t) {
LOG.error("db_json.jsp - Error: " + t.toString());
//t.printStackTrace();
response.setStatus(HttpServletResponse.SC_OK);
response.getWriter().write("{\"error\":\"" + t.toString() + "\"}");
response.getWriter().flush();
response.getWriter().close();
}
When I look in the logs I can see that the DataObject instance is getting properly populated:
783167943 30 Sep 2015 17:37:51,924 ERROR [http-8500-1] JSP - db_json_test.jsp - QUERY: select 'error' as Input_Parameters
783167959 30 Sep 2015 17:37:51,940 ERROR [http-8500-1] JSP - db_json_test.jsp - HEADER: Input_Parameters
783167959 30 Sep 2015 17:37:51,940 ERROR [http-8500-1] JSP - db_json_test.jsp - DATA: row: Input_Parameters, value: error
783167959 30 Sep 2015 17:37:51,940 ERROR [http-8500-1] JSP - db_json_test.jsp - OBJ: DataObject [iTotalRecords=1, iTotalDisplayRecords=1, sEcho=0, columns=[Input_Parameters], data=[[error]]]
783167959 30 Sep 2015 17:37:51,940 ERROR [http-8500-1] JSP - db_json_test.jsp - JSON:
However when I go to serialize it using gson.toJson(dObj) I get a blank string. I have tried specifying the type as shown in the example above to no different results. Outside of the argument that I probably shouldn't be doing this in a JSP file, what am I missing here?
Worth noting is that the catch routine does return the error message as valid JSON, so the contentType and charset are getting properly set in the headers.
The following Java code DOES produce the expected JSON...
public class gsonTest {
class DataObject {
private int iTotalRecords;
private int iTotalDisplayRecords;
private String sEcho;
private ArrayList<String> columns;
private ArrayList<ArrayList<String>> data;
// getter and setter methods
public void setColumns(ArrayList<String> cols) {
columns = cols;
}
public void setTotalDisplayRecords(int _numrecs) {
iTotalDisplayRecords = _numrecs;
}
public void setTotalRecords(int _numrecs) {
iTotalRecords = _numrecs;
}
public void setData(ArrayList<ArrayList<String>> _data) {
data = _data;
}
public void setEcho(String _echo) {
sEcho = _echo;
}
#Override
public String toString() {
return "DataObject [iTotalRecords=" + iTotalRecords
+ ", iTotalDisplayRecords=" + iTotalDisplayRecords
+ ", sEcho=" + sEcho
+ ", columns=" + columns
+ ", data=" + data + "]";
}
public DataObject() {
this.sEcho = "";
this.iTotalDisplayRecords = 0;
this.iTotalRecords = 0;
this.columns = new ArrayList<String>();
this.data = new ArrayList<ArrayList<String>>();
}
}
public static void main(String[] args) {
int totalCount = 0;
String sEcho = "1";
Gson gson = new Gson();
gsonTest tst = new gsonTest();
Type typeResults = new TypeToken<DataObject>(){}.getType();
DataObject obj = tst.new DataObject();
ArrayList<String> headerRow = new ArrayList<String>();
// write column names
int colCount = 2;
for (int i = 0; i < colCount; i++) {
headerRow.add("Column-" + String.valueOf(i));
}
obj.setColumns(headerRow);
// write data
ArrayList<ArrayList<String>> dataArray = new ArrayList<ArrayList<String>>();
int rowCount = 0;
while (rowCount < 20) {
ArrayList<String> dataRow = new ArrayList<String>();
for (int i = 0; i < colCount; i++) {
dataRow.add("Row-" + String.valueOf(rowCount) + ":Col-"
+ String.valueOf(i));
}
rowCount++;
dataArray.add(dataRow);
totalCount++;
}
obj.setData(dataArray);
obj.setEcho(sEcho);
obj.setTotalRecords(totalCount);
obj.setTotalDisplayRecords(rowCount);
String output = gson.toJson(obj,typeResults);
System.out.println(obj.toString());
System.out.println(output);
}
}
Here is the output:
DataObject [iTotalRecords=20, iTotalDisplayRecords=20, sEcho=1,
columns=[Column-0, Column-1], data=[[Row-0:Col-0, Row-0:Col-1],
[Row-1:Col-0, Row-1:Col-1], [Row-2:Col-0, Row-2:Col-1], [Row-3:Col-0,
Row-3:Col-1], [Row-4:Col-0, Row-4:Col-1], [Row-5:Col-0, Row-5:Col-1],
[Row-6:Col-0, Row-6:Col-1], [Row-7:Col-0, Row-7:Col-1], [Row-8:Col-0,
Row-8:Col-1], [Row-9:Col-0, Row-9:Col-1], [Row-10:Col-0,
Row-10:Col-1], [Row-11:Col-0, Row-11:Col-1], [Row-12:Col-0,
Row-12:Col-1], [Row-13:Col-0, Row-13:Col-1], [Row-14:Col-0,
Row-14:Col-1], [Row-15:Col-0, Row-15:Col-1], [Row-16:Col-0,
Row-16:Col-1], [Row-17:Col-0, Row-17:Col-1], [Row-18:Col-0,
Row-18:Col-1], [Row-19:Col-0, Row-19:Col-1]]]
{"iTotalRecords":20,"iTotalDisplayRecords":20,"sEcho":"1","columns":["Column-0","Column-1"],"data":[["Row-0:Col-0","Row-0:Col-1"],["Row-1:Col-0","Row-1:Col-1"],["Row-2:Col-0","Row-2:Col-1"],["Row-3:Col-0","Row-3:Col-1"],["Row-4:Col-0","Row-4:Col-1"],["Row-5:Col-0","Row-5:Col-1"],["Row-6:Col-0","Row-6:Col-1"],["Row-7:Col-0","Row-7:Col-1"],["Row-8:Col-0","Row-8:Col-1"],["Row-9:Col-0","Row-9:Col-1"],["Row-10:Col-0","Row-10:Col-1"],["Row-11:Col-0","Row-11:Col-1"],["Row-12:Col-0","Row-12:Col-1"],["Row-13:Col-0","Row-13:Col-1"],["Row-14:Col-0","Row-14:Col-1"],["Row-15:Col-0","Row-15:Col-1"],["Row-16:Col-0","Row-16:Col-1"],["Row-17:Col-0","Row-17:Col-1"],["Row-18:Col-0","Row-18:Col-1"],["Row-19:Col-0","Row-19:Col-1"]]}
After digging further I came to a workable solution. By combining the test Java class into the JSP as follows I got the correct output. I am unsure why this worked and the original did not
<%# page
language="java"
session="true"
contentType="application/json; charset=UTF-8"
%>
<%# page import="com.google.gson.Gson,
java.lang.reflect.Type,
com.google.gson.reflect.TypeToken,
java.util.ArrayList,
java.sql.*,
org.apache.log4j.Category,
com.foo.bar.*;"
%>
<%
final org.apache.log4j.Category LOG = org.apache.log4j.Category.getInstance ("JSP");
class db_json {
class DataObject {
private int iTotalRecords;
private int iTotalDisplayRecords;
private String sEcho;
private ArrayList<String> columns;
private ArrayList<ArrayList<String>> data;
// getter and setter methods
public void setColumns(ArrayList<String> cols) {
columns = cols;
}
public void setTotalDisplayRecords(int _numrecs) {
iTotalDisplayRecords = _numrecs;
}
public void setTotalRecords(int _numrecs) {
iTotalRecords = _numrecs;
}
public void setData(ArrayList<ArrayList<String>> _data) {
data = _data;
}
public void setEcho(String _echo) {
sEcho = _echo;
}
#Override
public String toString() {
return "DataObject [iTotalRecords=" + iTotalRecords
+ ", iTotalDisplayRecords=" + iTotalDisplayRecords
+ ", sEcho=" + sEcho
+ ", columns=" + columns
+ ", data=" + data + "]";
}
public DataObject() {
this.sEcho = "";
this.iTotalDisplayRecords = 0;
this.iTotalRecords = 0;
this.columns = new ArrayList<String>();
this.data = new ArrayList<ArrayList<String>>();
}
}
public String testJson(HttpServletRequest request){
String queryOvr = "select 'error' as Input_Parameters";
LOG.debug("db_json3.jsp - QUERY: " + queryOvr);
Gson gson = new Gson();
int rowCount=0;
int totalCount=0;
Statement stmt = null;
ResultSet returnData = null;
Connection conn = null;
try {
conn = DatabaseUtilities.getConnection();
stmt = conn.createStatement();
returnData = stmt.executeQuery(queryOvr);
ResultSetMetaData rsmd = returnData.getMetaData();
DataObject dObj = new DataObject();
ArrayList<String> headerRow = new ArrayList<String>();
int colCount = rsmd.getColumnCount();
// write column names
for (int i=0; i<colCount; i++) {
String headerName = rsmd.getColumnName(i+1);
if ("".equals(headerName)) {
headerName = "Column-" + String.valueOf(i+1);
}
LOG.debug("db_json3.jsp - HEADER: " + headerName);
headerRow.add(headerName);
}
dObj.setColumns(headerRow);
// write data
ArrayList<ArrayList<String>> dataArray = new ArrayList<ArrayList<String>>();
while ( returnData.next() ) {
if ( rowCount>=iDisplayStart && iDisplayLength>=0 && rowCount<iDisplayLength ) {
rowCount++;
ArrayList<String> dataRow = new ArrayList<String>();
for (int i=0; i<colCount; i++){
String dbData = returnData.getString(i+1);
LOG.debug("db_json3.jsp - DATA: row: " + headerRow.get(i) + ", value: " + dbData);
dataRow.add(dbData);
}
dataArray.add(dataRow);
}
totalCount++;
}
dObj.setData(dataArray);
dObj.setEcho(sEcho);
dObj.setTotalRecords(totalCount);
dObj.setTotalDisplayRecords(rowCount);
LOG.debug("db_json3.jsp - OBJ: " + dObj.toString());
Type typeResults = new TypeToken<DataObject>(){}.getType();
String json = gson.toJson(dObj, typeResults);
LOG.debug("db_json3.jsp - JSON: " + json);
return json;
}
catch (Throwable t) {
LOG.debug("db_json3.jsp - Error: " + t.toString());
return gson.toJson(t);
}
}
}
db_json dbjson = new db_json();
String json = dbjson.testJson();
response.setStatus(HttpServletResponse.SC_OK);
response.getWriter().write(json);
response.getWriter().flush();
response.getWriter().close();
%>
I have an ArrayList as shown below
import java.util.ArrayList;
public class Mann {
public static void main(String args[]) {
ArrayList<String> billOrderList = new ArrayList<String>();
list.add("VAT");
list.add("Discount");
list.add("SERVICE CHARGE");
StringBuilder select_query = new StringBuilder();
select_query.append("Select ");
for (int i = 0; i < billOrderList.size(); i++) {
if (i != billOrderList.size() - 1) {
select_query.append("" + billOrderList.get(i) + " , ");
} else {
select_query.append("" + billOrderList.get(i) + "");
}
}
select_query.append(" From VENDOR_ITEMS WHERE vendor_items_id = "
+ vendor_item + "");
VendorItems_Pstmt = dbConnection.prepareStatement(select_query
.toString());
VendorItems_RSet = VendorItems_Pstmt.executeQuery();
while (VendorItems_RSet.next()) {
String tax_name = VendorItems_RSet.getString();
}
}
}
How can i give the column name which is dynamic in this case in line VendorItems_RSet.getString();??
You need as ResultSetMetaData to get the column name associated with your query result.
You can get ResultSetMetaData from ResultSet by using ResultSet.getMetaDate, you can iterate it and get column all column name.
ResultSetMetaData VendorItems_RSet_metaData = VendorItems_RSet.getMetaData();
int numberOfColumns = VendorItems_RSet_metaData .getColumnCount();
for(int i=1;i<=numberOfColumns;i++)
{
String columnName = VendorItems_RSet_metaData.getColumnName(i);
}
I think you need all column data for that you can iterate your loop like
while (VendorItems_RSet.next())
{
for(int i=1;i<=numberOfColumns;i++)
{
String columnName = VendorItems_RSet_metaData.getColumnName(i);
String tax_name = VendorItems_RSet.getString(columnName);
System.out.println(tax_name);
}
}
ResultSetMetaData resultSetMetaData = VendorItems_RSet.getMetaData();
for (int i = 1; i <= resultSetMetaData.getColumnCount(); i++) {
String type = resultSetMetaData.getColumnTypeName(i); // Get Column type
String name= resultSetMetaData.getColumnName(i); //Column name
}
}
SELECT * and then
ResultSetMetaData metaData = VendorItems_RSet.getMetaData();
int columns = metaData.getColumnCount();
for (int i = 1; i <= columns; ++i) {
System.out.println(metaData.getColumnName(1));
}