Activate Progress Bar outside the main using data claculating in the background - multithreading

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

Related

RecylerView to pdf

Hello am new to Android studio
I have made recylerview for transaction details . I need to create pdf for this recylerview items.
Example: I have 24 cardviews in recylerview so need to create pdf with each page 4 cardviews only . So totally I need to get pdf as 6 pages .
How to do that . Thanks in advance.
This is sample image of my view
Am passing below code
recyclerView.measure(View.MeasureSpec.makeMeasureSpec(recyclerView.getWidth(),View.MeasureSpec.EXACTLY),View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED));
Bitmap bm=Bitmap.createBitmap(recyclerView.getWidth(),recyclerView.getMeasuredHeight(),Bitmap.Config.ARGB_8888);
String mpath2="/mnt/sdcard/mathanpaymentpdf";
File imageFile = new File(mpath2);
PDFHelper pdfHelper = new PDFHelper(imageFile,this);
pdfHelper.saveImageToPDF(recyclerView,bm,"mathan"+System.currentTimeMillis());
public class PDFHelper {
private File mFolder;
private File mFile;
private Context mContext;
public PDFHelper(File folder, Context context) {
this.mContext = context;
this.mFolder = folder;
if(!mFolder.exists())
mFolder.mkdirs();
}
public void saveImageToPDF(View title, Bitmap bitmap, String filename) {
mFile = new File(mFolder, filename + ".pdf");
if (!mFile.exists()) {
int height = title.getHeight() + bitmap.getHeight();
PdfDocument document = new PdfDocument();
PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(bitmap.getWidth(), height, 1).create();
PdfDocument.Page page = document.startPage(pageInfo);
Canvas canvas = page.getCanvas();
title.draw(canvas);
canvas.drawBitmap(bitmap, null, new Rect(0, title.getHeight(), bitmap.getWidth(),bitmap.getHeight()), null);
document.finishPage(page);
try {
mFile.createNewFile();
OutputStream out = new FileOutputStream(mFile);
document.writeTo(out);
document.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
This am tried am getting pdf on a single page only
Just I need to split into multiple pages.
Note: I need code in java, not in kotlin
Am solved this by using itext library
implementation 'com.itextpdf:itextpdf:5.0.6'
Then call with RecylerView
public void generatePDF(RecyclerView view) {
RecyclerView.Adapter adapter = view.getAdapter();
int sie2=adapter.getItemCount();
if (sie2 == 0) {
Toast.makeText(this,"No Transactions",Toast.LENGTH_LONG).show();
}else{
Bitmap bigBitmap = null;
if (adapter != null) {
int size = adapter.getItemCount();
int height = 0;
Paint paint = new Paint();
int iHeight = 0;
final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
// Use 1/8th of the available memory for this memory cache.
final int cacheSize = maxMemory / 8;
LruCache<String, Bitmap> bitmaCache = new LruCache<>(cacheSize);
for (int i = 0; i < size; i++) {
RecyclerView.ViewHolder holder = adapter.createViewHolder(view, adapter.getItemViewType(i));
adapter.onBindViewHolder(holder, i);
holder.itemView.measure(View.MeasureSpec.makeMeasureSpec(view.getWidth(), View.MeasureSpec.EXACTLY),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
holder.itemView.layout(0, 0, holder.itemView.getMeasuredWidth(), holder.itemView.getMeasuredHeight());
holder.itemView.setDrawingCacheEnabled(true);
holder.itemView.buildDrawingCache();
Bitmap drawingCache = holder.itemView.getDrawingCache();
if (drawingCache != null) {
bitmaCache.put(String.valueOf(i), drawingCache);
}
height += holder.itemView.getMeasuredHeight();
}
bigBitmap = Bitmap.createBitmap(view.getMeasuredWidth(), height, Bitmap.Config.ARGB_8888);
Canvas bigCanvas = new Canvas(bigBitmap);
bigCanvas.drawColor(Color.WHITE);
Document document=new Document();
final File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS), "MAT"+System.currentTimeMillis()+".pdf");
try {
PdfWriter.getInstance(document, new FileOutputStream(file));
} catch (DocumentException | FileNotFoundException e) {
e.printStackTrace();
}
for (int i = 0; i < size; i++) {
try {
//Adding the content to the document
Bitmap bmp = bitmaCache.get(String.valueOf(i));
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
com.itextpdf.text.Image image= com.itextpdf.text.Image.getInstance(stream.toByteArray());
//Image image = Image.getInstance(stream.toByteArray());
float scaler = ((document.getPageSize().getWidth() - document.leftMargin()
- document.rightMargin() - 50) / image.getWidth()) * 100; // 0 means you have no indentation. If you have any, change it.
image.scalePercent(scaler);
image.setAlignment(com.itextpdf.text.Image.ALIGN_CENTER | com.itextpdf.text.Image.ALIGN_TOP);
if (!document.isOpen()) {
document.open();
}
document.add(image);
} catch (Exception ex) {
Log.e("TAG-ORDER PRINT ERROR", ex.getMessage());
}
}
if (document.isOpen()) {
document.close();
}
// Set on UI Thread
runOnUiThread(new Runnable() {
#Override
public void run() {
android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(MainActivityAdminMain.this);
builder.setTitle("Success")
.setMessage("PDF File Generated Successfully.")
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton("Open", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// dialog.dismiss();
Intent target = new Intent(Intent.ACTION_VIEW);
target.setDataAndType(Uri.fromFile(file), "application/pdf");
target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
Intent intent56 = Intent.createChooser(target, "Open File");
try {
startActivity(intent56);
} catch (ActivityNotFoundException e) {
Toast.makeText(MainActivityAdminMain.this,"No PDF Viewer Installed.",Toast.LENGTH_LONG).show();
}
}
}).show();
}
});
}}
}
100% working.. This helps to anyone needs

how to attach an XML file in the "Files" tab of an action

I have a big question, you can attach XML through an action, when you import the XML and also save it in the "Files" tab, the question is. if it can be attached?.
Here is an example image:
what is missing is that I automatically attach in the "Files" tab, when I put upload
Here is my code where, I attached the XML
public PXAction<ARInvoice> CargarXML;
[PXUIField(DisplayName = "Carga de código hash")]
[PXButton()]
public virtual void cargarXML()
{
var Result = NewFilePanel.AskExt(true);
if (Result == WebDialogResult.OK)
{
PX.SM.FileInfo fileInfo = PX.Common.PXContext.SessionTyped<PXSessionStatePXData>().FileInfo["CargaSessionKey"];
string result = System.Text.Encoding.UTF8.GetString(fileInfo.BinData);
ARInvoice ari = Base.Document.Current;
xtFECodHashEntry graph2 = PXGraph.CreateInstance<xtFECodHashEntry>();
var pchExt = ari.GetExtension<ARRegisterExt>();
string Valor = "";
XmlDocument xm = new XmlDocument();
xm.LoadXml(result);
XmlNodeList elemList = xm.GetElementsByTagName("ds:DigestValue");
for (int i = 0; i < elemList.Count;)
{
Valor = (elemList[i].InnerXml);
break;
}
PXLongOperation.StartOperation(Base, delegate ()
{
xtFECodHash dac = new xtFECodHash();
dac.RefNbr = ari.RefNbr;
dac.DocType = ari.DocType;
dac.Nrocomprobante = ari.InvoiceNbr;
dac.Hash = Valor;
dac.Tipo = pchExt.UsrTDocSunat;
graph2.xtFECodHashs.Insert(dac);
graph2.Actions.PressSave();
});
}
}
If you have the FileInfo object which it seems like you do I have used something like this:
protected virtual void SaveFile(FileInfo fileInfo, PXCache cache, object row)
{
if (fileInfo == null)
{
return;
}
var fileGraph = PXGraph.CreateInstance<UploadFileMaintenance>();
if (!fileGraph.SaveFile(fileInfo, FileExistsAction.CreateVersion))
{
return;
}
if (!fileInfo.UID.HasValue)
{
return;
}
PXNoteAttribute.SetFileNotes(cache, row, fileInfo.UID.Value);
}
So in your example you could call this method as shown above using the following:
SaveFile(fileInfo, Base.Document.Cache, Base.Document.Current);

Application in JaveME using RMS

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..

How to edit data with dynamic TableView with dynamic column in JAVAFX

Today This is the demo to show data from CSV for DAT file without make custom class on tableView in JavaFX 2.0. I call this TableView as Dynamic TableView because the tableview automatically manages the columns and rows.
On my research about the editable on tableView we must have a custom class and implement it to tableView to show as this demo ==> http://docs.oracle.com/javafx/2/ui_controls/table-view.htm
But in this case I can not do it because we don't know how many column example with csv file or .dat file.... I want to do editable on this tableView in this case by add TextField into TableCell. How does it do without make custom class (because you do not how many column ...), and if it must make custom class then how about the design of custom class for this case?
Could you please help me?
private void getDataDetailWithDynamic() {
tblView.getItems().clear();
tblView.getColumns().clear();
tblView.setPlaceholder(new Label("Loading..."));
// #Override
try {
File aFile = new File(txtFilePath.getText());
InputStream is = new BufferedInputStream(new FileInputStream(aFile));
Reader reader = new InputStreamReader(is, "UTF-8");
BufferedReader in = new BufferedReader(reader);
final String headerLine = in.readLine();
final String[] headerValues = headerLine.split("\t");
for (int column = 0; column < headerValues.length; column++) {
tblView.getColumns().add(
createColumn(column, headerValues[column]));
}
// Data:
String dataLine;
while ((dataLine = in.readLine()) != null) {
final String[] dataValues = dataLine.split("\t");
// Add additional columns if necessary:
for (int columnIndex = tblView.getColumns().size(); columnIndex < dataValues.length; columnIndex++) {
tblView.getColumns().add(createColumn(columnIndex, ""));
}
// Add data to table:
ObservableList<StringProperty> data = FXCollections
.observableArrayList();
for (String value : dataValues) {
data.add(new SimpleStringProperty(value));
}
tblView.getItems().add(data);
}
} catch (Exception ex) {
System.out.println("ex: " + ex.toString());
}
for(int i=0; i<tblView.getColumns().size(); i++) {
TableColumn col = (TableColumn)tblView.getColumns().get(i);
col.setPrefWidth(70);
}
}
private TableColumn createColumn(
final int columnIndex, String columnTitle) {
TableColumn column = new TableColumn(DefaultVars.BLANK_CHARACTER);
String title;
if (columnTitle == null || columnTitle.trim().length() == 0) {
title = "Column " + (columnIndex + 1);
} else {
title = columnTitle;
}
Callback<TableColumn, TableCell> cellFactory = new Callback<TableColumn, TableCell>() {
#Override
public TableCell call(TableColumn p) {
System.out.println("event cell");
EditingCellData cellExtend = new EditingCellData();
return cellExtend;
}
};
column.setText(title);
column.setCellValueFactory(cellFactory);
return column;
}
Thanks for your reading.
This is the best way to resolve it ==> https://forums.oracle.com/message/11216643#11216643
I'm really thank for your reading about that.
Thanks

Blackberry - How if addElement() doesn't work?

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.

Resources