Java retrieving object from array - java

I'm having an issue fetching an object from an array of said Object. My code is below. I'm basically trying to build a table and fill in the columns with the data from each object. However currently the table is just showing the object and not the data. See picture:
Table:
public void buildTable(JPanel panel) {
File file = new File("C:\\Users\\user\\Desktop\\test.txt");
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
lineArray = new ArrayList<Person[]>();
while((line = br.readLine()) != null) {
String[] temp = line.split("\\t");
Person p = new Person(temp[0], temp[1], temp[2], temp[3], temp[4], temp[5], temp[6], temp[7], temp[8]);
lineArray.add(new Person[]{p});
}
br.close();
} catch (FileNotFoundException e) { e.printStackTrace();}
catch (IOException e) { e.printStackTrace(); }
List<String> columns = new ArrayList<String>();
final List<Person[]> values = new ArrayList<Person[]>();
columns.add("First Name");
columns.add("Last Name");
columns.add("Address");
columns.add("Address 2");
columns.add("City");
columns.add("State");
columns.add("Zip Code");
columns.add("Phone");
columns.add("Email");
for (int i = 0; i < lineArray.size(); i++) {
values.add(lineArray.get(i)); //this is the line where I'm guessing the main problem is
}
TableModel tableModel = new DefaultTableModel(values.toArray(new Object[][] {}), columns.toArray());
final JTable table = new JTable(tableModel);
JScrollPane tableContainer = new JScrollPane(table);
tableContainer.setBounds(10, 36, 833, 219);
panel.add(tableContainer);
table.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
int selectedRow = table.convertRowIndexToModel(table.getSelectedRow());
contactName.setText((String) table.getValueAt(selectedRow, 0) + " " + table.getValueAt(selectedRow, 1));
contactAddress.setText((String) table.getValueAt(selectedRow, 2));
}
});
}
Object Class:
public class Person {
public String firstName;
public String lastName;
public String address;
public String address2;
public String city;
public String state;
public String zip;
public String phone;
public String email;
public Person(String firstName, String lastName, String address, String address2, String city, String state, String zip, String phone, String email) {
this.firstName = firstName;
this.lastName = lastName;
this.address = address;
this.address2 = address2;
this.city = city;
this.state = state;
this.zip = zip;
this.phone = phone;
this.email = email;
}
}

To solve your problem, you need only ONE ArrayList of Person (and not of array of Person), and you don't need the value ArrayList.
What you need instead is some method that create an array of arrays representing a table containing your data, in fact an array of arrays of Strings. The problem is the 'columns' of the table are actually the fields of the Person class. I'm not sure if my solution (below) is the best, probably you can solve this problem also dealing with the reflection.
Anyway, this works (I tried to modify least as possible your code or to simplify it):
public void buildTable(JPanel panel) throws IOException {
File file = new File("C:\\Users\\user\\Desktop\\test.txt");
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
lineArray = new ArrayList<Person>();
while ((line = br.readLine()) != null) {
String[] temp = line.split(",");
Person p = new Person(temp[0], temp[1], temp[2], temp[3], temp[4], temp[5], temp[6], temp[7], temp[8]);
lineArray.add(p);
}
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
List<String> columns = new ArrayList<String>();
columns.add("First Name");
columns.add("Last Name");
columns.add("Address");
columns.add("Address 2");
columns.add("City");
columns.add("State");
columns.add("Zip Code");
columns.add("Phone");
columns.add("Email");
TableModel tableModel = new DefaultTableModel(Person.toStringsMatrix(lineArray), columns.toArray());
final JTable table = new JTable(tableModel);
JScrollPane tableContainer = new JScrollPane(table);
tableContainer.setBounds(10, 36, 833, 219);
panel.add(tableContainer);
}
And the Person class:
class Person {
public String firstName;
public String lastName;
public String address;
public String address2;
public String city;
public String state;
public String zip;
public String phone;
public String email;
public Person(String firstName, String lastName, String address, String address2, String city, String state, String zip, String phone, String email) {
this.firstName = firstName;
this.lastName = lastName;
this.address = address;
this.address2 = address2;
this.city = city;
this.state = state;
this.zip = zip;
this.phone = phone;
this.email = email;
}
public String[] toStrings() {
return new String[]{firstName, lastName, address, address2, city, state, zip, phone, email};
}
public static String[][] toStringsMatrix(ArrayList<Person> personList) {
int rows = personList.size();
String[] first = personList.get(0).toStrings();
int columns = first.length;
String[][] table = new String[rows][columns];
table[0] = first;
for (int k = 1; k < rows; k++) {
table[k] = personList.get(k).toStrings();
}
return table;
}
}
I hope this will help you.

Try adding a array of strings to your lineArray instead of Person objects.
lineArray.add(new String[]{temp[0], temp[1], temp[2], temp[3], temp[4], temp[5], temp[6], temp[7], temp[8]});

Related

Why is FileReader not reading beyond the end of the first line?

I'm trying to read in data from a text file using FileReader. There are four lines of text. Each line has the same attribute types (first name, last name, dob, ssn, etc.). I am trying to split the data read in by the " " delimiter into one long array and then assign the values to a record ArrayList. My logic (if you can even call it that), is that by doing this I'd have one giant array of String data which I could then assign to each of the record's 7 fields - 0-6 for the first record, 7-13 for the second record, 14-20 for the third... But it looks like my while loop is stopping at the end of line one. I feel really stupid here, but I cannot figure out how to get this to work. And yes, I know, there is a lot that is bad form in my code, but I'm just trying to get a feel for the functionality. Any advice here would be most appreciated. Thank you!
The text file looks like this:
John Smith 1996.03.07 123-45-6789 Chickenpox BedRest aspirin
Joe Blow 1996.03.07 123-45-6888 Smallpox BedRest Whiskey
Julie Wilson 1996.03.07 123-45-6999 Insomnia Exercise HotPeppers
Wayne Blaine 1942.07.07 123-45-6777 Measles WaitToGetBetter CodLiverOil
Here's my main.
public static void main(String [] args) throws Exception {
String line = "";
BlockRecord record0 = null;
BlockRecord record1 = null;
BlockRecord record2 = null;
BlockRecord record3 = null;
try {
ArrayList<String> data = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new FileReader("BlockInput0.txt"));
while((line = reader.readLine()) != null) {
System.out.println(line);
data.add(line);
}
record0 = new BlockRecord();
record1 = new BlockRecord();
record2 = new BlockRecord();
record3 = new BlockRecord();
record0.setBlockID(new String(UUID.randomUUID().toString()));
record1.setBlockID(new String(UUID.randomUUID().toString()));
record2.setBlockID(new String(UUID.randomUUID().toString()));
record3.setBlockID(new String(UUID.randomUUID().toString()));
//manually set until more functionality is in place
data = line.split(" ");
record0.setFirstName(data[0]);
record0.setLastName(data[1]);
record0.setDob(data[2]);
record0.setSsn(data[3]);
record0.setDiagnosis(data[4]);
record0.setTreatment(data[5]);
record0.setRx(data[6]);
record1.setFirstName(data[7]);
record1.setLastName(data[8]);
record1.setDob(data[9]);
record1.setSsn(data[10]);
record1.setDiagnosis(data[11]);
record1.setTreatment(data[12]);
record1.setRx(data[13]);
record2.setFirstName(data[14]);
record2.setLastName(data[15]);
record2.setDob(data[16]);
record2.setSsn(data[17]);
record2.setDiagnosis(data[18]);
record2.setTreatment(data[19]);
record2.setRx(data[20]);
record3.setFirstName(data[21]);
record3.setLastName(data[22]);
record3.setDob(data[23]);
record3.setSsn(data[24]);
record3.setDiagnosis(data[25]);
record3.setTreatment(data[26]);
record3.setRx(data[27]);
}
}catch(Exception e) {
e.printStackTrace();
}
}
Here's my BlockRecord class:
class BlockRecord{
String firstName;
String lastName;
String ssn;
String dob;
String diagnosis;
String treatment;
String rx;
String seed;
String winner;
String blockID;
String previousHash;
String verificationID = "0";
String uuid = UUID.randomUUID().toString();
String winningHash;
public static KeyPair keyPair;
public static int recordCount;
public String getWinningHash() {
return winningHash;
}
public void setWinningHash(String winningHash) {
this.winningHash = winningHash;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getSsn() {
return ssn;
}
public void setSsn(String ssn) {
this.ssn = ssn;
}
public String getDob() {
return dob;
}
public void setDob(String dob) {
this.dob = dob;
}
public String getDiagnosis() {
return diagnosis;
}
public void setDiagnosis(String diagnosis) {
this.diagnosis = diagnosis;
}
public String getTreatment() {
return treatment;
}
public void setTreatment(String treatment) {
this.treatment = treatment;
}
public String getRx() {
return rx;
}
public void setRx(String rx) {
this.rx = rx;
}
public String getSeed() {
return seed;
}
public void setSeed(String seed) {
this.seed = seed;
}
public String getWinner() {
return winner;
}
public void setWinner(String winner) {
this.winner = winner;
}
public String getBlockID() {
return blockID;
}
public void setBlockID(String blockID) {
this.blockID = blockID;
}
public String getPreviousHash() {
return previousHash;
}
public void setPreviousHash(String previousHash) {
this.previousHash = previousHash;
}
public String getVerificationID() {
return verificationID;
}
public void setVerificationID(String verificationID) {
this.verificationID = verificationID;
}
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
}
You read all the lines and add each on them to the list data in the loop:
while((line = reader.readLine()) != null) {
System.out.println(line);
data.add(line);
}
But then, you only split line, which is the last read line.
data = line.split(" ");
Quick fix:
Merge all the lines into one. Then split it.
String mergedLines = "";
while((line = reader.readLine()) != null) {
System.out.println(line);
mergedLines = mergedLines + line;
}
This is really dirty and uneffective as the file already provides separated records.
Better solution:
Create a BlockRecordfor each line without merging them. Then store the record in a list.
ArrayList<BlockRecord> allRecords = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new FileReader("BlockInput0.txt"));
while((line = reader.readLine()) != null) {
System.out.println(line);
data = line.split(" ");
BlockRecord record = new BlockRecord()
record.setFirstName(data[0]);
record.setLastName(data[1]);
record.setDob(data[2]);
record.setSsn(data[3]);
record.setDiagnosis(data[4]);
record.setTreatment(data[5]);
record.setRx(data[6]);
allRecords.add(record)
}
This way, you don't even have to know how many records to declare before reading

How do you make a CSV file take in more than one user

I successfully created a csv file from the data that I inputted into the textfields, but the problem is that it will only take in one user. I know the problem is that I didn't make my write method static but I can't figure out way a to transfer the data stored in the variable to the csv file without making not static.
public class newUserController {
//private ResourceBundle resources;
public Button continues;
public Button save;
public TextField tf_username;
public PasswordField pf_password;
public TextField tf_name;
public ComboBox<?> dd_selectGender;
public TextField tf_email;
public TextField tf_age;
public TextField tf_height;
public ComboBox<?> dd_measurment;
public void savePressed(ActionEvent event) throws IOException{
String username = tf_username.getText();
String password = pf_password.getText();
String name = tf_name.getText();
String gender = (String) dd_selectGender.getValue();
String email = tf_email.getText();
String age =tf_age.getText();
String height=tf_height.getText();
String measurment = (String) dd_measurment.getValue();
CSVBuilder csv = new CSVBuilder(username,password,name,gender,email,age,height,measurment);
}
public void continuePressed(ActionEvent event) throws IOException{
Parent menu = FXMLLoader.load(getClass().getResource("Menu Overview.fxml"));
Scene menuScene = new Scene(menu);
Stage window =(Stage)((Node)event.getSource()).getScene().getWindow();
window.setScene(menuScene);
window.show();
}
}
public class CSVBuilder {
String username;
String password;
String name;
String gender;
String email;
String age;
String height;
String measurement;
CSVBuilder(String user, String pass, String nam, String gen, String e_mail, String ag, String hei, String measur){
username = user;
password = pass;
name = nam;
gender = gen;
email = e_mail;
age = ag;
height = hei;
measurement = measur;
String filePath = "C:\\Users\\vargh\\eclipse-workspace\\Java\\FitLog.csv";
writeCsv(filePath);
}
//technically should be static
public void writeCsv(String filePath) {
//create demo Users
List<User> users= new ArrayList<User>();
User user = new User(username,password,name,gender,email,age,height,measurement);
users.add(user);
FileWriter fileWriter = null;
try {
fileWriter = new FileWriter(filePath);
fileWriter.append("Username, Password, Name, Gender, E-Mail, Age, Height, Measurement\n");
for(User u: users) {
fileWriter.append(String.valueOf(u.getUsername()));
fileWriter.append(",");
fileWriter.append(u.getPassword());
fileWriter.append(",");
fileWriter.append(u.getName());
fileWriter.append(",");
fileWriter.append(u.getGender());
fileWriter.append(",");
fileWriter.append(u.getEmail());
fileWriter.append(",");
fileWriter.append(u.getAge());
fileWriter.append(",");
fileWriter.append(u.getHeight());
fileWriter.append(",");
fileWriter.append(u.getMeasurement());
fileWriter.append("\n");
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
fileWriter.flush();
fileWriter.close();
}catch (Exception e) {
e.printStackTrace();
}
}
}
}
public class User {
String username;
String password;
String name;
String gender;
String email;
String age;
String height;
String measurement;
User(String user, String pass, String nam, String gen, String e_mail, String ag, String hei, String measur){
username = user;
password = pass;
name = nam;
gender = gen;
email = e_mail;
age = ag;
height = hei;
measurement = measur;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
public String getName() {
return name;
}
public String getGender() {
return gender;
}
public String getEmail() {
return email;
}
public String getAge() {
return age;
}
public String getHeight() {
return height;
}
public String getMeasurement() {
return measurement;
}
}
You're only adding 1 user, right?
List<User> users= new ArrayList<User>();
User user = new User(username,password,name,gender,email,age,height,measurement);
users.add(user);
Also, would call attention to:
CSVBuilder csv = new CSVBuilder(username,password,name,gender,email,age,height,measurment);
Would suggest refactoring that into a List of Users as such:
CSVBuilder(List<User> users){
this.users = users;
}
and then you can invoke it with something like:
List<User> users= new ArrayList<>();
User user = new User("username-1","password-1","alice","f","email#xyz.com","20","","");
users.add(user);
User user2 = new User("username-2","password-2","bob","m","email#abc.com","21","","");
users.add(user2);
CSVBuilder csvBuilder = new CSVBuilder(users);
csvBuilder.writeCsv("FitLog.csv");
Producing the output:
Username, Password, Name, Gender, E-Mail, Age, Height, Measurement
username-1,password-1,alice,f,email#xyz.com,20,,
username-2,password-2,bob,m,email#abc.com,21,,
Would also suggest FileWriter(File, boolean) since it seems like you may be trying to append to the file with a new user / click. Default option doesn't append, but overwrites.

Java Isolate comma seperated values in text file

I've been searching for a solution to my problem without any luck. So now I'm asking here for help.
I'm creating "Groups" by the following class:
public class Group {
private String groupID;
private ArrayList<User> usersInGroup;
The User class looks like this:
NOTE: I already have an ArrayList containing all existing Users.
public class User {
private String firstName;
private String lastName;
private String age;
private String gender;
private String usernameID;
private String password;
I'm already adding the groupID field from the "groupData.txt" CSV text file like this:
public static ArrayList<Group> listOfCreatedGroups() throws IOException {
ArrayList<Group> listOfGroups = new ArrayList<>();
FileReader fr = new FileReader("src/groupData.txt");
BufferedReader bfr = new BufferedReader(fr);
String line;
int totalLine = Destination.linesInFile("src/groupData.txt"); //total lines in file
for (int i = 0; i < totalLine; i++) {
line = bfr.readLine();
String[] groupID = line.split(",");
Group temp = new Group();
temp.setGroupID(groupID[0]);
listOfGroups.add(temp);
}
try {
bfr.close();
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
return listOfGroups;
}
The "groupData.txt" file is structured like this:
Line example = groupID,String_1,String2,String3 ... Stringn,\n
groupid,user,user,user,user,user,user,user,
groupid,user,user,user,
groupid,user,user,user,user,user
groupid,user,user
groupid,user,user,user,user
Since I only have the number of users in every group User.usernameID as 1 to n strings in the text file I can't add the whole User object to the Arraylist usersInGroup.
I somehow need to isolate the usernameID's and find the corresponding Users and add them to the ArrayList usersInGroup.
I hope any of you can give me a hint in the right direction. Thanks.
I don't know if this is how you were wanting because I didn't find the user data very specific or even mentioned of how you wanted. But let me know if this is enough
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
public class Group {
private static String groupID;
private static ArrayList<User> usersInGroup = new ArrayList<User>();
public static void main (String [] args) throws IOException {
addListToGroup(readFile());
}
public static void addListToGroup(ArrayList<ArrayList<String>> list) {
for (int i = 0; i < list.size(); i++) {
groupID = list.get(i).get(0);
for (int x = 0; x < list.get(i).size(); x++) {
User temp = new User(); // change this to however you setup the txt file
// the information from the list is in list.get(i).get(x) in order as in the textfile
temp.setAge(null);
temp.setFirstName(null);
temp.setGender(null);
temp.setLastName(null);
temp.setPassword(null);
temp.setUsernameID(null);
usersInGroup.add(temp);
}
}
}
public static ArrayList<ArrayList<String>> readFile() throws IOException {
List<String> temp = new ArrayList<String>();
Path path = Paths.get("file.txt");
temp = Files.readAllLines(path);
ArrayList<ArrayList<String>> lines = new ArrayList<ArrayList<String>>();
for (int i = 0; i < temp.size(); i++) {
String [] s = temp.get(i).split(",");
ArrayList<String> quickArray = new ArrayList<String>();
for (int x=0; x < s.length; x++) {
quickArray.add(s[x]);
}
lines.add(quickArray);
}
return lines;
}
}
class User {
private String firstName;
private String lastName;
private String age;
private String gender;
private String usernameID;
private String password;
//setters and getters
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getUsernameID() {
return usernameID;
}
public void setUsernameID(String usernameID) {
this.usernameID = usernameID;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}

Prevent adding duplicate data into JTable in Java

How to prevent adding duplicate data into Jtable.
This is my code.
try {
URL url = new URL("http://localhost:8080/webservice/rest/bdetails/get");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
String json = "";
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
json += output;
}
conn.disconnect();
java.lang.reflect.Type listType = new TypeToken<ArrayList<BDetails>>() {
}.getType();
List<BDetails> bList = new Gson().fromJson(json, listType);
for( BDetails adr : bList)
{
DefaultTableModel model = (DefaultTableModel) pTable.getModel();
Vector<String> row = new Vector<String>();
row.add(detail.getUserName());
row.add(detail.getFirstName());
row.add(detail.getLastName());
row.add(detail.getAddress();
model.addRow( row );
}
} catch (IOException | RuntimeException ex) {
System.out.println(ex);
}
When I run this method It add data to the table. When I run again It add same data to the table. And again it do the same. How can I fix that? Can anybody help me? Thanks in advance. Below I have added the BDetails Class.
BDetails Class
public class BDetails
{
private String username;
private String firstName;
private String lastName;
private String address;
public BDetails() {
}
public BDetails(String username, String firstName, String lastName, String address) {
this.username = username;
this.firstName = firstName;
this.lastName = lastName;
this.address = address;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
You can try this,
java.lang.reflect.Type listType = new TypeToken<ArrayList<BDetails>>() {
}.getType();
List<BDetails> bList = new Gson().fromJson(json, listType);
DefaultTableModel model = (DefaultTableModel) pTable.getModel();
model.setRowCount(0);
for( BDetails adr : bList)
{
Vector<String> row = new Vector<String>();
row.add(detail.getUserName());
row.add(detail.getFirstName());
row.add(detail.getLastName());
row.add(detail.getAddress();
model.addRow( row );
}
model.setRowCount(0) will clear all the rows before inserting data. It worked for me.
First, I took BDetails and used Netbeans to add the equals and hashcode methods. This is important, as it provides away to assess if two instances of an object are the same
public class BDetails {
private String username;
private String firstName;
private String lastName;
private String address;
public BDetails() {
}
public BDetails(String username, String firstName, String lastName, String address) {
this.username = username;
this.firstName = firstName;
this.lastName = lastName;
this.address = address;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
#Override
public int hashCode() {
int hash = 7;
hash = 13 * hash + Objects.hashCode(this.username);
hash = 13 * hash + Objects.hashCode(this.firstName);
hash = 13 * hash + Objects.hashCode(this.lastName);
hash = 13 * hash + Objects.hashCode(this.address);
return hash;
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final BDetails other = (BDetails) obj;
if (!Objects.equals(this.username, other.username)) {
return false;
}
if (!Objects.equals(this.firstName, other.firstName)) {
return false;
}
if (!Objects.equals(this.lastName, other.lastName)) {
return false;
}
if (!Objects.equals(this.address, other.address)) {
return false;
}
return true;
}
}
I then create a custom TableModel (I'm bias, but I don't have much love for DefaultTableModel and it makes the next step easier)
public class BDetailsTableModel extends AbstractTableModel {
private List<BDetails> rows;
private String[] columnNames = {"User name", "First name", "Last Name", "Address"};
public BDetailsTableModel(List<BDetails> rows) {
this.rows = rows;
}
#Override
public int getRowCount() {
return rows.size();
}
#Override
public String getColumnName(int column) {
return columnNames[column];
}
#Override
public int getColumnCount() {
return 4;
}
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
BDetails details = rows.get(rowIndex);
switch (columnIndex) {
case 0:
return details.getUsername();
case 1:
return details.getFirstName();
case 2:
return details.getLastName();
case 3:
return details.getAddress();
}
return null;
}
}
And finally...
List<BDetails> bList = new Gson().fromJson(json, listType);
//for (BDetails adr : bList) {
// DefaultTableModel model = (DefaultTableModel) pTable.getModel();
// Vector<String> row = new Vector<String>();
// row.add(detail.getUserName());
// row.add(detail.getFirstName());
// row.add(detail.getLastName());
// row.add(detail.getAddress();
// model.addRow(row);
//}
Set<BDetails> unquie = new HashSet<>(bList);
List<BDetails> rows = new ArrayList<>(unquie);
BDetailsTableModel model = new BDetailsTableModel(rows);
pTable.setModel(model);
Okay, all this does is adds the bList to Set, this will remove all duplicates from the list for us (using the hashcode of the objects), add the results to a ArrayList (because it has a get method) and then supplies that to our BDetailsTableModel
Now, if you don't want to replace the TableModel each time, but instead, add the results it becomes a little more difficult, as you need to manage the possibility that the new set of data might contain duplicates of the old set.
You could add the following to BDetailsTableModel...
public void add(BDetails details) {
int rowCount = getRowCount();
if (rows.contains(details)) {
return;
}
rows.add(details);
fireTableRowsInserted(rowCount, rowCount);
}
public void addAll(List<BDetails> newRows) {
Set<BDetails> rows = new HashSet<>(newRows);
addAll(rows);
}
public void addAll(Set<BDetails> newRows) {
Set<BDetails> allRows = new HashSet<>(rows);
allRows.addAll(newRows);
rows = new ArrayList<>(allRows);
fireTableDataChanged();
}
and instead of creating a new instance of BDetailsTableModel, simply use the existing instance (from pTable) and use the above functionality to add new rows

Reading contents of a file into class objects

I have a text file of employee entries as follows:
000, first name1, middle name1
001, first name2, middle name2
002, first name3, middle name3
003, first name4, middle name4
004, first name5, middle name5
And I have a class Employee as follows:
public class Employee {
public int id;
public String fName;
public String mName;
public String lName;
}
I've read the contents of the file into an array. But what I want is to construct an array of objects of class Employee, and a way for each attribute of the class to be initialised with each entry. Something like this:
Employee e[] = new Employee[5];
Checking the details of each object in the array...
e[0].id = 000
e[0].fName = "first name1"
e[0].mName = "middle name1"
e[0].lName = "last name1"
Then,
e[1].id = 001
And so on...
Is there any way I can do this?
public class Employee {
public int id;
public String fName;
public String mName;
public String lName;
public Employee(String line) {
String[] split = line.split(",");
id = Integer.parseInt(split[0]);
fName = split[1];
mName = split[2];
lName = split[3];
}
}
Since you already read the file into array (of string I suppose).
String[] lines = ....;
Employee[] employees = new Employee[lines.length];
for(int i = 0; i < lines.length; i++) {
employees[i] = new Employee(lines[i]);
}
There you go... you have an array of employees.
Read the file and loop over its content line by line. Then parse the lines and create a new Employee() in each iteration. Set your values, such as id and name. Finally, add your new Employee instance to a List<Employee> and continue with the next entry.
// Read data from file
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
// List to collect Employee objects
List<Employee> employees = new ArrayList<Employee>();
// Read file line by line
String line = "";
while ((line = br.readLine()) != null) {
// Parse line to extract individual fields
String[] data = this.parseLine(line);
// Create new Employee object
Employee employee = new Employee();
employee.id = Integer.valueOf(data[0]);
employee.fName = data[1];
employee.mName = data[2];
// Add object to list
employees.add(employee);
}
// Further process your Employee objects...
}
Also, there are CSV libraries that can handle all the nasty parts of reading a file that has comma separated values. I'd suggest using OpenCSV, for example.
Here already answers posted but I still gonna post mine...
package com.stackoverflow.java.test;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class Employee {
public int id;
public String fName;
public String mName;
public Employee(int id, String fName, String mName) {
this.id = id;
this.fName = fName;
this.mName = mName;
}
public static void main(String[] args) throws IOException {
Employee[] e = new Employee[5];
FileReader fr=new FileReader("YourDoc.txt");
BufferedReader br=new BufferedReader(fr);
String line="";
String[] arrs=null;
int num=0;
while ((line=br.readLine())!=null) {
arrs=line.split(",");
e[num] = new Employee(Integer.valueOf(arrs[0]), arrs[1], arrs[2]);
num++;
}
br.close();
fr.close();
for(int i=0 ; i< e.length; i++) {
System.out.println(e[i].id + " and " + e[i].fName + " and " + e[i].mName);
}
}
}
try :
public static void main(String[] args) throws IOException {
File f1 = new File("d:\\data.txt");
Scanner scanner = new Scanner(f1);
List<Employee1> empList=new ArrayList<>();
while(scanner.hasNextLine()){
String data[]=scanner.nextLine().split(",");
empList.add(new Employee(Integer.parseInt(data[0]),data[1],data[2],data[3]));
}
scanner.close();
System.out.println(empList);
}
Employee.java
class Employee{
public int id;
public String fName;
public String mName;
public String lName;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getfName() {
return fName;
}
public void setfName(String fName) {
this.fName = fName;
}
public String getmName() {
return mName;
}
public void setmName(String mName) {
this.mName = mName;
}
public String getlName() {
return lName;
}
public void setlName(String lName) {
this.lName = lName;
}
public Employee(int id, String fName, String mName, String lName) {
super();
this.id = id;
this.fName = fName;
this.mName = mName;
this.lName = lName;
}
#Override
public String toString() {
return "Employee [id=" + id + ", fName=" + fName + ", mName="
+ mName + ", lName=" + lName + "]";
}
}

Categories

Resources