Passing value to another class in java - java

I have a problem in passing the value of input of user to another class. This is a webservice that's why i don't know how i will fix it and this is my first time to encounter wevservice. This is my code in getting the input of user.
PlateNumberCheck.java
//PATH FOR CHECKING PLATE NUMBER
#Path("platecheck") //for the url
public class PlateNumberCheck {
public String anss;
#GET
//To get the full url : http://Ipaddress:portnumber/#path/#getPath
#Path("/check")
#Produces(MediaType.APPLICATION_JSON)
//Produces is for the response of JSON.
public String check(#QueryParam("taxi_plate_no") String taxi_plate_no){
String sagot = "";
anss = taxi_plate_no;
if(checkInput(taxi_plate_no)){
display();
sagot = JsonConstruction.JSONResponse("checked", true);
} else{
sagot = JsonConstruction.JSONResponse("checked", false, "Not in the database");
}
return sagot;
}
private boolean checkInput (String taxi_plate_no){
System.out.println("Check Input");
boolean output = false;
if(JsonConstruction.isNotNull(taxi_plate_no)){
try{
output = DatabaseConnection.checkPlate(taxi_plate_no);
} catch (Exception e){
output = false;
}
} else{
output = false;
}
return output;
}
public void display(){
System.out.println(anss);
}
}
I think this class works. because as you can see i use the method first before it success and the method contains system.out.print which prints the input in console. This is my second class which i want to pass the input to this class.
DisplayTaxiDetails.java
#Path("/displays")
public class DisplayTaxiDetails {
String plates;
#GET
#Path("taxidetails")
#Produces(MediaType.APPLICATION_JSON)
public String taxidetails (){
String taxidetails = null;
ArrayList<Objects> taxiDetailsList = new ArrayList<Objects>();
try{
PlateNumberCheck plate = new PlateNumberCheck();
plates = plate.anss;
taxiDetailsList = new ArrayConnection().getTaxiDetails(plates);
System.out.println(plates);
Gson gson = new Gson();
taxidetails = gson.toJson(taxiDetailsList);
} catch (Exception e){
e.printStackTrace();
}
return taxidetails;
}
}
As you can see i call the first class and access the anss which is the string of that class where the input was stored. but when i access it and try to pass value it doesn't work. I use again system.out.print to see if it prints the data but it always shows null which i think the value from first class is not passed to the variable of this second class.

You need to understand the basics of java runtime environment. That'll explain how your objects bind with each other and can interact with each other. In your case, you are creating a new instance of PlateNumberCheck every time your method in second class is getting called.
PlateNumberCheck plate = new PlateNumberCheck();
For that instance, you don't have any value set in the anss field (by the way, this is also not correct way, but that's for later) as this instance has just got created.

Related

How to load a text file, add it to an array and change it into an object?

I am creating a program to display restaurant reviews which are saved in a text file. The text file is read in via the DAOimpl class as shown.
public class DAOlmpl implements DAOInterface {
static final char DELIMITER=',';
/**#Override*/
public Repository load(String filename) {
Repository repository = new Repository();
try (BufferedReader br = new BufferedReader(new FileReader(filename))) {
String[] temp;
String line = br.readLine();
while(line!=null){
temp=line.split(Character.toString(DELIMITER));
String name = stripQuotes(temp[0]);
String location = stripQuotes(temp[1]);
Restaurant restaurant = new Restaurant(name, location) {};
int lines = Integer.parseInt(temp[2]);
ArrayList<Review> review = new ArrayList<>();
for (int i=0; i<lines; i++) {
restaurant.addReviews(review);
}
repository.add(restaurant);
line = br.readLine();
}
br.close();
} catch (IOException ex) {
Logger.getLogger(DAOlmpl.class.getName()).log(Level.SEVERE, null, ex);
}
return repository;
}
}
and then is transfered over to the Restaurant class using this method.
public void addReviews(Review review) {
this.reviewsCollection.add(review);
}
However, I cant seem to get it over into the Restruant class as its in the form of an arraylist and not an object. I've treid many wayas to correct it, but cant get it working
If I read it correct, may this could be the Solution:
List<Review> reviews = new ArrayList<>();
for (Review review : reviews) {
restaurant.addReview(review);
}
and for the function
public void addReview(Review review) {
this.reviewsCollection.add(review);
}
So you add each Review separately what is in your list.
But you don't put any Review object in to your List so your list will be empty in this example.
Hope it helps.
Some logic is missing from your code. I noticed that you did not create any Review object. To remedy this, you could create Review objects, one after another and call the Restaurant.addReviews(Review); method for each Review object created. This could be done in the for loop as shown below:
for (int i=0; i<lines; i++) {
// Create a review object
//
Review review = createReview();
// Add the review object
//
restaurant.addReviews(review);
}
The above would obviate the need for the ArrayList of reviews.
In addition, The method to add reviews shown below...
public void addReviews(Review review) {
this.reviewsCollection.add(review);
}
...could be broken down into 2 methods. One method named: addReview to add a single Review and the other named: addReviews to add many Reviews. Notice the letter 's' missing from the former and added to the later method name. Use the 's' to signify adding multiple... See both methods below:
public void addReviews(List<Review> reviews) {
this.reviewsCollection.addAll(reviews);
}
public void addReview(Review review) {
this.reviewsCollection.add(review);
}
There are more observations. But I simply answered the immediate pressing (i.e your question).
Now, lets put it all together:
public class DAOlmpl implements DAOInterface {
static final char DELIMITER=',';
/**#Override*/
#Override
public Repository load(String filename) {
Repository repository = new Repository();
try (BufferedReader br = new BufferedReader(new FileReader(filename))) {
String line = br.readLine();
while(line!=null){
Restaurant restaurant = createRestaurantHavingReviews(line)
repository.add(restaurant);
line = br.readLine();
}
br.close();
} catch (IOException ex) {
Logger.getLogger(DAOlmpl.class.getName()).log(Level.SEVERE, null, ex);
}
return repository;
}
public Restaurant createRestaurantHavingReviews(String line) {
String [] temp=line.split(Character.toString(DELIMITER));
Restaurant restaurant = createRestaurant(temp);
int lines = Integer.parseInt(temp[2]);
for (int i=0; i<lines; i++) {
Review review = createReview(temp);
restaurant.addReview(review);
}
return restaurant;
}
public Restaurant createRestaurant(String[]temp) {
String name = stripQuotes(temp[0]);
String location = stripQuotes(temp[1]);
Restaurant restaurant = new Restaurant(name, location) {};
return restaurant;
}
public Review createReview(String[]temp) {
throw new UnsupportedOperationException("Please implement me!");
}
}
The above code is more readable and if you implement the public Review createReview(String[]temp) method above.. we could take it up from there if you have more questions.
Hope this helps.

Separating Parsing Method

I'm creating a program which handles SKU's. I currently have two classes in my program, the SKU class is the main class and a Store class in which an ArrayList is initialised and SKU objects are stored in the array. I currently have a method in my SKU class which takes input from a file, parses the data and stores the data using a String tokenizer in the objects variables and adds the objects to the array in the Store class. The problem I'm facing is that I'm wanting to separate the parsing method in the SKU class so that it simply reads from a line, and then have a separate method which takes a file input for the parser and finally update my Store class so that it initialises the products with the parsed data. Please, can you help me in regards to this?
My parsing method in the SKU class is currently as follows:
public void parser() {
try {
// create a Buffered Reader object instance with a FileReader
BufferedReader br = new BufferedReader(new FileReader("products.txt"));
// read from first line from the text file
String fileRead = br.readLine();
// skip first line from sample file as it contains headings
int lineNumber = 0;
// loop until all lines are read
while (fileRead != null)
{
if(lineNumber == 0) {
lineNumber++;
continue;
}
lineNumber++;
// use string.split to load a string array with the values from each line of
// the file, using a tab as the delimiter
String[] tokenize = fileRead.split("\t");
// assume file is made correctly
// and make temporary variables for the three types of data
String tempProductCode = tokenize[0];
String tempDescription = tokenize[1];
BigDecimal tempPrice = new BigDecimal(tokenize[2]);
// create temporary instance of SKU object
// and load with three data values
SKU tempObj = new SKU();
tempObj.setProductCode(tempProductCode);
tempObj.setDescription(tempDescription);
tempObj.setPrice(tempPrice);
// add to array list
Store.mySkuArrayList.add(tempObj);
// read next line before looping
// if end of file reached
fileRead = br.readLine();
}
// close file stream
br.close();
}
// handle exceptions
catch (FileNotFoundException fnfe)
{
System.out.println("file not found");
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
My Store class is as follows:
public class Store {
public static ArrayList<SKU> mySkuArrayList = new ArrayList<SKU>();
public void addSKU(SKU sku) {
mySkuArrayList.add(sku);
}
Split your code to three separate classes. SkuFile class represents text file where sku codes is stored, this class knows how to every sku entry stored and able to parse it. Sku class contains data. Store class contains
list of Sku and accept SkuFile in it's constructor.
class SkuFile {
private String path;
SkuFile(String path) {
this.path = path;
}
List<Sku> readAllSku() {
ArrayList<Sku> result = new ArrayList<>();
try {
List<String> lines = Files.readAllLines(new File(path).toPath());
for(String skuLine : lines) {
result.add(parseFrom(skuLine));
}
} catch (IOException e) {
throw new RuntimeException(e);
}
return result;
}
private Sku parseFrom(String data){
String[] tokenize = data.split("\t");
productCode = tokenize[0];
description = tokenize[1];
price = new BigDecimal(tokenize[2]);
return new Sku(productCode, description, price);
}
}
class Sku {
private String code;
private String description;
private BigDecimal price;
Sku(String code, String description, BigDecimal price) {
this.code = code;
this.description = description;
this.price = price;
}
//getters setters methods
}
class Store {
private List<Sku> skus;
Store(SkuFile file) {
skus = file.readAllSku();
}
}
class Test {
public static void main(String[] args) {
Store store = new Store(new SkuFile("products.txt"));
}
}
One way to handle this is by making the parse method return a list of tokenizers(e.g. List tokenizeList) and a second method which takes that list as input and populates the SkuArrayList
Possible implementation of the parser method
public List<String[]> parser() {
List<String[]> tokenizeList = new ArrayList<>();
try {
... /*file opening logic*/
while (fileRead != null)
{
.../*line counting logic*/
String[] tokenize = fileRead.split("\t");
tokenizeList.add(tokenize);
fileRead = br.readLine();
}
// close file stream
br.close();
}// handle exceptions
catch (FileNotFoundException fnfe)
{
System.out.println("file not found");
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
return tokenizeList;
}
Possible implementation of the populate store method
public void populateStore(List<String[]> tokenizeList) {
for(String[] tokenize: tokenizeList) {
String tempProductCode = tokenize[0];
String tempDescription = tokenize[1];
BigDecimal tempPrice = new BigDecimal(tokenize[2]);
SKU tempObj = new SKU();
tempObj.setProductCode(tempProductCode);
tempObj.setDescription(tempDescription);
tempObj.setPrice(tempPrice);
// add to array list
Store.mySkuArrayList.add(tempObj);
}
}
And the main method from where you call these two methods
public void foo() {
populateStore(parser());
}

Issues Serializing an ArrayList object containing other ArrayList objects

So I'm Serializing an ArrayList of ArrayLists essentially but I'm running into an issue. To be honest I'm still pretty new to Java, I've tried so many different methods to fix this as well as searched relentlessly on this site and have not been successful. I know that the way I word things may be hard to follow along or is confusing so I'll post my code here to see. Sorry in advance for all the code. SuperUsers has an arraylist of LoginInfo, PasswordKeeper has an Arraylist of SuperUsers, and the SuperUser arraylist gets serialized in PasswordKeeper. but any changes made to the LoginInfo arraylist do not save and i cannot figure out why. If anyone can help I would really Appreciate it. Thanks
public class PasswordKeeper{
private ArrayList<SuperUser> users;
private static Scanner keyboard = new Scanner(System.in);
public PasswordKeeper() {
users = new ArrayList();
}
public void login() {
try {
// reads in SuperUser arraylist
get();
} catch (EOFException a) {
System.out.println("You are the First User!");
} catch (IOException b) {
System.out.println(b);
} catch (ClassNotFoundException c) {
System.out.println(c);
}
boolean loopDisplay = true;
while (loopDisplay) {
existingUser = keyboard.next();
existingPass = keyboard.next();
SuperUser temp = new SuperUser(existingUser, existingPass);
System.out.println();
if (users.contains(temp)) {
// viewing superUser method
temp.display();
//saves after method call is over
try {
System.out.println("Saving.");
save(users);
} catch (IOException e) {
System.out.println(e);
}
}
}
//This happens if there is a new user
if(answer == 2){
SuperUser tempNew = null;
boolean cont = true;
String newUser;
String pass;
while(cont){
newUser = keyboard.nextLine();
System.out.println();
//System.out.println(users.size());
tempNew = new SuperUser(newUser, pass);
if(passValid(pass) == true){
if(makeSure(tempNew) == true){
System.out.println("Login Created!");
tempNew = new SuperUser(newUser, pass);
//actually being added to the arraylist
users.add(tempNew);
cont = false;
}
}
}
//SuperUser.display method
tempNew.display();
try{
System.out.println("Saving.");
save(users);
}catch(IOException e){
System.out.println(e);
}
}
}
}
//makeSure and passValid methods
public boolean makeSure(SuperUser user){
if(users.contains(user)){
return false;
}
return true;
}
public boolean passValid(String pass){
boolean passes = false;
String upper = "(.*[A-Z].*)";
String lower = "(.*[a-z].*)";
String numbers = "(.*[0-9].*)";
String special = "(.*[,~,!,#,#,$,%,^,&,*,(,),-,_,=,+,[,{,],},|,;,:,<,>,/,?].*$)";
if((pass.length()>15) || (pass.length() < 8)){
System.out.println("Entry must contain over 8 characters\n" +
"and less than 15.");
passes = false;
}if(!pass.matches(upper) || !pass.matches(lower)){
System.out.println("Entry must contain at least one uppercase and lowercase");
passes = false;
}if(!pass.matches(numbers)){
System.out.println("Password should contain atleast one number.");
passes = false;
}if(!pass.matches(special)){
System.out.println("Password should contain atleast one special character");
passes = false;
}else{
passes = true;
}
return passes;
//serializable methods
public void save(ArrayList<SuperUser> obj) throws IOException {
File file = new File("userInformation.dat");
FileOutputStream fileOut = new FileOutputStream(file, false);
BufferedOutputStream buffedOutput = new BufferedOutputStream(fileOut);
ObjectOutputStream out = new ObjectOutputStream(buffedOutput);
out.writeObject(obj);
out.close();
fileOut.close();
}
public ArrayList<SuperUser> get() throws IOException, ClassNotFoundException {
FileInputStream fileIn = new FileInputStream("userInformation.dat");
BufferedInputStream buffedInput = new BufferedInputStream(fileIn);
ObjectInputStream in = new ObjectInputStream(buffedInput);
users = (ArrayList<SuperUser>) in.readObject();
in.close();
fileIn.close();
return users;
}
public class SuperUser implements Serializable {
private String userName;
private String password;
private static Scanner keyboard = new Scanner(System.in);
private ArrayList<LoginInfo> info = new ArrayList();
public SuperUser(String name, String pass) {
userName = name;
password = pass;
}
public String getUser() {
return userName;
}
public void display() {
String next = keyboard.next();
//want to add data to LoginInfo arraylist
if (next.equalsIgnoreCase("add")) {
add();
} else if (next.equalsIgnoreCase("delete")) {
delete();
} else if (numberCheck(next)) {
int choice = (int) Integer.parseInt(next) - 1;
edit(choice);
//!!!! this: after doing this i lose whatever data i added
//to the LoginInfo arraylist, right after this the
//SuperUser arraylist gets saved. but the added data to
//loginInfo does not
} else if (next.equalsIgnoreCase("logout")) {
System.out.println(info.size());
}
}
public boolean numberCheck(String in) {
try {
Integer.parseInt(in);
} catch (NumberFormatException e) {
return false;
}
return true;
}
//method to add to the Arraylist
public void add() {
System.out.println("What is the website name?:");
String trash = keyboard.nextLine();
String webName = keyboard.nextLine();
System.out.println("The Username?:");
String webUsername = keyboard.nextLine();
System.out.println("The Password?:");
String webPass = keyboard.nextLine();
info.add(new LoginInfo(webUsername, webPass, webName));
System.out.println(info.size());
//method goes back to display
display();
}
}
}
Your problem is here
SuperUser temp = new SuperUser(existingUser, existingPass);
System.out.println();
if (users.contains(temp)) {
// viewing superUser method
temp.display();
You create a temporary object which with the username and password.
Your 'users.contains()' method returns true because '.equals()' is based on the username, however the 'temp' object is a different instance to that in the list.
So when you call 'temp.display()' it is not calling on an object in the list, so no data changes will save.
You need to find the existing object from the list for that user. I would suggest that you swap your list for a map keyed on username.
You have a list named users. Once you created new SuperUser instance (temp), you are checking that it belongs to this list (users.contains(temp), which is false of course - from where it will occur there?). If it have belonged, the method display would be called, which in turn would add LoginInfo to that SuperUser (add() call), but I bet in reality it doesn't happened.
Also, I see where you read from users (check whether new SuperUser instances belong there), I see where you overwrite it (during desealization) but I don't see adding any instance to there, which makes me think that it is always empty.
Are you sure that SuperUser contains any LoginInfo in its array list?

CSVReader does not check the whole file

I am trying to open a csv file using openCSV, iterate over every column and if the userID is different write a new JavaBean pair at the end of the file.
The problem is that the reader only checks the first column of my file and not the whole file. While created, the file contains only a header and nothing else. The program will check every column and if the sudoID is different it will write it to the file. If the sudoID in the first line is equal to the the one imported from my main class it will recognise it and not write it. But if this -same- sudoID is in the second row it will not recognise it and will write it again.
For instance, if my CSV looks like this it will work:
"Patient_id Pseudo_ID",
"32415","PAT106663926"
If it looks like this it will re-write the sudoID:
"Patient_id Pseudo_ID",
"32416","PAT104958880"
"32415","PAT106663926"
Thanks!
My Code:
public class CSVConnection {
#SuppressWarnings({ "deprecation", "resource", "rawtypes", "unchecked" })
public String getID(String sID,String pseudoID) throws IOException, CsvDataTypeMismatchException, CsvRequiredFieldEmptyException{
try {
CsvToBean csv = new CsvToBean();
String csvFilename = "CsvFile.csv";
Writer writer= new FileWriter(csvFilename,true);
CSVReader csvReader = new CSVReader(new FileReader(csvFilename),',','"',1);
ColumnPositionMappingStrategy strategy = new ColumnPositionMappingStrategy();
strategy.setType(PatientCSV.class);
String[] columns = new String[] {"patID","pseudoID"};
strategy.setColumnMapping(columns);
//Set column mapping strategy
StatefulBeanToCsv<PatientCSV> bc = new StatefulBeanToCsvBuilder<PatientCSV>(writer).withMappingStrategy(strategy).build();
List patList = csv.parse(strategy, csvReader);
for (Object patObj : patList) {
PatientCSV pat = (PatientCSV) patObj;
if(((PatientCSV) patObj).getPatID().equals(sID)){
return pat.getPseudoID();
}
else
{
PatientCSV pat1 = new PatientCSV();
pat1.setPatID(sID);
pat1.setPseudoID(pseudoID);
patList.add(pat1);
/*Find a way to import it to the CSV*/
bc.write(pat1);
writer.close();
return pseudoID;
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public static void main(String [] args) throws IOException, CsvDataTypeMismatchException, CsvRequiredFieldEmptyException{
CSVConnection obj = new CSVConnection();
String sID="32415";
String pseudoID="PAT101830150";
obj.getID(sID,pseudoID);
}
}
and the Java Bean :
public class PatientCSV {
private String patID;
private String pseudoID;
public String getPatID() {
return patID;
}
public void setPatID(String patID) {
this.patID = patID;
}
public String getPseudoID() {
return pseudoID;
}
public void setPseudoID(String pseudoID) {
this.pseudoID = pseudoID;
}
public PatientCSV(String patID, String pseudoID) {
super();
this.patID = patID;
this.pseudoID = pseudoID;
}
public PatientCSV() {
super();
// TODO Auto-generated constructor stub
}
public String toString()
{
return "Patient [id=" + patID + ", pseudoID=" + pseudoID + "]";
}
}
Lets inspect your for loop
for (Object patObj : patList) {
PatientCSV pat = (PatientCSV) patObj;
if(((PatientCSV) patObj).getPatID().equals(sID)){
return pat.getPseudoID();
}
else
{
PatientCSV pat1 = new PatientCSV();
pat1.setPatID(sID);
pat1.setPseudoID(pseudoID);
patList.add(pat1);
/*Find a way to import it to the CSV*/
bc.write(pat1);
writer.close();
return pseudoID;
}
}
So in the case you mention it is not working as expected, meaning that the line that matches your input is the second line:
"Patient_id Pseudo_ID",
"32416","PAT104958880"
"32415","PAT106663926"
So you call: getID("32415", "PAT106663926")
What happens in your loop is:
You take the first element of your csv patients, the one with id: 32416,
check if it matches with the id given as input to your method, 32415.
It does not match so it goes to the else part. There it creates the new patient (with the same patID and pseudoID as the 2nd row of your csv) and stores it in the file.
So by now you should have 2 entries in your csv with the same data "32415","PAT106663926".
I think that this is the error, in your for loop you should check against all entries if there is a match, and then create the patient and store it to the csv.
An example:
PatientCSV foundPatient = null;
for (Object patObj : patList) {
PatientCSV pat = (PatientCSV) patObj;
if(((PatientCSV) patObj).getPatID().equals(sID)){
foundPatient = pat;
}
}
if (foundPatient == null) {
foundPatient = new PatientCSV();
foundPatient.setPatID(sID);
foundPatient.setPseudoID(pseudoID);
patList.add(foundPatient);
/*Find a way to import it to the CSV*/
bc.write(foundPatient);
writer.close();
}
return foundPatient.getPseudoID();
P.S. The above example is written very quickly, just to give you the idea what needs to be done.

Java retrieve data from sqlite return Objects instead of values

I'm trying to retrieve some data from my Db (I'm using SQLite) using DAO
public class ClassSectionDAO implements IClassSectionDAO{
#Override
public void selectAllClassSection() {
d = new DBManager();
sqliteQuery = new SqliteQueries();
d.executeQuery(sqliteQuery.selectAllFrom("classSection"));
try{
while(d.getResultSet().next()){
ClassSection classSection = new ClassSection();
classSection.setClassSectionId(d.getResultSet().getString("classSectionId"));
classSection.setSchoolClassCode(d.getResultSet().getString("schoolClassCode"));
classSection.setClassSectionNumber(d.getResultSet().getInt("classSectionNumber"));
classSection.setClassSectionAvailability(d.getResultSet().getString("classSectionAvailability"));
classSectionList.add(classSection);
System.out.println("classSectionList: " + classSectionList);
}
}
catch(Exception e){
Logger.getLogger(ClassSectionDAO.class.getName()).log(Level.SEVERE, null, e);
classSectionList = null;
}
finally{
d.closeDatabaseConnection();
}
}
}
All I'm getting is a list of objects like
classSectionList: [entities.classSection.ClassSection#19ccf6d, entities.classSection.ClassSection#1faf0e7, entities.classSection.ClassSection#1cf8409]
What should I do in order to get the values instead?
PS: If you want to see more code, let me know
I think you just made a typo, as you already said in your question: I get a list of Objects (of type ClassSection). That's clear because you print the list of Objects.
If you want to do it in the while loop (print immediately the value for every result), just change the last line in the loop to:
System.out.println("classSectionList: " + classSection.getSchoolClassCode());
If you want to print the values of all results (after all results are processed), just add Michaƫl's solution after the wile loop.
for(ClassSection c : classSectionList) {
System.out.println(c.getSchoolClassCode());
// print other attributes
}
EDIT :
Firt solution :
public class ClassSectionDAO implements IClassSectionDAO{
#Override
public void selectAllClassSection() {
d = new DBManager();
sqliteQuery = new SqliteQueries();
d.executeQuery(sqliteQuery.selectAllFrom("classSection"));
try{
while(d.getResultSet().next()){
ClassSection classSection = new ClassSection();
classSection.setClassSectionId(d.getResultSet().getString("classSectionId"));
classSection.setSchoolClassCode(d.getResultSet().getString("schoolClassCode"));
classSection.setClassSectionNumber(d.getResultSet().getInt("classSectionNumber"));
classSection.setClassSectionAvailability(d.getResultSet().getString("classSectionAvailability"));
classSectionList.add(classSection);
// Solution of ProgrammingIsAwsome
System.out.println("classSectionList: " + classSection.getSchoolClassCode());
}
}
catch(Exception e){
Logger.getLogger(ClassSectionDAO.class.getName()).log(Level.SEVERE, null, e);
classSectionList = null;
}
finally{
d.closeDatabaseConnection();
}
}
}
Second solution :
public class ClassSectionDAO implements IClassSectionDAO{
#Override
public void selectAllClassSection() {
d = new DBManager();
sqliteQuery = new SqliteQueries();
d.executeQuery(sqliteQuery.selectAllFrom("classSection"));
try{
while(d.getResultSet().next()){
ClassSection classSection = new ClassSection();
classSection.setClassSectionId(d.getResultSet().getString("classSectionId"));
classSection.setSchoolClassCode(d.getResultSet().getString("schoolClassCode"));
classSection.setClassSectionNumber(d.getResultSet().getInt("classSectionNumber"));
classSection.setClassSectionAvailability(d.getResultSet().getString("classSectionAvailability"));
classSectionList.add(classSection);
}
// Print the list after the while
for(ClassSection c : classSectionList) {
System.out.println(c.getSchoolClassCode());
// print other attributes
}
}
catch(Exception e){
Logger.getLogger(ClassSectionDAO.class.getName()).log(Level.SEVERE, null, e);
classSectionList = null;
}
finally{
d.closeDatabaseConnection();
}
}
}

Categories