The Google Analytics API does not find PagePath - java

I am trying to report google analytics data to a database using JAVA, but certain addresses are returning null even if the URL exists.
Example: / catalog / companyX / US / en ----- it finds.
/catalog/companyX/US/en/research ------ he can't find it.
I tried using the filter "ga: pagePath=#/research" and it always returns null. What will be the problem? Because on google analytics site he finds these URLs.
public GetReportsResponse getReport(AnalyticsReporting service) throws IOException {
// Create the DateRange object.
DateRange dateRange = new DateRange();
dateRange.setStartDate("2019-10-06");
dateRange.setEndDate("2019-10-06");
// Create the Metrics object.
Metric timeOnPage = new Metric().setExpression("ga:timeOnPage");
Metric totalEvents = new Metric().setExpression("ga:totalEvents");
Metric avgSessionDuration = new Metric().setExpression("ga:avgSessionDuration");
Metric hits = new Metric().setExpression("ga:hits");
// Create the Dimensions object.
Dimension browser = new Dimension().setName("ga:browser");
Dimension device = new Dimension().setName("ga:deviceCategory");
Dimension country = new Dimension().setName("ga:country");
Dimension page = new Dimension().setName("ga:pagePath");
Dimension eventCategory = new Dimension().setName("ga:eventCategory");
Dimension eventAction = new Dimension().setName("ga:eventAction");
Dimension eventLabel = new Dimension().setName("ga:eventLabel");
Dimension date = new Dimension().setName("ga:date");
Dimension pageTitle = new Dimension().setName("ga:pageTitle");
ReportRequest request6 = new ReportRequest().setViewId(VIEW_ID).setDateRanges(Arrays.asList(dateRange))
.setPageSize(100000)
.setMetrics(Arrays.asList(totalEvents, hits, avgSessionDuration, timeOnPage))
.setDimensions(Arrays.asList(date, country, page, browser, device, eventCategory, eventAction,
eventLabel, pageTitle));
ArrayList<ReportRequest> requests = new ArrayList<ReportRequest>();
requests.add(request6);
// Create the GetReportsRequest object.
GetReportsRequest getReport = new GetReportsRequest().setReportRequests(requests);
// Call the batchGet method.
GetReportsResponse response = service.reports().batchGet(getReport).execute();
// Return the response.
return response;
}
public void printResponse(GetReportsResponse response) {
for (Report report : response.getReports()) {
ColumnHeader header = report.getColumnHeader();
List<String> dimensionHeaders = header.getDimensions();
List<MetricHeaderEntry> metricHeaders = header.getMetricHeader().getMetricHeaderEntries();
List<ReportRow> rows = report.getData().getRows();
if (rows == null) {
System.out.println("No data found for " + VIEW_ID);
return;
}
for (ReportRow row : rows) {
TableGA tableGA = new TableGA();
Acessos acessos = new Acessos();
List<String> dimensions = row.getDimensions();
List<DateRangeValues> metrics = row.getMetrics();
if (row.getDimensions() != null) {
for (int i = 0; i < dimensionHeaders.size() && i < dimensions.size(); i++) {
switch (dimensionHeaders.get(i)) {
case "ga:browser":
tableGA.setBrowser(dimensions.get(i));
break;
case "ga:deviceCategory":
tableGA.setDevice(dimensions.get(i));
break;
case "ga:country":
tableGA.setCountry(dimensions.get(i));
break;
case "ga:pagePath":
tableGA.setPage(dimensions.get(i));
break;
case "ga:eventCategory":
tableGA.setEventCategory(dimensions.get(i));
break;
case "ga:eventAction":
tableGA.setEventAction(dimensions.get(i));
break;
case "ga:eventLabel":
tableGA.setEventLabel(dimensions.get(i));
break;
case "ga:date":
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date convertedCurrentDate = null;
String year = dimensions.get(i).substring(0, 4);
String month = dimensions.get(i).substring(4, 6);
String day = dimensions.get(i).substring(6, 8);
String date = year + "-" + month + "-" + day;
try {
convertedCurrentDate = simpleDateFormat.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
tableGA.setActualDate(convertedCurrentDate);
break;
case "ga:pageTitle":
tableGA.setPageTitle(dimensions.get(i));
break;
}
}
}
for (int j = 0; j < metrics.size(); j++) {
DateRangeValues values = metrics.get(j);
for (int k = 0; k < values.getValues().size() && k < metricHeaders.size(); k++) {
switch (metricHeaders.get(k).getName()) {
case "ga:timeOnPage":
tableGA.setTimeOnPage(Double.parseDouble(values.getValues().get(k)));
break;
case "ga:totalEvents":
tableGA.setTotalEvents(Integer.parseInt(values.getValues().get(k)));
break;
case "ga:avgSessionDuration":
tableGA.setAvgSessionDuration(Double.parseDouble(values.getValues().get(k)));
break;
case "ga:hits":
tableGA.setHits(Integer.parseInt(values.getValues().get(k)));
break;
}
}
}
gaService.save(tableGA);
System.out.println(tableGA.getPage());
gaService.save(acessos);
}
}
}

Related

One Row in One Page: Boxable

This is the code for this issue for you to check if there is any problem in the code.
Now the problem is when I limit the rows to 45 (this number fits in one page) every row will print in one page.
But, If I don't limit the rows and the row size (approximately 100-200), every row goes to new page in the PDF. The PDF page number goes to approximately equal to row numbers.
I have opened this issue in Boxable's git but it's not active so I came for help here.
Following are the files generated in both conditions:
LimitTemp.pdf
noLimitTemp.pdf
public class CSVtoPDF {
private float marginBetweenYElements = 10;
private float titleFontSize = 18;
private float fontSize = 8;
private float headerFontSize = 12;
private float header1FontSize = 14;
private float header2FontSize = 12;
private float headerCellHeight = 19;
private float dataCellHeight = 12;
private PDFont font = PDType1Font.HELVETICA;
private PDFont headerFont = PDType1Font.TIMES_BOLD;
List filteredData = new ArrayList();
ReportSettings rs = new ReportSettings();
String filePath, destPath, header1, header2, filename;
public CSVtoPDF(List data, Audit audit) throws IOException {
this.filteredData = data;
Date liveDate = new Date();
SimpleDateFormat format= new SimpleDateFormat("YYYY-MM-DD HH:mm:ss");
liveDate = Calendar.getInstance().getTime();
float headerCellHeight = 18;
PDDocument doc = new PDDocument();
PDPage page = new PDPage(PDRectangle.A4);
//page.setMediaBox(new PDRectangle(PDRectangle.A4.getHeight(),
// PDRectangle.A4.getWidth()));
PDPageContentStream cos = new PDPageContentStream(doc, page);
/* Add page to PDDocument */
doc.addPage(page);
System.out.println("Inside Main csvtopdf");
//Draw Header
Preferences prefs = Preferences.userRoot().node(this.getClass().getName());
try {
String[] keys = prefs.keys();
//destPath = prefs.get("destpath", rs.getDestPath());
//filename = prefs.get("file_name", rs.getFileName());
//header1 = prefs.get("header1", rs.getHeader1());
//header2 = prefs.get("header2", rs.getHeader2());
} catch (BackingStoreException ex) {
System.err.println(ex);
}
header1= "Header 1";
header2= "Header 2";
cos.beginText();
cos.moveTextPositionByAmount(220, 810);
cos.setFont(headerFont, header1FontSize);
cos.drawString(header1);
cos.endText();
cos.beginText();
cos.moveTextPositionByAmount(220, 800);
cos.setFont(headerFont, header2FontSize);
cos.drawString(header2);
cos.endText();
cos.beginText();
cos.moveTextPositionByAmount(220, 790);
cos.setFont(headerFont, headerFontSize);
cos.drawString("Report: Filtered Audit Report");
cos.endText();
//cos.beginText();
// cos.moveTo(200, 30);
//cos.setFont(headerFont, headerFontSize);
// cos.drawString(header2);
//cos.endText();
/* Initialize DataTable */
float margin = 20;
float tableWidth = page.getMediaBox().getWidth() - (2 * margin);
float yStartNewPage = page.getMediaBox().getHeight() - (2 * margin);
float yStart = yStartNewPage;
float bottomMargin = -800;
BaseTable table = new BaseTable(yStart, yStartNewPage,
bottomMargin, tableWidth, margin, doc, page, true, true);
Row<PDPage> dataRow = table.createRow(dataCellHeight);
for (int i = 0; i < data.size() - 1; i++) {
System.out.println(data.get(i));
}
drawTableData(table, dataCellHeight, 20, data, 1,doc,page);
table.draw();
File result;
if (Objects.isNull(destPath)) {
cos.close();
result = new File("temp.pdf");
} else {
result = new File(destPath);
}
System.out.println("befor save result");
doc.save(result);
System.out.println("after save result");
}
public void drawTableData(BaseTable table, float dataCellHeight, float
cellWidth, List<Audit> data, int style,PDDocument doc,PDPage page) {
String s;
Cell<PDPage> cell;
// for (int k = 0; k < data.size(); k++) {
System.out.println("inside drawtable for ");
for (int i = 0; i < data.size(); i++) { // add row
System.out.println("inside drawtable for " + i);
Audit atmp = data.get(i);
//if (i==35) {
// doc.addPage(page);
//}
Row<PDPage> sTableRow = table.createRow(dataCellHeight);
for (int j = 0; j <= 2; j++) { //add cell in the rows
if (j == 0) { // normal cells on right
s = atmp.getTimeStamp();
s = s.replaceAll("^\"|\"$", "");
cell = sTableRow.createCell(cellWidth, s, HorizontalAlignment.CENTER, VerticalAlignment.BOTTOM);
setStyle(style, cell);
//k++;
} else if (j == 1) { //big cells on left
s = atmp.getDiscription();
s = s.replaceAll("^\"|\"$", "");
cell = sTableRow.createCell(cellWidth + 50, s, HorizontalAlignment.CENTER, VerticalAlignment.BOTTOM);
setStyle(style, cell);
// k++;
} else if (j == 2) { //top blank cell
//System.out.println("In j null and 0 " + j);
s = atmp.getUserID();
s = s.replaceAll("^\"|\"$", "");
cell = sTableRow.createCell(cellWidth - 10, s, HorizontalAlignment.CENTER, VerticalAlignment.BOTTOM);
//cell.setBottomBorderStyle(null);
setStyle(style, cell);
//k++;
}
}
table.addHeaderRow(sTableRow);
System.out.println(" row added ");
}
//}
}
public void setStyle(int type, Cell cell) {
// type : 0 as header, 1 as table body
if (type == 0) {
cell.setFont(headerFont);
//cell.setHeight(headerCellHeight);
cell.setFontSize(headerFontSize);
cell.setBottomPadding(3);
} else if (type == 1) {
cell.setTopPadding(1);
cell.setFont(font);
cell.setAlign(HorizontalAlignment.LEFT);
//cell.setHeight(dataCellHeight);
cell.setFontSize(fontSize);
cell.setBottomPadding(1);
}
}
I found a silly problem in my code. I am telling this so that someone else must not repeat this.
I treated every row of the data table as header row. So it went to new page.
To be specific. In the function drawTableData I removed table.addHeaderRow(sTableRow)

How to display Object array in JTable?

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);
}
}

JScrollPane not working horizontally

Hi. I need some help. JScrollPane working vertically good but horizontally not. And I cant find whats the problem. I know that its a little big project and there is a lot of confusing codes but I cant delete any of that function.
public final class Salary extends javax.swing.JFrame {
private SalaryTableModel tableModel;
public int selectedRow = -1;
public static String bolme;
public static String ay;
public static int il = 0;
private final String selectedItem_Bolme;
private final String selectedItem_Ay;
private final int selectedItem_Il;
private List<Pojo> sortedList;
public TableColumn date;
public static int bolmeId = 0;
public static String ad;
public static int row2;
public void visible(String bolme2, String ay2, int il2) {
il = il2;
ay = ay2;
bolme = bolme2;
new Salary().setVisible(true);
}
public RXTable autoResizeColWidth(RXTable table, SalaryTableModel model) {
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
table.setModel(model);
int margin = 5;
for (int i = 0; i < table.getColumnCount(); i++) {
int vColIndex = i;
DefaultTableColumnModel colModel = (DefaultTableColumnModel) table.getColumnModel();
TableColumn col = colModel.getColumn(vColIndex);
int width;
TableCellRenderer renderer = col.getHeaderRenderer();
if (renderer == null) {
renderer = table.getTableHeader().getDefaultRenderer();
}
Component comp = renderer.getTableCellRendererComponent(table, col.getHeaderValue(), false, false, 0, 0);
width = comp.getPreferredSize().width;
for (int r = 0; r < table.getRowCount(); r++) {
renderer = table.getCellRenderer(r, vColIndex);
comp = renderer.getTableCellRendererComponent(table, table.getValueAt(r, vColIndex), false, false,
r, vColIndex);
width = Math.max(width, comp.getPreferredSize().width);
}
width += 2 * margin;
col.setPreferredWidth(width);
}
((DefaultTableCellRenderer) table.getTableHeader().getDefaultRenderer()).setHorizontalAlignment(
SwingConstants.LEFT);
table.getTableHeader().setReorderingAllowed(false);
return table;
}
public Salary() {
initComponents();
Toolkit.getDefaultToolkit().getImage(getClass().getResource("/images/db.png"));
setDefaultCloseOperation(EXIT_ON_CLOSE);
List<Pojo> model = DBO.findBolme();
HashSet hs = new HashSet();
ArrayList al = new ArrayList();
model.stream().forEach((model1) -> {
hs.add(model1.getBolme());
});
al.addAll(hs);
comboBolme.addItem("Butun Bolmeler");
al.stream().forEach((al1) -> {
comboBolme.addItem(al1);
bolmeId++;
});
comboBolme.removeItem("null");
if (bolme == null) {
comboBolme.setSelectedIndex(0);
} else {
comboBolme.setSelectedItem(bolme);
}
if (ay == null) {
comboAy.setSelectedIndex(0);
} else {
comboAy.setSelectedItem(ay);
}
List<Pojo> model2 = DBO.findIl();
HashSet hs2 = new HashSet();
ArrayList al2 = new ArrayList();
model2.stream().forEach((model1) -> {
hs2.add(model1.getIl());
});
al2.addAll(hs2);
comboIl.addItem(0000);
al2.stream().forEach((al1) -> {
comboIl.addItem(al1);
});
comboIl.removeItem(0);
if (il == 0) {
comboIl.setSelectedIndex(0);
} else {
comboIl.setSelectedItem(il);
}
selectedItem_Bolme = (String) comboBolme.getSelectedItem();
selectedItem_Ay = (String) comboAy.getSelectedItem();
selectedItem_Il = Integer.parseInt(comboIl.getSelectedItem().toString());
Pojo tempVar;
sortedList = DBO.salary_Find(selectedItem_Bolme, selectedItem_Ay, selectedItem_Il);
for (int i = 0; i < sortedList.size(); i++) {
if (sortedList.get(i).getIsleyir() == 1) {
sortedList.remove(i);
i--;
}
}
for (int i = 0; i < sortedList.size(); i++) {
for (int j = 0; j < sortedList.size(); j++) {
if (sortedList.get(i).getCem() == sortedList.get(j).getCem()) {
}
if (sortedList.get(i).getCem() > sortedList.get(j).getCem()) {
tempVar = sortedList.get(j);
sortedList.set(j, sortedList.get(i));
sortedList.set(i, tempVar);
}
}
}
tableModel = new SalaryTableModel(sortedList) {
#Override
public boolean isCellEditable(int row, int column) {
ad = tableModel.getTopic(row).getAd();
selectedRow = tableModel.getTopic(row).getId();
row2 = row;
return (column != 0) && (column != 17);
}
};
table.setModel(tableModel);
table = autoResizeColWidth(table, tableModel);
table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM");
DatePickerCellEditor datePicker = new DatePickerCellEditor(formatter);
datePicker.setFormats(formatter);
date = table.getColumnModel().getColumn(18);
date.setCellEditor(datePicker);
table = new RXTable(tableModel);
JScrollPane pane = new JScrollPane(table);
add(pane);
table.setSelectAllForEdit(true);
table.getColumnModel().getColumn(0).setMinWidth(100);
table.getColumnModel().getColumn(1).setMinWidth(100);
table.getColumnModel().getColumn(2).setMinWidth(100);
table.getColumnModel().getColumn(3).setMinWidth(100);
table.getColumnModel().getColumn(4).setMinWidth(100);
table.getColumnModel().getColumn(5).setMinWidth(100);
table.getColumnModel().getColumn(6).setMinWidth(100);
table.getColumnModel().getColumn(7).setMinWidth(100);
table.getColumnModel().getColumn(8).setMinWidth(100);
table.getColumnModel().getColumn(9).setMinWidth(100);
table.getColumnModel().getColumn(10).setMinWidth(100);
table.getColumnModel().getColumn(11).setMinWidth(100);
table.getColumnModel().getColumn(12).setMinWidth(100);
table.getColumnModel().getColumn(13).setMinWidth(100);
table.getColumnModel().getColumn(14).setMinWidth(100);
table.getColumnModel().getColumn(15).setMinWidth(100);
table.getColumnModel().getColumn(16).setMinWidth(100);
table.getColumnModel().getColumn(17).setMinWidth(100);
table.getColumnModel().getColumn(18).setMinWidth(100);
table.getColumnModel().getColumn(19).setMinWidth(100);
table.getColumnModel().getColumn(20).setMinWidth(100);
table.getColumnModel().getColumn(21).setMinWidth(100);
table.getColumnModel().getColumn(21).setMaxWidth(10000);
setLocationRelativeTo(null);
double x = 0;
for (int i = 0; i < tableModel.getRowCount(); i++) {
x += tableModel.getTopic(i).getArtim();
}
lblArtiminCemi.setText(String.valueOf((x)));
double y = 0;
for (int i = 0; i < tableModel.getRowCount(); i++) {
y += tableModel.getTopic(i).getCem();
}
lblTotal.setText(String.valueOf((y)));
comboBolme.addActionListener((ActionEvent e) -> {
String selectedBolme = (String) comboBolme.getSelectedItem();
visible(selectedBolme, ay, il);
setVisible(false);
});
comboAy.addActionListener((ActionEvent e) -> {
String selectedAy = (String) comboAy.getSelectedItem();
visible(bolme, selectedAy, il);
setVisible(false);
});
comboIl.addActionListener((ActionEvent e) -> {
int selectedIl = Integer.parseInt(comboIl.getSelectedItem().toString());
visible(bolme, ay, selectedIl);
setVisible(false);
});
table.getModel().addTableModelListener((TableModelEvent e) -> {
int row = e.getFirstRow();
int column = e.getColumn();
TableModel model1 = (TableModel) e.getSource();
String columnName = model1.getColumnName(column);
Object value = model1.getValueAt(row, column);
Pojo temp;
sortedList = DBO.salary_Find(selectedItem_Bolme, selectedItem_Ay, selectedItem_Il);
for (int i = 0; i < sortedList.size(); i++) {
if (sortedList.get(i).getIsleyir() == 1) {
sortedList.remove(i);
i--;
}
}
for (int i = 0; i < sortedList.size(); i++) {
for (int j = 0; j < sortedList.size(); j++) {
if (sortedList.get(i).getCem() > sortedList.get(j).getCem()) {
temp = sortedList.get(j);
sortedList.set(j, sortedList.get(i));
sortedList.set(i, temp);
}
}
}
List<Pojo> list = sortedList;
Pojo data = list.get(row);
switch (column) {
case 0:
data.setId((int) value);
break;
case 1:
data.setAd((String) value);
break;
case 2:
data.setCins((int) value);
break;
case 3:
data.setBank((Double) value);
data.setCem(data.getBank() + data.getIlk_maas() + data.getSon_maas() + data.getArtim());
break;
case 4:
data.setIlk_maas((Double) value);
data.setCem(data.getBank() + data.getIlk_maas() + data.getSon_maas() + data.getArtim());
break;
case 5:
data.setSon_maas((Double) value);
data.setCem(data.getBank() + data.getIlk_maas() + data.getSon_maas() + data.getArtim());
break;
case 6:
data.setArtim((Double) value);
data.setCem(data.getBank() + data.getIlk_maas() + data.getSon_maas() + data.getArtim());
break;
case 7:
data.setCem((Double) value);
break;
case 8:
data.setElave_is((int) value);
break;
case 9:
data.setMukafatlandirma((Double) value);
break;
case 10:
data.setQayib_gunu((int) value);
break;
case 11:
data.setDetal_xetasi((Double) value);
break;
case 12:
data.setSatin_alma((Double) value);
break;
case 13:
data.setBolme(value.toString().toUpperCase());
break;
case 14:
data.setAy((String) value);
break;
case 15:
data.setIl((Integer) value);
break;
case 16:
data.setIsleyir((int) value);
break;
case 17:
data.setNe_qeder_isleyib((String) value);
break;
case 18:
try {
String time = value.toString();
Date date3 = new Date();
SimpleDateFormat format2 = new SimpleDateFormat("yyyy/MM");
Date date4 = format2.parse(time);
SimpleDateFormat format3 = new SimpleDateFormat("yyyy/MM");
data.setBaslama_tarixi(format3.format(date4));
Calendar cal = Calendar.getInstance();
cal.setTime(date3);
Calendar cal2 = Calendar.getInstance();
cal2.setTime(date4);
int diffYear = cal.get(Calendar.YEAR) - cal2.get(Calendar.YEAR);
int diffMonth = cal.get(Calendar.MONTH) - cal2.get(Calendar.MONTH);
if (diffMonth < 0) {
diffMonth += 12;
diffYear--;
}
data.setNe_qeder_isleyib(diffYear + " il " + diffMonth + " ay");
} catch (NumberFormatException | IndexOutOfBoundsException | ParseException ex) {
Logger.getLogger(Salary.class.getName()).log(Level.SEVERE, null, ex);
}
break;
case 19:
data.setBorc((Double) value);
break;
case 20:
data.setYekun_maas((Double) value);
data.setCem(data.getBank() + data.getIlk_maas() + data.getSon_maas() + data.getArtim());
data.setYekun_maas(data.getCem() - data.getBorc()
- ((data.getCem() / 26) * data.getQayib_gunu()) - data.getDetal_xetasi()
+ data.getSatin_alma() + ((data.getCem() / 26) * data.getElave_is()));
break;
case 21:
data.setQeyd((String) value);
break;
}
DBO.salary_Update(data, selectedRow);
visible(bolme, ay, il);
setVisible(false);
});
}`
If what you want is to display the full text of the cells instead of an abbreviation, you can use the Table Column Adjuster. e.g.:
String[] columnNames = {"Colum1", "Colum2", "Colum2"};
String[][] data = {
{"ABCDEFGHIJKLMNOPQRSTUVWXYZ", "-", "-"},
{"-", "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "-"},
{"-", "-", "ABCDEFGHIJKLMNOPQRSTUVWXYZ"}
};
TableModel model = new DefaultTableModel(data, columnNames);
JTable table = new JTable();
table.setModel(model);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
TableColumnAdjuster tca = new TableColumnAdjuster(table);
tca.adjustColumns();
JScrollPane pane = new JScrollPane(table);
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(pane);
frame.setSize(400, 300);
frame.setVisible(true);
You can get the code for the class TableColumnAdjuster from http://www.camick.com/java/source/TableColumnAdjuster.java
Found a way )
table.setModel(tableModel);
table = autoResizeColWidth(table, tableModel);
//table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM");
DatePickerCellEditor datePicker = new DatePickerCellEditor(formatter);
datePicker.setFormats(formatter);
date = table.getColumnModel().getColumn(18);
date.setCellEditor(datePicker);
table = new RXTable(tableModel) {
#Override
public boolean getScrollableTracksViewportWidth() {
return getPreferredSize().width < getParent().getWidth();
}
};
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
JScrollPane pane = new JScrollPane(table);
add(pane);
//table.setSelectAllForEdit(true);
//table.getColumnModel().getColumn(0).setMinWidth(100);
//table.getColumnModel().getColumn(1).setMinWidth(100);
//....
//table.getColumnModel().getColumn(21).setMinWidth(100);
//table.getColumnModel().getColumn(21).setMaxWidth(10000);
setLocationRelativeTo(null);

Android: How to parse HTML Table into ListView?

Hello i want to parse a HTML Table into a Android ListView but i don't know where to start. The Table has a lot of information. Could someone help me to start with this?
Thanks in advance!
The HTML Table: http://intranet.staring.nl/toepassingen/rooster/lochem/2W2/2012090320120909/2W01533.htm (Just click view source).
You will first need to parse the HTML table into a data structure, and then use ListView to display that information. Try using the JSoup library to do the HTML parsing: http://jsoup.org/cookbook/introduction/parsing-a-document
I don't know if you already got your answer here but I did the same with the link you suggest, I will post my code here but it is still very messy and don't apply for the newest timetable(9th hour)
Im using HTML Cleaner library for parsing the html:
try {
HtmlCleaner hc = new HtmlCleaner();
CleanerProperties cp = hc.getProperties();
cp.setAllowHtmlInsideAttributes(true);
cp.setAllowMultiWordAttributes(true);
cp.setRecognizeUnicodeChars(true);
cp.setOmitComments(true);
String loc = sp.getString( Constants.pref_locatie , "" );
String per = sp.getString( Constants.pref_persoon , "" );
String oob = sp.getString( Constants.pref_onderofboven , "" );
int counteruurmax;
int[] pauze;
if (oob.contains("onder")){
pauze = Constants.pauzeo;
} else if (oob.contains("boven")) {
pauze = Constants.pauzeb;
} else {
return false;
}
String url = "";
if (loc.contains("lochem")) {
url += Constants.RoosterLochem;
url += t.getDatum();
url += "/";
url += per;
counteruurmax = 11;
} else if (loc.contains("herenlaan")) {
url += Constants.RoosterHerenlaan;
url += per;
counteruurmax = 13;
} else if (loc.contains("beukenlaan")) {
url += Constants.RoosterBeukenlaan;
url += per;
counteruurmax = 11;
} else {
return false;
}
String htmlcode = t.getHtml(url);
TagNode html = hc.clean(htmlcode);
Document doc = new DomSerializer(cp, true).createDOM(html);
XPath xp = XPathFactory.newInstance().newXPath();
NodeList nl = (NodeList) xp.evaluate(Constants.XPathRooster, doc, XPathConstants.NODESET);
int counteruur = 1;
int counterdag = 1;
int decreaser = 0;
Boolean isPauze = false;
RoosterItems RItems = new RoosterItems();
RoosterItem RItem = null;
for (int i = 0; i < nl.getLength(); i++){
if ((counteruur == pauze[0]) || (counteruur == pauze[1]) || (counteruur == pauze[2])) {
isPauze = true;
decreaser++;
}
if (!isPauze) {
RItem = new RoosterItem();
switch (counterdag){
case 1:
RItem.setDag("ma");
break;
case 2:
RItem.setDag("di");
break;
case 3:
RItem.setDag("wo");
break;
case 4:
RItem.setDag("do");
break;
case 5:
RItem.setDag("vr");
break;
}
Node n = nl.item(i);
String content = n.getTextContent();
if (content.length() > 1) {
RItem.setUur(""+(counteruur-decreaser));
NodeList t1 = n.getChildNodes();
NodeList t2 = t1.item(0).getChildNodes();
NodeList t3 = t2.item(0).getChildNodes();
for (int j = 0; j < t3.getLength(); j++) {
Node temp = t3.item(j);
if (t3.getLength() == 3) {
switch (j) {
case 0:
RItem.setLes(""+temp.getTextContent());
break;
case 1:
RItem.setLokaal(""+temp.getTextContent());
break;
case 2:
RItem.setDocent(""+temp.getTextContent());
break;
default:
return false;
}
} else if (t3.getLength() == 4) {
switch (j) {
case 0:
break;
case 1:
RItem.setLes("tts. " + temp.getTextContent());
break;
case 2:
RItem.setLokaal(""+temp.getTextContent());
break;
case 3:
RItem.setDocent(""+temp.getTextContent());
break;
default:
return false;
}
} else if (t3.getLength() == 1) {
RItem.setLes(""+temp.getTextContent());
} else {
return false;
}
}
} else {
RItem.setUur("" + (counteruur-decreaser));
RItem.setLokaal("Vrij");
}
RItems.add(RItem);
}
if (counteruur == counteruurmax) { counteruur = 0; counterdag++; decreaser = 0;}
counteruur++;
isPauze = false;
}
if (RItems.size() > 0) {
mSQL = new RoosterSQLAdapter(mContext);
mSQL.openToWrite();
mSQL.deleteAll();
for (int j = 0; j < RItems.size(); j++) {
RoosterItem insert = RItems.get(j);
mSQL.insert(insert.getDag(), insert.getUur(), insert.getLes(), insert.getLokaal(), insert.getDocent());
}
if (mSQL != null) mSQL.close();
}
return true;
} catch (ParserConfigurationException e) {
e.printStackTrace();
return false;
} catch (XPathExpressionException e) {
e.printStackTrace();
return false;
}
There are a few constants but I think you can guess them yourself;) and otherwise you know how to ask me for them:)
The RoosterItem class will hold all variables of an hour, and the RoosterItems will hold more than one RoosterItem
Good Luck!
So far i think JSoup is one of the best way to extract or manipulate the HTML.....
See this link :
http://jsoup.org/
But somehow.... this did't worked in my case, so i converted the entire HTML code into String, then parsed it.....

outOfMemoryError:java heap

public class seventhma {
XSSFSheet m_sheet;
int m_iNbRows;
int m_iCurrentRow = 0;
private static final String JAVA_TOSTRING = "EEE MMM dd HH:mm:ss zzz yyyy";
public seventhma(XSSFSheet sheet) {
m_sheet = sheet;
m_iNbRows = sheet.getPhysicalNumberOfRows();
}
/*
* Returns the contents of an Excel row in the form of a String array.
*
* #see com.ibm.ccd.common.parsing.Parser#splitLine()
*/
public String[] splitLine() throws Exception {
// if (m_iCurrentRow == m_iNbRows)
// return null;
XSSFRow row = m_sheet.getRow(m_iCurrentRow);
if (row == null) {
return null;
} else {
int cellIndex = 0;
int noOfCells = row.getPhysicalNumberOfCells();
String[] values = new String[noOfCells];
short firstCellNum = row.getFirstCellNum();
short lastCellNum = row.getLastCellNum();
if (firstCellNum >= 0 && lastCellNum >= 0) {
for (short iCurrent = firstCellNum; iCurrent < lastCellNum; iCurrent++) {
XSSFCell cell = (XSSFCell) row.getCell(iCurrent);
if (cell == null) {
values[iCurrent] = "";
cellIndex++;
continue;
} else {
switch (cell.getCellType()) {
case XSSFCell.CELL_TYPE_NUMERIC:
double value = cell.getNumericCellValue();
if (DateUtil.isCellDateFormatted(cell))
{
if (DateUtil.isValidExcelDate(value)) {
Date date = DateUtil.getJavaDate(value);
SimpleDateFormat dateFormat = new SimpleDateFormat(JAVA_TOSTRING);
values[iCurrent] = dateFormat.format(date);
} else {
// throw new
// Exception("Invalid Date value found at row number "
// +
// row.getRowNum()+" and column number "+cell.getCellNum());
}
} else {
values[iCurrent] = value + "";
}
break;
case XSSFCell.CELL_TYPE_STRING:
values[iCurrent] = cell.getStringCellValue();
break;
case XSSFCell.CELL_TYPE_BLANK:
values[iCurrent] = null;
break;
default:
values[iCurrent] = null;
}
}
}
}
m_iCurrentRow++;
return values;
}
}
public static void main(String args[]) {
XSSFWorkbook workBook = null;
File file = new File("E:\\Local\\Local2.xlsx");
InputStream excelDocumentStream = null;
try {
excelDocumentStream = new FileInputStream(file);
// POIFSFileSystem fsPOI = new POIFSFileSystem(new
// BufferedInputStream(excelDocumentStream));
BufferedInputStream bfs = new BufferedInputStream(excelDocumentStream);
workBook = new XSSFWorkbook(bfs);
seventhma parser = new seventhma(workBook.getSheetAt(0));
String[] res = null;
while ((res = parser.splitLine()) != null) {
for (int i = 0; i < res.length; i++) {
System.out.println("[" + res[i] + "]" + "\t");
}
System.out.println(res.length);
}
bfs = null;
excelDocumentStream.close();
} catch (Exception e) {
System.out.println(e);
e.printStackTrace();
}
}
}
This program gives java heap out of space and when excel sheet containing 16 columns is uploaded it gives ArrayIndexOutOfBoundException.I had increased memory of eclipse upto -Xmx1600m but that also didnt work.
You get the ArrayIndexOutOfBoundException on the values array because you use the row.getPhysicalNumberOfCells() to determine its size. But row.getPhysicalNumberOfCells() will only count the cells that are actually filled in the file.
For example if you create an Excel sheet and only fill columns A, C and F and don't touch the other cells at all row.getPhysicalNumberOfCells() will return 3.
But you are iterating over all the cells by getting row.getFirstCellNum() and row.getLastCellNum(). So values[iCurrent] will sure be out of bounds once you reach cell F.
Regarding the OutOfMemory issue:
XSSF uses a LOT of memory. Try pushing your VM to as much memory as is possible for your machine. Or if you are just reading the files then try to go with the eventmodel API instead of the usermodel (think SAX vs. DOM).
(source: apache.org)

Categories