Hiding headers from a query in java program - java

So i have a program that spits out data from google to a csv file. What i want to do is allow users to choose to display the headers or not via using a string.
Here is my printer:
...some code
// getting the queries to print
if (results.getRows() == null || results.getRows().isEmpty()) {
pw.println("No results Found.");
System.out.println("No results Found.");
} else {
// Print column headers.
for (ColumnHeaders header : results.getColumnHeaders()) {
pw.print(header.getName() + ", ");
}
pw.println();
// Print actual data.
for (List<String> row : results.getRows()) {
for (String column : row) {
pw.print(column + ",");
}
pw.println();
}
pw.close();
}
}
}
I have a properties file that is connected to my program and i want to put it so that when a user types in no in the header part of the properties file i dont want the headers to show.
I was thinking about converting the header part into a string and putting it in the if then statement. any suggestions? thx in advanced
EDIT:
// column headers statement
if (headers=="yes") {
for (ColumnHeaders header : results.getColumnHeaders())
pw.print(header.getName() + ", ");
} else {
// Print column headers.
for (ColumnHeaders header : results.getColumnHeaders()) {
pw.print("" + ", ");
}
pw.println();
}
// getting the queries to print
if (results.getRows() == null || results.getRows().isEmpty()) {
pw.println("No results Found.");
System.out.println("No results Found.");
} else {
// Print actual data.
for (List<String> row : results.getRows()) {
for (String column : row) {
pw.print(column + ",");
}
pw.println();
}
pw.close();
}
}
}
But what I have now is not working correctly.

First thing is first, you are not checking the user input correctly to match
You need to change
if (headers=="yes") {
to
if (headers.equals("yes")) {
I would also get rid of the else statement for printing out nothing in the first row except commas. Do you really want the first row to just be commas?
Make sure to close your stream at the end no matter what, too. It looks like your pw.close() is in an else statement.

Related

Checking which parameter is missing from file content

I have a TransferReader class which reads a file containing transfer data from bank account to another using the following form:
SenderAccountID,ReceiverAccountID,Amount,TransferDate
"473728292,474728298,1500.00,2019-10-17 12:34:12" (unmodified string)
Suppose that the file has been modified before being read so that one of the above mentioned paramaters are missing, and I want to check which of those are missing.
"474728298,1500.00,2019-10-17 12:34:12" (modified string)
I am using a BufferedReader to read each line, and then splitting each element into a String[] using String.split(",") as delimeter.
As already realized, because the Sender Account ID and Receiver Account ID are right next to one another within a record there is no real way of knowing which ID might be missing unless a delimiter remains in its' place indicating a Null value. There are however mechanisms available to determine that it is indeed one of the two that is missing, which one will need to be carried out through User scrutiny and even then, that may not be good enough. The other record column fields like Amount and Transfer Date can be easily validated or if missing can be implicated within a specific File Data Status Log.
Below is some code that will read a data file (named Data.csv) and log potential data line (record) errors into a List Interface object which is iterated through and displayed within the Console Window when the read is complete. There are also some small helper methods. Here is the code:
private void checkDataFile(String filePath) {
String ls = System.lineSeparator();
List<String> validationFailures = new ArrayList<>();
StringBuilder sb = new StringBuilder();
// 'Try With Resources' used here to auto-close reader.
try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
String line;
int lineCount = 0;
// Read the file line-by-line.
while ((line = reader.readLine()) != null) {
line = line.trim();
lineCount++;
if (lineCount == 1 || line.equals("")) {
continue;
}
sb.delete(0, sb.capacity()); // Clear the StringBuilder object
// Start the Status Log
sb.append("File Line Number: ").append(lineCount)
.append(" (\"").append(line).append("\")").append(ls);
// Split line into an Array based on a comma delimiter
// reguardless of the delimiter's spacing situation.
String[] lineParts = line.split("\\s{0,},\\s{0,}");
/* Validate each file line. Log any line that fails
any validation for any record column data into a
List Interface object named: validationFailures
*/
// Are there 4 Columns of data in each line...
if (lineParts.length < 4) {
sb.append("\t- Invalid Column Count!").append(ls);
// Which column is missing...
// *** You may need to add more conditions to suit your needs. ***
if (checkAccountIDs(lineParts[0]) && lineParts.length >= 2 && !checkAccountIDs(lineParts[1])) {
sb.append("\t- Either the 'Sender Account ID' or the "
+ "'ReceiverAccountID' is missing!").append(ls);
}
else if (lineParts.length >= 3 && !checkAmount(lineParts[2])) {
sb.append("\t- The 'Amount' value is missing!").append(ls);
}
else if (lineParts.length < 4) {
sb.append("\t- The 'Transfer Date' is missing!").append(ls);
}
}
else {
// Is SenderAccountID data valid...
if (!checkAccountIDs(lineParts[0])) {
sb.append("\t- Invalid Sender Account ID in column 1! (")
.append(lineParts[0].equals("") ? "Null" :
lineParts[0]).append(")");
if (lineParts[0].length() < 9) {
sb.append(" <-- Not Enough Or No Digits!").append(ls);
}
else if (lineParts[0].length() > 9) {
sb.append(" <-- Too Many Digits!").append(ls);
}
else {
sb.append(" <-- Not All Digits!").append(ls);
}
}
// Is ReceiverAccountID data valid...
if (!checkAccountIDs(lineParts[1])) {
sb.append("\t- Invalid Receiver Account ID in coloun 2! (")
.append(lineParts[1].equals("") ? "Null" :
lineParts[1]).append(")");
if (lineParts[1].length() < 9) {
sb.append(" <-- Not Enough Or No Digits!").append(ls);
}
else if (lineParts[1].length() > 9) {
sb.append(" <-- Too Many Digits!").append(ls);
}
else {
sb.append(" <-- Not All Digits!").append(ls);
}
}
// Is Amount data valid...
if (!checkAmount(lineParts[2])) {
sb.append("\t- Invalid Amount Value in column 3! (")
.append(lineParts[2].equals("") ? "Null" :
lineParts[2]).append(")").append(ls);
}
// Is TransferDate data valid...
if (!checkTransferDate(lineParts[3], "yyyy-MM-dd HH:mm:ss")) {
sb.append("\t- Invalid Transfer Date Timestamp in column 4! (")
.append(lineParts[3].equals("") ? "Null" :
lineParts[3]).append(")").append(ls);
}
}
if (!sb.toString().equals("")) {
validationFailures.add(sb.toString());
}
}
}
catch (FileNotFoundException ex) {
System.err.println(ex.getMessage());
}
catch (IOException ex) {
System.err.println(ex.getMessage());
}
// Display the Log...
String timeStamp = new SimpleDateFormat("yyyy/MM/dd - hh:mm:ssa").
format(new Timestamp(System.currentTimeMillis()));
String dispTitle = "File Data Status at " + timeStamp.toLowerCase()
+ " <:-:> (" + filePath + "):";
System.out.println(dispTitle + ls + String.join("",
Collections.nCopies(dispTitle.length(), "=")) + ls);
if (validationFailures.size() > 0) {
for (String str : validationFailures) {
if (str.split(ls).length > 1) {
System.out.println(str);
System.out.println(String.join("", Collections.nCopies(80, "-")) + ls);
}
}
}
else {
System.out.println("No Issues Detected!" + ls);
}
}
private boolean checkAccountIDs(String accountID) {
return (accountID.matches("\\d+") && accountID.length() == 9);
}
private boolean checkAmount(String amount) {
return amount.matches("-?\\d+(\\.\\d+)?");
}
private boolean checkTransferDate(String transferDate, String format) {
return isValidDateString(transferDate, format);
}
private boolean isValidDateString(String dateToValidate, String dateFromat) {
if (dateToValidate == null || dateToValidate.equals("")) {
return false;
}
SimpleDateFormat sdf = new SimpleDateFormat(dateFromat);
sdf.setLenient(false);
try {
// If not valid, it will throw a ParseException
Date date = sdf.parse(dateToValidate);
return true;
}
catch (ParseException e) {
return false;
}
}
I'm not exactly sure what your particular application process will ultimately entail but if other processes are accessing the file and making modifications to it then it may be wise utilize a locking mechanism to Lock the file during your particular process and Unlock the file when it is done. This however will most likely require you to utilize a different reading algorithm since locking a file must be done through a writable channel. Using the FileChannel and FileLock classes from the java.nio package could possibly assist you here. There would be examples of how to utilize these classes within the StackOverflow forum.

Change order of columns in a txt file

I have a txt file where some columns do not appear in every row but this causes the problem that in the rows where they appear they mess up the order of my columns:
35=d|5799=00000000|980=A|779=20190721173046000465|1180=310|1300=64|462=5|207=XCME|1151=ES|6937=ES|55=ESM0|48=163235|22=8|167=FUT|461=FFIXSX|200=202006|15=USD|1142=F|562=1|1140=3000|969=25.000000000|9787=0.010000000|996=IPNT|1147=50.000000000|1150=302775.000000000|731=00000110|5796=20190724|1149=315600.000000000|1148=285500.000000000|1143=600.000000000|1146=12.500000000|9779=N|864=2|865=5|1145=20190315133000000000|865=7|1145=20200619133000000000|1141=1|1022=GBX|264=10|870=1|871=24|872=00000000000001000010000000001111|1234=0|5791=279|5792=10121|
35=d|5799=00000000|980=A|779=20190721173046000465|1180=310|1300=64|462=5|207=XCME|1151=ES|6937=ES|55=ESU9|48=191262|22=8|167=FUT|461=FFIXSX|200=201909|15=USD|1142=F|562=1|1140=3000|969=25.000000000|9787=0.010000000|996=IPNT|1147=50.000000000|1150=302150.000000000|731=00000110|5796=20190724|1149=315700.000000000|1148=285600.000000000|1143=600.000000000|1146=12.500000000|9779=N|864=2|865=5|1145=20180615133000000000|865=7|1145=20190920133000000000|1141=1|1022=GBX|264=10|870=1|871=24|872=00000000000001000010000000001111|1234=0|5791=250519|5792=452402|
35=d|5799=00000000|980=A|779=20190721173046000465|1180=310|1300=64|462=5|207=XCME|1151=$E|6937=0ES|55=0ESQ9|48=229588|22=8|167=FUT|461=FFIXSX|200=201908|15=USD|1142=F|562=1|1140=3000|969=25.000000000|9787=0.010000000|996=IPNT|1147=50.000000000|1150=25.000000000|731=00000011|5796=20190607|1143=0.000000000|1146=12.500000000|9779=N|864=2|865=5|1145=20190621133000000000|865=7|1145=20190816133000000000|1141=1|1022=GBX|264=10|870=1|871=24|872=00000000000001000010000000001111|1234=0|
35=d|5799=00000000|980=A|779=20190721173114000729|1180=441|1300=56|462=16|207=DUMX|1151=1O|6937=OQE|55=OQEH4 C6100|48=1546|22=8|167=OOF|461=OCEFPS|201=1|200=202403|15=USD|202=6100.000000000|947=USD|9850=0.100000000|1142=F|562=1|1140=999|969=1.000000000|1146=10.000000000|9787=0.010000000|996=BBL|1147=1000.000000000|731=00000001|1148=0.100000000|9779=N|5796=20190718|864=2|865=5|1145=20181031213000000000|865=7|1145=20240126193000000000|1141=1|1022=GBX|264=3|870=1|871=24|872=00000000000001000000000100000101|1234=1|1093=4|1231=1.0000|711=1|309=211120|305=8|311=OQDH4|1647=0|
35=d|5799=00000000|980=A|779=20190721173115000229|1180=441|1300=56|462=16|207=DUMX|1151=1O|6937=OQE|55=OQEM4 C5700|48=2053|22=8|167=OOF|461=OCEFPS|201=1|200=202406|15=USD|202=5700.000000000|947=USD|9850=0.100000000|1142=F|562=1|1140=999|969=1.000000000|1146=10.000000000|9787=0.010000000|996=BBL|1147=1000.000000000|731=00000001|1148=0.100000000|9779=N|5796=20190718|864=2|865=5|1145=20181031213000000000|865=7|1145=20240425183000000000|1141=1|1022=GBX|264=3|870=1|871=24|872=00000000000001000000000100000101|1234=1|1093=4|1231=1.0000|711=1|309=329748|305=8|311=OQDM4|1647=0|
For example in the first three rows there always comes 461=… and then 200=… while starting from the 4th row between 461=… and 200=… there is 201=…
Now I thought of somehow moving every column which appears later which was not there in the first row to the end of the row so that it becomes the last column but I do not know how to do exactly this operation. Here is what I have tried:
private static void ladeDatei(String datName) {
File file = new File(datName);
if (!file.canRead() || !file.isFile())
System.exit(0);
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader(datName));
String row = null;
String row2 = null;
while ((row = in.readLine()) != null) {
System.out.println("Gelesene Zeile: " + row);
while(row.contains("|")) {
row2 = row.substring(row.indexOf("|") + 1);
row=row2;
row2 = row.substring(0, row.indexOf("=") + 1);
row2 = row2.replace("=", "");
if(!numbers.contains(row2)) {
numbers.add(row2);
}
System.out.println(row);
//System.out.println(row2);
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (in != null)
try {
in.close();
} catch (IOException e) {
}
}
}
I thought about splitting every row by | and save them in the textArr list but then I wouldn't know which rows belong together. My main problem is that I don't know a good way to check if the column exists in an earlier row and how to move it to the end of the row.
EDIT: Now I saved every new entry in the numbers arraylist (see my edit in the code above) but now I am stuck because I don't know how to shift them and all the ones which come after them to the end of each row.
That's a hell of a job. What I would do is:
(1) split the lines at |
(2) make a List where You append the numbers between | and = (append each new number at the end)
(3) make a Map where the line parts are mapped to the numbers in (2) as key
(4) make a second Map where the max-column-values of the line parts are mapped to the numbers in (2)
(5) read through the List from (2) joinig the associated line parts with | padded to the max-column-values
(if there is no line part for a specific number You must do the padding as well)
When ever possible — I would prefer to structure the line parts in a html-table.
The change of the column order will not solve the problem of broader or smaller colums.

Using Jackcess to retrieve numeric values stored in a text field gives ClassCastException

I am working with Jackcess to read and categorize an access database. It's simply meant to open the database, loop through each line, and print out individual row data to the console which meet certain conditions. It works fine, except for when I try to read numeric values. My code is below. (This code is built into a Swing GUI and gets executed when a jbutton is pressed.)
if (inv == null) { // Check to see if inventory file has been set. If not, then set it to the default reference path.
inv = rPath;
}
if (inventoryFile.exists()) { // Check to see if the reference path exists.
List<String> testTypes = jList1.getSelectedValuesList();
List<String> evalTypes = jList3.getSelectedValuesList();
List<String> grainTypes = jList2.getSelectedValuesList();
StringBuilder sb = new StringBuilder();
for (int i=0; i<=evalTypes.size()-1; i++) {
if (i<evalTypes.size()-1) {
sb.append(evalTypes.get(i)).append(" ");
}
else {
sb.append(evalTypes.get(i));
}
}
String evalType = sb.toString();
try (Database db = DatabaseBuilder.open(new File(inv));) {
Table sampleList = db.getTable("NTEP SAMPLES LIST");
Cursor cursor = CursorBuilder.createCursor(sampleList);
for (int i=0; i<=testTypes.size()-1; i++) {
if ("Sample Volume".equals(testTypes.get(i))) {
if (grainTypes.size() == 1 && "HRW".equals(grainTypes.get(0))) {
switch (evalType) {
case "GMM":
for (Row row : sampleList){
if (null != row.getString("CURRENTGAC")) {}
if ("HRW".equals(row.get("GRAIN")) && row.getDouble("CURRENTGAC")>=12.00) {
System.out.print(row.get("GRAIN") + "\t");
System.out.println(row.get("CURRENTGAC"));
}
}
break;
case "NIRT":
// some conditional code
break;
case "TW":
// some more code
break;
}
}
else {
JOptionPane.showMessageDialog(null, "Only HRW samples can be used for the selected test(s).", "Error", JOptionPane.ERROR_MESSAGE);
}
break;
}
}
}
catch (IOException ex) {
Logger.getLogger(SampleFilterGUI.class.getName()).log(Level.SEVERE, null, ex);
}
When the code is run I get the following error:
java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Double
The following condition looks to be what is throwing the error.
row.getDouble("CURRENTGAC")>=12.00
It appears that when the data is read from the database, the program is reading everything as a string, even though some fields are numeric. I was attempting to cast this field as a double, but java doesn't seem to like that. I have tried using the Double.parseDouble() and Double.valueOf() commands to try converting the value (as mentioned here) but without success.
My question is, how can I convert these fields to numeric values? Is trying to type cast the way to go, or is there a different method I'm not aware of? You will also notice in the code that I created a cursor, but am not using it. The original plan was to use it for navigating through the database, but I found some example code from the jackcess webpage and decided to use that instead. Not sure if that was the right move or not, but it seemed like a simpler solution. Any help is much appreciated. Thanks.
EDIT:
To ensure the program was reading a string value from my database, I input the following code
row.get("CURRENTGAC").getClass().getName()
The output was java.lang.String, so this confirms that it is a string. As was suggested, I changed the following code
case "GMM":
for (Row row : sampleList){
if (null != row.get("CURRENTGAC"))
//System.out.println(row.get("CURRENTGAC").getClass().getName());
System.out.println(String.format("|%s|", row.getString("CURRENTGAC")));
/*if ("HRW".equals(row.get("GRAIN")) && row.getDouble("CURRENTGAC")>=12.00 && row.getDouble("CURRENTGAC")<=14.00) {
System.out.print(row.get("GRAIN") + "\t");
System.out.println(row.get("CURRENTGAC"));
}*/
}
break;
The ouput to the console from these changes is below
|9.85|
|11.76|
|9.57|
|12.98|
|10.43|
|13.08|
|10.53|
|11.46|
...
This output, although looks numeric, is still of the string type. So when I tried to run it with my conditional statement (which is commented out in the updated sample code) I still get the same java.lang.ClassCastException error that I was getting before.
Jackcess does not return all values as strings. It will retrieve the fields (columns) of a table as the appropriate Java type for that Access field type. For example, with a test table named "Table1" ...
ID DoubleField TextField
-- ----------- ---------
1 1.23 4.56
... the following Java code ...
Table t = db.getTable("Table1");
for (Row r : t) {
Object o;
Double d;
String fieldName;
fieldName = "DoubleField";
o = r.get(fieldName);
System.out.println(String.format(
"%s comes back as: %s",
fieldName,
o.getClass().getName()));
System.out.println(String.format(
"Value: %f",
o));
System.out.println();
fieldName = "TextField";
o = r.get(fieldName);
System.out.println(String.format(
"%s comes back as: %s",
fieldName,
o.getClass().getName()));
System.out.println(String.format(
"Value: %s",
o));
try {
d = r.getDouble(fieldName);
} catch (Exception x) {
System.out.println(String.format(
"r.getDouble(\"%s\") failed - %s: %s",
fieldName,
x.getClass().getName(),
x.getMessage()));
}
try {
d = Double.parseDouble(r.getString(fieldName));
System.out.println(String.format(
"Double.parseDouble(r.getString(\"%s\")) succeeded. Value: %f",
fieldName,
d));
} catch (Exception x) {
System.out.println(String.format(
"Double.parseDouble(r.getString(\"%s\")) failed: %s",
fieldName,
x.getClass().getName()));
}
System.out.println();
}
... produces:
DoubleField comes back as: java.lang.Double
Value: 1.230000
TextField comes back as: java.lang.String
Value: 4.56
r.getDouble("TextField") failed - java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Double
Double.parseDouble(r.getString("TextField")) succeeded. Value: 4.560000
If you are unable to get Double.parseDouble() to parse the string values from your database then either
they contain "funny characters" that are not apparent from the samples you posted, or
you're doing it wrong.
Additional information re: your sample file
Jackcess is returning CURRENTGAC as String because it is a Text field in the table:
The following Java code ...
Table t = db.getTable("NTEP SAMPLES LIST");
int countNotNull = 0;
int countAtLeast12 = 0;
for (Row r : t) {
String s = r.getString("CURRENTGAC");
if (s != null) {
countNotNull++;
Double d = Double.parseDouble(s);
if (d >= 12.00) {
countAtLeast12++;
}
}
}
System.out.println(String.format(
"Scan complete. Found %d non-null CURRENTGAC values, %d of which were >= 12.00.",
countNotNull,
countAtLeast12));
... produces ...
Scan complete. Found 100 non-null CURRENTGAC values, 62 of which were >= 12.00.

How do I display a whole category from a text file?

I managed to display 1 record of the asked category but what i need is for the program to display everything from that category. If it's too vague the code might help. Thanks in advance
public static void SearchCatRecord() throws Exception
{
LoadFile();
System.out.println("\t\t\t*******************************");
System.out.println("\n\t\t\t---------SEARCH CATEGORIZED ITEM--------");
System.out.println("\n\t\t\t*******************************");
System.out.print("\t\t\tEnter Category: ");
String searchnum = br.readLine();
boolean found = false;
for(int i=0;i<row;i++)
{
String record[] = list.get(i).split(",");
String num = record[1];
if(searchnum.equals(num))
{
found = true;
System.out.println("\t\t\t*******************************");
System.out.println("\n\t\t\t---------RECORD FOUND----------");
System.out.println("\n\t\t\tProduct Number : "+record[0]);
System.out.println("\t\t\tCategory : "+record[1]);
System.out.println("\t\t\tProduct Name : "+record[2]);
System.out.println("\t\t\tPrice : "+record[3]);
System.out.println("\t\t\tQuantity : "+record[4]);
System.out.println("\n\t\t\t*******************************");
Thread.sleep(2000);
found = true;
System.out.println("\n\n\t\t\tSearch Completed");
exiting();
}
}
if(found == false)
{
System.out.println("\t\t\tNo Record Found");
System.out.println("\t\t\t*******************************");
exiting();
}
MainMenu();
}
The following code asks the user which category should the program display. then it displays the asked category but it only displays one record.
This is because you call exiting(); when you found the first record. You should remove it in your loop.
for example:
for(int i=0;i<row;i++)
{
String record[] = list.get(i).split(",");
String num = record[1];
if(searchnum.equals(num))
{
found = true;
System.out.println("\t\t\t*******************************");
System.out.println("\n\t\t\t---------RECORD FOUND----------");
System.out.println("\n\t\t\tProduct Number : "+record[0]);
System.out.println("\t\t\tCategory : "+record[1]);
System.out.println("\t\t\tProduct Name : "+record[2]);
System.out.println("\t\t\tPrice : "+record[3]);
System.out.println("\t\t\tQuantity : "+record[4]);
System.out.println("\n\t\t\t*******************************");
Thread.sleep(2000);
}
}
System.out.println("\n\n\t\t\tSearch Completed");
if(found == false)
{
System.out.println("\t\t\tNo Record Found");
System.out.println("\t\t\t*******************************");
}
exiting();
If you want to find all the records then you should not breakout after finding one record that meets your criteria. I believe your method invocation exiting() is not needed in loop.
On a side note why are you setting found=true twice in the loop? Also what is the need of Thread.sleep(2000) in the code?

ConcurrentModificationException when edting the data in the arraylist to text file

private void btnOKActionPerformed(java.awt.event.ActionEvent evt)
{
try
{
if(txtStaffID.getText(0, 2).equals("AD"))
{
for(Admin admin:admincontrolpanel.adminList)
{
if(txtUsername.getText().equals("") || txtPassword.getText().equals("") || txtName.getText().equals("") || txtEmail.getText().equals("") || txtContactNumber.getText().equals("") || txtICNumber.getText().equals(""))
{
JOptionPane.showMessageDialog(null, "Please fill in the blank", "ERROR", JOptionPane.ERROR_MESSAGE);
}
else if(txtUsername.getText() != null && txtPassword.getText() != null && txtName.getText() != null && txtEmail.getText() != null && txtContactNumber.getText() != null && txtICNumber.getText() != null)
{
admin.setId(txtStaffID.getText());
admin.setUsername(txtUsername.getText());
admin.setPassword(txtPassword.getText());
admin.setName(txtName.getText());
admin.setEmail(txtEmail.getText());
admin.setContactNumber(txtContactNumber.getText());
admin.setIcNumber(txtICNumber.getText());
Admin newAdmin = new Admin(admin.getId(),admin.getUsername(),admin.getPassword(),admin.getName(),admin.getEmail(),admin.getContactNumber(),admin.getIcNumber());
admincontrolpanel.adminList.remove(admin);
admincontrolpanel.adminList.add(newAdmin);
}
}
JOptionPane.showMessageDialog(null, "Successfully Added!", "Add Staff", JOptionPane.PLAIN_MESSAGE);
dispose();
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
Inside the text file got these data...
AD001|jeff|jeff|jeff|jeff#gmail.com|123456|123456
AD002|admin|admin|admin|admin#gmail.com|123456|123456
When I press OK button to edi...it shows me this ConcurrentModificationException error....Anyone can help me to take a look of it??
Admin is the class...adminList is the arraylist...
try
{
PrintWriter pw = new PrintWriter("Admin.txt");
for(Admin admin:admincontrolpanel.adminList)
{
pw.println(admin.getId() + "|" + admin.getUsername() + "|" + admin.getPassword() + "|" + admin.getName() + "|" + admin.getEmail() + "|" + admin.getContactNumber() + "|" + admin.getIcNumber());
}
pw.close();
}
catch(Exception e)
{
e.printStackTrace();
}
This is the code i want to write into the text file from arraylist....
then it gave me this kind of data inside the arraylist...can edit it..but deleted the 1st data and add a new data into it
AD002|admin|admin|admin|admin#gmail.com|123456|123456
AD002|admin|admin|admin|admin#gmail.com|999|123456
A quick search through SO would have quickly shown you possible solutions..you can use a standard for loop and loop until the previous list's size, instead of using an implicit Iterator the way you are:
ArrayList<Admin> = admincontrolpanel.adminList;
int adminListSize = adminList.size();
for(int i=0;i<adminListSize;i++) {
Admin admin = adminList.get(i);
Or you can use a ListIterator to loop through the list using an Iterator and modify it.
Also, admincontrolpanel is not a good variable name. Use camelCase.
for(Admin admin:admincontrolpanel.adminList)
Through this loop you are iterating adminList(ArrayList)
Admin newAdmin = new Admin(admin.getId(),admin.getUsername(),admin.getPassword(),admin.getName(),admin.getEmail(),
admin.getContactNumber(),admin.getIcNumber());
admincontrolpanel.adminList.remove(admin);
admincontrolpanel.adminList.add(newAdmin);
above in last two line you are removing and adding ArrayList item which is not allowed here because you already iterating ArrayList. you can not do iterating and modifying ArrayList at the same time here. thats why you are facing Concurrent..exception.
This problem may occur due to thread inside another thread. For example if your are executing some code in your first thread and along this you have another thread inside this thread. then this problem occur.

Categories