I want to make an income report line chart in last 30 days, i only need the date on series1 (horizontal chart) and the total income on series2 (vertical chart).
the object is DayBill that contain String date, and BigDecimal totalAmount. i want to make like date = 2017-09-19 got totalamount = 112527.5 , and so on.
public class ChartViewBean implements Serializable {
private LineChartModel lineModel1;
private List<DayBill> bills;
private TotalSalesDAO dao;
#PostConstruct
public void init() {
createLineModels();
}
public void itemSelect(ItemSelectEvent event) {
FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Item selected",
"Item Index: " + event.getItemIndex() + ", Series Index:" + event.getSeriesIndex());
FacesContext.getCurrentInstance().addMessage(null, msg);
}
public LineChartModel getLineModel1() {
return lineModel1;
}
private void createLineModels() {
lineModel1 = initLinearModel();
lineModel1.setTitle("Linear Chart");
lineModel1.setLegendPosition("e");
Axis yAxis = lineModel1.getAxis(AxisType.Y);
yAxis.setMin(0);
yAxis.setMax(10);
lineModel1.setExtender("skinChart");
}
private LineChartModel initLinearModel() {
LineChartModel model = new LineChartModel();
LineChartSeries series1 = new LineChartSeries();
series1.setLabel("Series 1");
series1.set(1, 2);
series1.set(2, 1);
series1.set(3, 3);
series1.set(4, 6);
series1.set(5, 8);
LineChartSeries series2 = new LineChartSeries();
series2.setLabel("Series 2");
series2.set(1, 6);
series2.set(2, 3);
series2.set(3, 2);
series2.set(4, 7);
series2.set(5, 9);
model.addSeries(series1);
model.addSeries(series2);
return model;
}
this is my DAO, i already get the data that i want. The problem is i dont know how to put the data to the chart.
public List<DayBill> getDayBills() throws Exception
{
Connection conn = ds.getConnection();
PreparedStatement ps = null;
ResultSet rs = null;
StringBuffer query = new StringBuffer();
List<DayBill> list = new ArrayList<DayBill>();
query
.append(" select SUM(GRAND_TOTAL) , substr(BILL_DATE,0,11) ")
.append(" from R_BILL where substr(BILL_DATE,0,11) >= date('now','localtime','-30 day') ");
query.append(" group by strftime('%d',BILL_DATE) ");
query.append(" order by BILL_DATE ASC ");
try
{
DayBill daybill;
ps = conn.prepareStatement(query.toString());
rs = ps.executeQuery();
while(rs.next())
{
daybill = new DayBill();
daybill.setTotalAmount(rs.getBigDecimal(1));
daybill.setDate(rs.getString(2));
list.add(daybill);
}
}
finally
{
if(rs != null)
rs.close();
if(ps != null)
ps.close();
if(conn != null)
conn.close();
}
return list;
}
this is what i want, like income perday
Related
Its working fine with the following code but only one problem exist, Each time when I enter details of another Persons Payment it replaces the previous data in the database, I Dont'know why?
may table will look like id,date, houseName, mobile, month, subscription, amount, payed_Amount
one person could have multiple payments.
its the details to be inserted.
private void saveDataIntoDb() {
String date = dateView.getText().toString();
String phone = mobileNo.getText().toString();
String house = housename.getText().toString();
PayBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
boolean result= false;
int length=paymentReports.size();
//to get data from listLayout
for (int i = 0; i < list_layout.getChildCount(); i++) {
View customView = list_layout.getChildAt(i);
TextView selectedSubscription = customView.findViewById(id.selected_subType);
Spinner month_s = customView.findViewById(id.spinner);
TextView amount = customView.findViewById(id.amount);
TextView payed = customView.findViewById(id.payedAmount);
selected_Sub_name = selectedSubscription.getText().toString();
payedMonth = monthList.get(month_s.getSelectedItemPosition());
System.out.println("payedMonth-------------" + payedMonth);
Amnt = Integer.parseInt(amount.getText().toString());
System.out.println("sub_amount,,,,,,,,,,,,,,,,,,,," + Amnt);
Payed = Integer.parseInt(payed.getText().toString());
System.out.println("payed_money________________" + Payed);
result= _db.insertdata(date, phone, house, selected_Sub_name, payedMonth, Amnt, Payed);
}
if (result== true) {
Toast.makeText(DepositPage.this, "= Inserted Successfully", Toast.LENGTH_SHORT).show();
// Intent intent=new Intent(getApplicationContext(),Report_Page.class);
// startActivity(intent);
} else {
Toast.makeText(DepositPage.this, "= Insertion Failed", Toast.LENGTH_SHORT).show();
}
}
});
}
here is the insert query
boolean insertdata(String date, String phone, String housename, String sub_type, String month, int amount, int payed) {
SQLiteDatabase sqLiteDatabase = getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(Date, date);
contentValues.put(Phone, phone);
contentValues.put(Housename, housename);
contentValues.put(Sub_type, sub_type);
contentValues.put(Month, month);
contentValues.put(Amount, amount);
contentValues.put(Payed, payed);
Long result = sqLiteDatabase.insert(TABLE_Payment_Details, null, contentValues);
if (result == -1) {
return false;
} else {
return true;
}
}
i'm trying to activate progress bar that showing the advance of the "for loop" i have while i reading my files and writes them to excel file.
the problam is that the bar don't update to the user until the end of the for loop in each way i tried. what is the right way to do this? is it possible to activate progress bar in the middle of the MyPanel class?
i have the next classes:
Tester(contain the main) , MyPanel , LogFileReader , DefectFileReader.
Tester
public class Tester {
public static void main(String[] args){
JFrame frame = new JFrame("Analayzer GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(450, 300);
frame.setLocationRelativeTo(null);
MyPanel p = new MyPanel();
frame.add(p);
frame.setVisible(true);
}
}
My Panel (only the relevant code)
public class MyActionListener implements ActionListener
{
public void actionPerformed(ActionEvent click)
{
/*...........(code irelevant).......*/
if(click.getSource() == analayze){
Boolean valid = isValidToStart();
if(valid == true){
try{
fos = new FileOutputStream("c:/temp/analayze.xlsx");
if(DFloaded == true){
try {
pbar.repaint();
DF = new File[DFLIST.length];
dfReader = new DefectFileReader[DFLIST.length];
docArray = new Document[DFLIST.length];
for(int i = 0 ; i < DFLIST.length ; i++){
/******* This is where i want to update my bar according to (i/DFList.length) ********/
System.out.println("i'm sending the file down here to parse from file to document");
System.out.println(DFLIST[i].getAbsoluteFile());
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
docArray[i] = (Document) db.parse(DFLIST[i]);
docArray[i].getDocumentElement().normalize();
dfReader[i] = new DefectFileReader(DFLIST[i] , docArray[i]);
dfReader[i].getRunsIndex();
totalDuration = sumTimes(dfReader[i].inspectionDuration());
if(i==0){
firstWriteToExcel(dfReader[0], sheet, workbook, fos);
writeToExcel(dfReader[0], sheet, workbook, fos);
}
if(i!=0)
writeToExcel(dfReader[i] , sheet , workbook , fos );
repaint();
if(INPloaded == true){
}
DFLIST[i] = null;
dfReader[i].clearDfReader();
docArray[i] = null;
System.gc();
}
}
catch(Exception e ) {
System.out.println(e);
System.exit(0);
}
}
row = sheet.createRow(rowIndex);
totalDuration = sumTimes("00:00:00");
if(inspectionDuration.getState() == true){
row.createCell(cellIndex - 1).setCellValue(totalDuration);
row.getCell(cellIndex - 1).setCellStyle(csForFirstWrite);
}
((Workbook) workbook).write(fos);
workbook.close();
JOptionPane.showMessageDialog(null, "Your data has been analyze!\n you can find the result in c:\\temp");
System.exit(0);
}catch(Exception e){
e.printStackTrace();
}
}
}
I'm trying write application in Jave ME with RMS. Application stores information about courier's customer.
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.rms.*;
import java.io.ByteArrayOutputStream;
import java.io.ByteArrayInputStream;
import java.io.DataOutputStream;
import java.io.DataInputStream;
public class ClientsApp extends MIDlet implements CommandListener {
// controls
private Display screen = null;
private List menu = null;
private Form addClientForm = null;
private Form showClientForm = null;
private RecordStore clients;
private ByteArrayOutputStream stream = null;
private DataOutputStream out = null;
private byte[] dates;
TextField name = null;
TextField surname = null;
TextField email = null;
TextField phone = null;
DateField date = null;
TextField price = null;
TextField description = null;
// comands
private final Command backCommand;
private final Command mainMenuCommand;
private final Command exitCommand;
private final Command addClientCommand;
public ClientsApp() {
// initializating controls and comands
menu = new List("Lista klientów", Choice.IMPLICIT);
backCommand = new Command("Cofnij", Command.BACK, 0);
mainMenuCommand = new Command("Main", Command.SCREEN, 1);
exitCommand = new Command("Koniec", Command.EXIT, 2);
addClientCommand = new Command("Zapisz", Command.OK, 3);
stream = new ByteArrayOutputStream();
out = new DataOutputStream(stream);
menu.append("Dodaj klienta", null);
menu.append("Przegladaj klientow", null);
menu.append("Usun klienta", null);
}
protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
}
protected void pauseApp() {
}
protected void startApp() throws MIDletStateChangeException {
screen = Display.getDisplay(this);
screen.setCurrent(menu);
try {
clients = RecordStore.openRecordStore("clients", false, RecordStore.AUTHMODE_PRIVATE, false);
}
catch(RecordStoreException exc) {
}
menu.addCommand(exitCommand);
menu.setCommandListener(this);
}
public void commandAction(Command cmd, Displayable dsp) {
if(cmd.getCommandType() == Command.EXIT) {
try{
destroyApp(false);
notifyDestroyed();
}
catch(Exception exc) {
exc.printStackTrace();
}
}
else if(cmd.getCommandType() == Command.BACK) {
screen.setCurrent(menu);
}
else if(cmd.getCommandType() == Command.OK) {
try {
out.writeUTF(name.getString());
out.writeUTF(surname.getString());
out.writeUTF(email.getString());
out.writeUTF(phone.getString());
out.writeUTF(date.getDate().toString());
out.writeUTF(price.getString());
out.writeUTF(description.getString());
dates = stream.toByteArray();
clients.addRecord(dates, 0, dates.length);
stream.close();
out.close();
clients.closeRecordStore();
}
catch(Exception exc) {
}
}
else {
List option = (List) screen.getCurrent();
switch(option.getSelectedIndex()) {
case 0 : {
addClients();
break;
}
case 1 : {
showClients();
break;
}
case 2 : {
deleteClients();
break;
}
}
}
}
protected void addClients() {
addClientForm = new Form("Dodaj klienta");
name = new TextField("Imię klienta", "", 10, TextField.ANY);
surname = new TextField("Nazwisko klienta", "", 15, TextField.ANY);
email = new TextField("Email klienta", "", 20, TextField.EMAILADDR);
phone = new TextField("Numer telefonu", "", 12, TextField.PHONENUMBER);
date = new DateField("Data dostarczenia", DateField.DATE);
price = new TextField("Do zapłaty", "", 6, TextField.NUMERIC);
description = new TextField("Uwagi", "", 50, TextField.ANY);
addClientForm.append(name);
addClientForm.append(surname);
addClientForm.append(email);
addClientForm.append(phone);
addClientForm.append(date);
addClientForm.append(price);
addClientForm.append(description);
screen.setCurrent(addClientForm);
addClientForm.addCommand(backCommand);
addClientForm.addCommand(addClientCommand);
addClientForm.setCommandListener(this);
}
protected void showClients() {
TextBox info = new TextBox("Klienci", null, 100, 0);
RecordEnumeration iterator = null;
String str = null;
byte[] temp = null;
try {
iterator = clients.enumerateRecords(null, null, false);
while(iterator.hasNextElement()) {
temp = iterator.nextRecord();
}
for(int i = 0; i < temp.length; i++) {
str += (char) temp[i];
}
System.out.println(str);
clients.closeRecordStore();
}
catch(Exception exc) {
}
info.setString(str);
screen.setCurrent(info);
}
}
Write/read information from RecordStore don't work. I don't have any exception throw. Could somebody help me?
PS Sorry for my bad language.
Are you sure you do not get any exception? Catch blocks are empty...
I see several issues:
Shouldn't you open the record store with createIfNecessary (2nd parameter) set to true?
In ShowClients method, you should use DataInputStream to read items from the record (the byte array 'temp'), the loop over temp is strange. And a check for null 'temp' to avoid NPE when the store is empty is missing too.
On OK command, and also in ShowClients, the store is closed, so next time it will fail with RecordStoreNotOpenException I guess.
I would also consider flushing 'out' stream before calling stream.toByteArray(), although in this case (DataOutputStrea/ByteArrayOutputStream) it is nothing but a good practice..
I actually followed below link added columns and row data as dynamic, little confused on how to show on xhtml. any help
http://balusc.blogspot.com/2006/06/using-datatables.html#PopulateDynamicDatatable
List<String> strlist = new ArrayList<String>();
List<List<String>> dynamicListynamicList = new ArrayList<List<String>>();
strlist.add("Name");
strlist.add("SSN");
for(String columnName : columnNamesList){
strlist.add(columnName);
}
List<String> rowData = new ArrayList<String>();
for(String otherList : listData){
try {
rowData.add(otherList.getName());
rowData.add(otherList.getId());
if(otherList.getAmount() != null){
for(BigDecimal amount : otherList.getAmount()){
if(amount != null){
rowData.add(amount.toString());
}else{
rowData.add("");
}
}
}else{
for(String s : strlist){
rowData.add("");
}
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
dynamicListynamicList.add(Arrays.asList(rowData.toArray(new String[rowData.size()] )));
}
String[] strarray = new String[strlist.size()];
dynamicHeaders = strlist.toArray(strarray );
populateDynamicDataTable(dynamicListynamicList);
private void populateDynamicDataTable(List<List<String>> dynamicList2){
HtmlDataTable dynamicDataTable = new HtmlDataTable();
for (int i = 0; i < dynamicList2.get(0).size(); i++) {
HtmlColumn column = new HtmlColumn();
dynamicDataTable.getChildren().add(column);
HtmlOutputText header = new HtmlOutputText();
header.setValue(createValueExpression("#{dynamicItemColumn[" + dynamicHeaders[i] + "]}", String.class));
column.setHeader(header);
HtmlOutputText output = new HtmlOutputText();
output.setValueExpression("value",
createValueExpression("#{dynamicItem[" + i + "]}", String.class));
column.getChildren().add(output);
}
dynamicDataTableGroup = new HtmlPanelGroup();
dynamicDataTableGroup.getChildren().add(dynamicDataTable);
setDynamicList(dynamicList2);
every thing works fine as data being added, now i wasnt sure and my apologies, how to iterate in jsf page(xhtml), to show relvant columna nd rowdata..
I am a newbie of Blackberry developing application. I try to store all xml parsing data to an object, and set them to a vector.
public class XmlParser extends MainScreen {
Database d;
private HttpConnection hcon = null;
private Vector binN;
public Vector getBinN() {
return binN;
}
public void setBinN(Vector bin) {
this.binN = bin;
}
LabelField from;
LabelField ttl;
LabelField desc;
LabelField date;
public XmlParser() {
LabelField title = new LabelField("Headline News" ,LabelField.HCENTER|LabelField.USE_ALL_WIDTH);
setTitle(title);
try {
URI myURI = URI.create("file:///SDCard/Database/WebFeed.db");
d = DatabaseFactory.open(myURI);
Statement st = d.createStatement("SELECT feed_url, feed_name FROM WebFeed");
st.prepare();
Cursor c = st.getCursor();
while (c.next()) {
Row r = c.getRow();
hcon = (HttpConnection)Connector.open(r.getString(0));
hcon.setRequestMethod(HttpConnection.GET);
hcon.setRequestProperty("User-Agent", "Profile/MIDP-1.0 Configuration/CLDC-1.0");
hcon.setRequestProperty("Content-Length", "0");
hcon.setRequestProperty("Connection", "close");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
builder.isValidating();
Document document = builder.parse(hcon.openInputStream());
Element rootElement = document.getDocumentElement();
rootElement.normalize();
NodeList list = document.getElementsByTagName("item");
int i=0;
while (i<10){
Node item = list.item(i);
if(item.getNodeType() != Node.TEXT_NODE) {
NodeList itemChilds = item.getChildNodes();
int j=0;
while (j<10){
Node detailNode = itemChilds.item(j);
if(detailNode.getNodeType() != Node.TEXT_NODE) {
if(detailNode.getNodeName().equalsIgnoreCase("title")) {
ttl = new LabelField(getNodeValue(detailNode)) {
public void paint(Graphics g) {
g.setColor(Color.BLUE);
super.paint(g);
}
};
from = new LabelField(r.getString(1), LabelField.FIELD_RIGHT|LabelField.USE_ALL_WIDTH);
ttl.setFont(Font.getDefault().derive(Font.BOLD));
from.setFont(Font.getDefault().derive(Font.BOLD));
add (from);
add (ttl);
} else if(detailNode.getNodeName().equalsIgnoreCase("description")) {
desc = new LabelField(getNodeValue(detailNode), 0, 70, USE_ALL_WIDTH);
add(desc);
} else if(detailNode.getNodeName().equalsIgnoreCase("dc:date")) {
date = new LabelField(getNodeValue(detailNode), 11, 5, USE_ALL_WIDTH) {
public void paint(Graphics g) {
g.setColor(Color.ORANGE);
super.paint(g);
}
};
add(date);
add(new SeparatorField());
} else if(detailNode.getNodeName().equalsIgnoreCase("pubDate")) {
date = new LabelField(getNodeValue(detailNode), 0, 22, USE_ALL_WIDTH) {
public void paint(Graphics g) {
g.setColor(Color.ORANGE);
super.paint(g);
}
};
add(date);
add(new SeparatorField());
} else {
System.out.println("not the node");
}
} else {
System.out.println("not text node");
}
j++;
}
}
i++;
BinNews bin = new BinNews();
bin.setProv(from.getText());
bin.setTitle(ttl.getText());
bin.setDesc(desc.getText());
bin.setDate(date.getText());
binN.addElement(bin);
}
setBinN(binN);
}
//setBinN(binN);
st.close();
d.close();
} catch (Exception e) {
add (new LabelField(e.toString(),LabelField.HCENTER|LabelField.USE_ALL_WIDTH));
System.out.println(e.toString());
}
}
public String getNodeValue(Node node) {
NodeList nodeList = node.getChildNodes();
Node childNode = nodeList.item(0);
return childNode.getNodeValue();
}
}
I try to store all data from an object called BinNews, to a vector called binN. But when I do debugging, I found that BinN has null value, because "binN.addElement(bin)" doesn't work.
Please advise.
First, you don't actually call setBinN until after the while(i < 10) loop completes. So when you say binN.addElement(bin) then binN will be null.
However your setBinN(binN) call doesn't make sense because you're passing in binN and then setting it to itself which isn't going to do anything.
What you can do is have binN = new Vector(); at the top of the constructor and then it won't be null later on. I don't think the setBinN call will be necessary later on if you're adding the BinNews objects straight to binN.