Reading multiple line textfile to database - java

I have a text file that looks like this:
Person1 Name
Person1 age
Person1 Address
Person2 Name
Person2 age
Person2 Address
Person3 Name
Person2 age
Person3 Address
and I need to get the information to a database.
I have the database connection and know how to enter the info into the database once I have the lines put into the correct variables . . . but how do I get java to identify each new line and set the info to a variable.
Basically I need to take the textfile info and add to the following variables
$Name
$Age
$Address
I thought of using an Array but since I'm mixing strings and numbers, I can't use a String array.
Since I'm using Line per line there is no delimiter.
** Updated info **
I used name, age and address as example variables, and got some of the answers kind of working but I still can't get it completely working, so I should post the whole code . . .
I'm open to code cleanup as well (I'm really new to Java)
The answers given I kind of got to work, except the reader is separating the variables by spaces and in a situation like name and address both have spaces in them, the space delimiter isn't giving me the results I need.
Here is the textfile contents:
Ray Wade
200
American Foundation for Children with AIDS
Tom Hardy
125.50
American Red Cross
As you can see I call the LoadTextFile(); within the CreateTables() function
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.text.*;
import java.sql.*;
import javax.sql.*;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
public class Charity extends JFrame
{
JButton btnCalc = new JButton("Donate"), btnLoad = new JButton("Load File"), btnExit = new JButton("Exit");
JLabel name, amount, intro = new JLabel("Would You Like to Donate to a Charity Today? It Only Takes a Few Moments"), message1 = new JLabel(""), message2 = new JLabel("");
JTextField textName, textAmount;
// Create String Array to list charities in the combobox
String[] charities = { "Choose a Charity or Enter a New Charity",
"American Foundation for Children with AIDS",
"American Red Cross",
"Breast Cancer Research Foundation",
"Livestrong *Formerly Lance Armstrong Foundation*",
"Michael J. Fox Foundation for Parkinson's Research" };
JComboBox charityList = new JComboBox(charities);
String file ="Charity.txt";
// Variables used later
double dAmount;
String Charity = null;
int debug = 0; // change to 1 to turn debug mode on
// Variables initialized for Database Stuff
Object[][] databaseInfo;
Object[] columns = {"name", "charity", "amount"};
Connection conn = null;
ResultSet rows;
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/";
String DBname = "charity";
String DBusername = "root";
String DBpass = "password";
// Variables and Class for TableModel
DefaultTableModel dTableModel = new DefaultTableModel(databaseInfo, columns){
public Class getColumnClass(int column) {
Class returnValue;
// Verifying that the column exists (index > 0 && index < number of columns
if ((column >= 0) && (column < getColumnCount())) {
returnValue = getValueAt(0, column).getClass();
} else {
// Returns the class for the item in the column
returnValue = Object.class;
}
return returnValue;
}
};
/**
Sets the title, size and layout of the JFrame.<!-- -->Also calls the methods to setup the panels.
*/
public Charity()
{
super("Donations to Charities"); // Title of frame
setLayout(new FlowLayout()); // Declare layout of frame
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Default close
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); // Get screen size
this.setResizable( false ); // turn off frame resize
this.setSize(600, dim.height-100); // set size of frame
CreatePanels();
GetAction(); // Call ActionListeners
CreateDatabase();
}
public void CreatePanels()
{
SetupCharityGroup(); // Call method to setup charity list panel
SetupDataPanel(); // Call method to setup data collection panel
SetupDisplayTable();
setVisible(true); // Make frame visible
}
/**
Method to setup the display panel containing a JTable that will show the information read from the database.
*/
private void SetupDisplayTable()
{
JTable table = new JTable(dTableModel); // Create a JTable using the custom DefaultTableModel
table.setFont(new Font("Serif", Font.PLAIN, 16)); // Increase the font size for the cells in the table
table.setRowHeight(table.getRowHeight()+5); // Increase the size of the cells to allow for bigger fonts
table.setAutoCreateRowSorter(true); // Allows the user to sort the data
// right justify amount column
TableColumn tc = table.getColumn("amount");
RightTableCellRenderer rightRenderer = new RightTableCellRenderer();
tc.setCellRenderer(rightRenderer);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); // Disable auto resizing
// Set the width for the columns
TableColumn col1 = table.getColumnModel().getColumn(0);
col1.setPreferredWidth(200);
TableColumn col2 = table.getColumnModel().getColumn(1);
col2.setPreferredWidth(275);
TableColumn col3 = table.getColumnModel().getColumn(2);
col3.setPreferredWidth(75);
// Put the table in a scrollpane and add scrollpane to the frame
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setPreferredSize(new Dimension(552, 400));
this.add(scrollPane, BorderLayout.CENTER);
}
/**
Method to setup the data panel containing textFields, Labels, and buttons.
*/
private void SetupDataPanel()
{
JPanel pan = new JPanel();
GridLayout grid = new GridLayout(0, 1, 5, 5);
pan.setLayout(grid);
// Setup TextFields and Labels for name of person donating
// and add them to the panel
name = new JLabel("Name");
textName = new JTextField("", 16);
textName.setHorizontalAlignment(JTextField.RIGHT);
pan.add(name);
pan.add(textName);
// Setup TextFields and Labels for amount being donated
// and add them to the panel
amount = new JLabel("Donation Amount");
textAmount = new JTextField("", 4);
textAmount.setHorizontalAlignment(JTextField.RIGHT);
pan.add(amount);
pan.add(textAmount);
// add buttons and message labels to panel
pan.add(intro);
pan.add(btnCalc);
pan.add(btnLoad);
pan.add(btnExit);
pan.add(message1);
pan.add(message2);
this.add(pan);
}
/**
Method to setup the charity panel with a border containing an editable combobox filled with a list of charities.
*/
private void SetupCharityGroup()
{
JPanel Boxpan=new JPanel();
Boxpan.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(), "Charities"));
this.add(Boxpan);
charityList.setEditable(true);
Boxpan.add(charityList);
}
/**
Add ActionHandlers to interactive elements.
*/
private void GetAction()
{
ActionHandler handler = new ActionHandler();
btnLoad.addActionListener(handler);
btnCalc.addActionListener(handler);
btnExit.addActionListener(handler);
charityList.addActionListener( handler );
}
/**
Method to make ActionHandlers into ActionListeners.
*/
private class ActionHandler implements ActionListener
{
public void actionPerformed(ActionEvent evt)
{
String incmd = evt.getActionCommand();
if (incmd.equals("Donate")) // If Donate button is pressed
if (textName.getText().isEmpty())
{
message1.setText("<html><font color='red'>Invalid Donation</font>");
message2.setText("<html><font color='red'>Error: Name of Donor missing!<font>");
} else
CheckDonate();
else if (incmd.equals("Load File")) // If Load File button is pressed
DatabaseLoad();
else if (incmd.equals("Exit")) // If Exit button is pressed
System.exit(0);
}
}
/**
Method to check if charity is selected in the combobox.<!-- -->If a charity is selected, call CharitySelected method, otherwise send error message to Frame.
*/
private void CheckCharity()
{
Object selectedCharity = charityList.getSelectedItem();
if (charityList.getSelectedIndex() == 0) // if charity is not selected
{
message1.setText("<html><font color='red'>Invalid Donation</font>");
message2.setText("<html><font color='red'>Error: No Charity Selected!<font>");
} else CharityIsSelected();
}
/**
If charity is selected, set the selected value to "Charity" variable and call method to thank donator.
*/
private void CharityIsSelected()
{
Object selectedCharity = charityList.getSelectedItem();
Charity = selectedCharity.toString(); // selectedCharity Object converted to String
ThankYou();
}
/**
Thank the donator and call the databseAdd method.
*/
private void ThankYou()
{
message1.setText("Thank You! "+textName.getText());
message2.setText(" $"+textAmount.getText()+" Will be donated to "+Charity);
DatabaseAdd();
}
/**
Method that will check that donation amount is a number in a range between 1 and 1000000000.
*/
private void CheckDonate()
{ try
{
dAmount = Double.parseDouble(textAmount.getText());
if(dAmount <= 0.0 || dAmount > 1000000000 )
{
message1.setText("<html><font color='red'>Invalid Donation</font>");
message2.setText("<html><font color='red'>Amount invalid</font>");
} else CheckCharity();
} catch (NumberFormatException ex) {
// Executes if the data entered is not a number
if (debug == 1)
{
message1.setText("Error: "+ex.getMessage());
message2.setText("");
} else
{
message1.setText("<html><font color='red'>Invalid Donation</font>");
message2.setText("<html><font color='red'>Amount Not Recognized</font>");
}
}
}
public void DBConnection()
{ try
{
// The driver allows you to query the database with Java
// forName dynamically loads the class for you
Class.forName(driver);
// DriverManager is used to handle a set of JDBC drivers
// getConnection establishes a connection to the database
// You must also pass the userid and password for the database
conn = DriverManager.getConnection (url, DBusername, DBpass);
} catch (SQLException ex) {
// debug:
if (debug == 1)
{
message1.setText("Error: "+ex.getMessage());
message2.setText("Error: "+ex.getErrorCode());
} else
message1.setText("Database Error: contact admin");
message2.setText("");
} catch (ClassNotFoundException ex) {
// Executes if the driver can't be found
// debug:
if (debug == 1)
{
message1.setText("Error: "+ex.getMessage());
message2.setText("");
} else
message1.setText("Driver Error: contact admin");
message2.setText("");
}
}
/**
Method to add the entered information to the database.<!-- -->Once the information is added to the database, clear the form fields.
*/
private void DatabaseAdd()
{ try
{
url = url+DBname;
DBConnection();
// Statement objects executes a SQL query
// createStatement returns a Statement object
Statement s = conn.createStatement();
// Prepare the query and values to be inserted into the database
String str="INSERT INTO donations(name,charity,amount) VALUES (?,?,?)";
java.sql.PreparedStatement statement = conn.prepareStatement(str);
statement.setString(1,textName.getText());
statement.setString(2,Charity);
statement.setDouble(3,dAmount);
statement.executeUpdate();
// Reset form after saved to database
textName.setText("");
textAmount.setText("");
charityList.setSelectedIndex(0);
s.close();
DatabaseLoad(); // Call the Database Info
} catch (SQLException ex) {
// debug:
if (debug == 1)
{
message1.setText("Error: "+ex.getMessage());
message2.setText("Error: "+ex.getErrorCode());
} else
message1.setText("Database Error: contact admin");
message2.setText("");
}
}
/**
Method will load the database information and display it in Frame in a JTable.
*/
private void DatabaseLoad()
{ try
{
url = url+DBname;
DBConnection();
// Statement objects executes a SQL query
// createStatement returns a Statement object
Statement s = conn.createStatement();
// This is the query I'm sending to the database
String selectStuff = "SELECT `name`, `charity`, `amount` FROM `"+DBname+"`.`donations` ";
// A ResultSet contains a table of data representing the
// results of the query. It can not be changed and can
// only be read in one direction
rows = s.executeQuery(selectStuff);
// Set the table RowCount to 0
dTableModel.setRowCount(0);
// Temporarily holds the row results
Object[] tempRow;
// next is used to iterate through the results of a query
while(rows.next())
{
// Gets the column values based on class type expected
tempRow = new Object[]{rows.getString(1), rows.getString(2), rows.getDouble(3) };
dTableModel.addRow(tempRow); // Adds the row of data to the end of the model
}
// Successfully loaded, message the user
message1.setText("<html><font color='red'>Database Info Loaded</font>");
message2.setText("");
s.close();
} catch (SQLException ex) {
// debug:
if (debug == 1)
{
message1.setText("Error: "+ex.getMessage());
message2.setText("Error: "+ex.getErrorCode());
} else
message1.setText("Database Error: contact admin");
message2.setText("");
}
}
/**
Method will create the database if it does not exist.
*/
private void CreateDatabase()
{ try
{
DBConnection();
// Statement objects executes a SQL query
// createStatement returns a Statement object
Statement s = conn.createStatement();
String dbCreate = "CREATE DATABASE "+DBname;
s.executeUpdate(dbCreate);
s.close();
} catch(SQLException ex){
// debug:
if (debug == 1)
{
message1.setText("Error: "+ex.getMessage());
message2.setText("Error: "+ex.getErrorCode());
}
} catch(Exception ex){
// debug:
if (debug == 1)
{
message1.setText("Error: "+ex.getMessage());
message2.setText("");
}
}
CreateTables();
}
/**
Method will create the table needed in the database.
*/
private void CreateTables()
{ try
{
DBConnection();
// Statement objects executes a SQL query
// createStatement returns a Statement object
Statement s = conn.createStatement();
String tableCreate = "create table "+DBname+".donations " + "(`name` varchar(200), " + "`charity` varchar(200), " + "amount double)";
s.executeUpdate(tableCreate);
// After creating the tables
// Load the information from the textfile
LoadTextFile();
s.close();
} catch(SQLException ex){
// debug:
if (debug == 1)
{
message1.setText("Error: "+ex.getMessage());
message2.setText("Error: "+ex.getErrorCode());
}
} catch(Exception ex){
// debug:
if (debug == 1)
{
message1.setText("Error: "+ex.getMessage());
message2.setText("");
}
}
}
public void LoadTextFile()
{
}
// To change justification to the right
class RightTableCellRenderer extends DefaultTableCellRenderer {
public RightTableCellRenderer() {
setHorizontalAlignment(JLabel.RIGHT);
}
}
// Main method calls the constructor
public static void main(String[] args)
{
new Charity();
}
}

Following code snippet will solve your problem.
public class Test {
public static void main( String[] args ) throws Exception
{
HashMap<String, Person> personMap = new HashMap<String, Person>();
try
{
BufferedReader in = new BufferedReader( new FileReader( "File Path" ) );
String str;
Person person = new Person();
int count = 0;
String key = "";
while( ( str = in.readLine() ) != null )
{
if ( null != str && str.trim().length() == 0 )
{
personMap.put( key, person );
count = -1;
person = new Person();
}
else {
String arr[] = str.split( " " );
key = arr[0];
if (count == 0) {
person.setName( arr[1] );
}
else if (count == 1) {
person.setAge( arr[1] );
}
else if (count == 2) {
person.setAddress( arr[1] );
}
}
count ++;
}
personMap.put( key, person );
in.close();
}
catch( IOException e )
{
System.out.println( "Exception" + e.getMessage() );
}
}
}
public class Person
{
private String name = null;
private String age = null;
private String Address = null;
public String getName()
{
return name;
}
public void setName( String name )
{
this.name = name;
}
public String getAge()
{
return age;
}
public void setAge( String age )
{
this.age = age;
}
public String getAddress()
{
return Address;
}
public void setAddress( String address )
{
Address = address;
}
}
I hope it helps

Use BufferedReader to read one line at a time, extract the required info from that line and assign it to the variables. In case you want to hold it in the memory, use a POJO with those 3 properties.
You may use regex to split the line and get the required value(s).

I wrote a set of functions that does something similar. I use a bufferedReader like the other user suggested.
public ArrayList<String> readFileToMemory(String filepath)
{
BufferedReader br = null;
String currentLine = null;
ArrayList<String> fileContents = new ArrayList<String>();
try
{
br = new BufferedReader(new FileReader(filepath));
while((currentLine = br.readLine()) != null)
{
//fileContents.add(br.readLine());
fileContents.add(currentLine);
}
}
catch(IOException e)
{
e.printStackTrace();
}
finally
{
try
{
br.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
return fileContents;
}
This will just read in the each line of a file as a separate entry in a list. Just take the entries and do what you need.

If you're only doing this once, just do 3 replaces in notepad ++
Replace \r\n\r\n with "|||"
replace \r\n with ","
replace ||| with \r\n
then you've got a regular .csv file.

Related

Getting array out of bounds exception when updating a record

I have created a simple address book program which allows the user to add and update a record. There is also a jtable on the address book which shows the user all the records in the address Book. I have recently added logic where the user updates an existing record and the table refreshes. But if I then click on the updated record or any record in the Jtable to display into the Jtext field I get a I get an Array Out of Bounds error.
Code for getting records from the Database
public void addTable() throws Exception {
tableModel = new DefaultTableModel();
xtable = new JTable(tableModel);
tableModel.addColumn("ID");
tableModel.addColumn("First Name");
tableModel.addColumn("Surname");
tableModel.addColumn("Address Line 1");
tableModel.addColumn("Address Line 2");
tableModel.addColumn("Address Line 3");
tableModel.addColumn("City");
tableModel.addColumn("Post Code");
tableModel.addColumn("Email Address");
tableModel.addColumn("Phone Number");
db.connectDb();
String outQuery = "SELECT * FROM Contacts";
db.myFs = db.st.executeQuery(outQuery);
while (db.myFs.next()) {
String id = db.myFs.getString("ContactID");
String fName = db.myFs.getString("FirstName");
String sName = db.myFs.getString("Surname");
String adOne = db.myFs.getString("AddressLineOne");
String adTwo = db.myFs.getString("AddressLineTwo");
String adThree = db.myFs.getString("AddressLineThree");
String cCity = db.myFs.getString("City");
String pCode = db.myFs.getString("PostCode");
String eAddress = db.myFs.getString("EmailAddress");
String eName = db.myFs.getString("PhoneNumber");
tableModel.insertRow(0, new Object[] { id, fName,sName, adOne, adTwo, adThree, cCity,
pCode, eAddress, eName });
}
db.st.close();
db.con.close();
pane = new JScrollPane(xtable);
pane.setBounds(700, 100, 400, 100);
panel.add(pane);
}
Code to display record into JTextField
public void fetchRec() {
xtable.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e){
String col0 = (String) xtable.getValueAt(xtable.getSelectedRow(),0);
String col1 = (String) xtable.getValueAt(xtable.getSelectedRow(),1);
String col2 = (String) xtable.getValueAt(xtable.getSelectedRow(),2);
String col3 = (String) xtable.getValueAt(xtable.getSelectedRow(),3);
String col4 = (String) xtable.getValueAt(xtable.getSelectedRow(),4);
String col5 = (String) xtable.getValueAt(xtable.getSelectedRow(),5);
String col6 = (String) xtable.getValueAt(xtable.getSelectedRow(),6);
String col7 = (String) xtable.getValueAt(xtable.getSelectedRow(),7);
String col8 = (String) xtable.getValueAt(xtable.getSelectedRow(),8);
String col9 = (String) xtable.getValueAt(xtable.getSelectedRow(),9);
idLabelField.setText(col0);
firstNameLabelField.setText(col1);
surNameLabelField.setText(col2);
addressLineOneField.setText(col3);
addressLineTwoField.setText(col4);
addressLineThreeField.setText(col5);
cityField.setText(col6);
postCodeField.setText(col7);
emailAddressField.setText(col8);
phoneNumberField.setText(col9);
}
});
}
Code to Update a record in the Db
public void updateButton() {
updateButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
number = Integer.parseInt(idLabelField.getText());
setID(number);
setFirstName(firstNameLabelField.getText());
setSurName(surNameLabelField.getText());
setAddressLineOne(addressLineOneField.getText());
setAddressLineTwo(addressLineTwoField.getText());
setAddressLineThree(addressLineThreeField.getText());
setCity(cityField.getText());
setPostCode(postCode.getText());
setEmailAddress(emailAddressField.getText());
setPhoneNumber(phoneNumberField.getText());
try {
db.updateDB(getID(),getFirstName(), getSurName(), getAddressLineOne(), getAddressLineTwo(),
getAddressLineThree(), getCity(), getPostCode(), getEmailAddress(), getPhoneNumber());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
addTable();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
The error i am getting is Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 8
First of all don't use a null layout and setBounds(). Swing was designed to be used for layout managers.
I have recently added logic where the user updates an existing record and the table refreshes.
I would guess the problem is that you keep creating new components (ie. JTable and JScrollPane) and then add the components to the screen.
The problem is you never remove the previous components so you have multiple instances of each component being painted on the frame and your variables don't reference the visible components.
So the solution is create your JTable and JScrollPane and add the components to the frame when you first create the frame. Then, when you "referesh" the data you just create a new DefaultTableModel and use the setModel(...) method to update the table.
Or you can use setRowCount(0) of your current DefaultTableModel to remove all the current data and then use use the addRow(...) method to repopulate the model with the dat in the ResultSet.

Storing Objects of an array into CSV file and reading them with specific arguments for GUI

As a part of my assignment I had to store objects of an array in a flat-file and retrieve them when certain criteria was met. I can save the objects fine but when retrieving them I have an issue with getting more than one value, I understand what is going wrong but I am struggling to find a solution. Here is the concept of whats happening.
Button no 10,A (R1S10 in the code)is my testing button, When I click it it creates an event that I will show below.
Click event for button 10A -
private void R1S10ActionPerformed(java.awt.event.ActionEvent evt) {
seats.add(seat1);
if (R1S10.getBackground().equals(Color.red) &&(IsSeatBooked().equals("true"))){
Component frame = null;
JOptionPane.showMessageDialog(frame, "Seat UnBooked");
seat1.setBooked("false");
seat1.setName("");
R1S10.setBackground(Color.yellow);
try {
reader();
writer();
//String booked = "true";
//Pass String booked into csv file
} catch (IOException ex) {
Logger.getLogger(SeatingPlan.class.getName()).log(Level.SEVERE, null, ex);
}
}
else{
Component frame = null;
String name = JOptionPane.showInputDialog(frame, "Please enter name of Customer booking");
if (name.isEmpty()) {
JOptionPane.showMessageDialog(frame, "No value entered");
} else if (name != null) {
seat1.setName(name);
seat1.setBooked("true");
R1S10.setBackground(Color.red);
JOptionPane.showMessageDialog(frame, "Your Booking has been placed");
try {
writer();
reader();
//String booked = "true";
//Pass String booked into csv file
} catch (IOException ex) {
Logger.getLogger(SeatingPlan.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
Followed by the screen below -
Outcome -
And when the button is pressed again -
I am using three methods in this SeatingPlan.java - writer(),reader() and IsSeatBooked().
SeatingPlan -
public class SeatingPlan extends javax.swing.JFrame {
/**
* Creates new form SeatingPlan
*/
String seatNo, name, bookedSeat;
FileWriter fileWriter = null;
List<Seat> seats = new ArrayList<Seat>();
//Seat Object Declaration
Seat seat1 = new Seat("R1S10","","false");
Seat seat2 = new Seat("R1S9", "", "false");
String fileName = "seat.csv";
writer -
public void writer() throws IOException {
//Delimiter used in CSV file
final String NEW_LINE_SEPARATOR = "\n", COMMA_DELIMITER = ",";
//CSV file header
final String FILE_HEADER = "seatID,name,booked";
//fileName = System.getProperty("user.home") + "/seat.csv";
try {
fileWriter = new FileWriter(fileName);
//Write the CSV file header
fileWriter.append(FILE_HEADER.toString());
//Add a new line separator after the header
fileWriter.append(NEW_LINE_SEPARATOR);
//Write a new student object list to the CSV file
for (Seat seat : seats) {
fileWriter.append(String.valueOf(seat.getSeatID()));
fileWriter.append(COMMA_DELIMITER);
fileWriter.append(seat.getName());
fileWriter.append(COMMA_DELIMITER);
fileWriter.append(seat.isBooked());
fileWriter.append(NEW_LINE_SEPARATOR);
}
System.out.println("CSV file was created successfully !!!");
} catch (Exception e) {
System.out.println("Error in CsvFileWriter !!!");
e.printStackTrace();
} finally {
fileWriter.flush();
fileWriter.close();
}
}
reader -
public void reader() {
//Delimiter used in CSV file
final String COMMA_DELIMITER = ",";
//Student attributes index
final int SEAT_ID_IDX = 0;
final int SEAT_NAME_IDX = 1;
final int SEAT_BOOKED = 2;
//private static final int STUDENT_LNAME_IDX = 2;
BufferedReader fileReader = null;
try {
//Create a new list of student to be filled by CSV file data
List<Seat> seats = new ArrayList<>();
String line = "";
//Create the file reader
fileReader = new BufferedReader(new FileReader(fileName));
//Read the CSV file header to skip it
fileReader.readLine();
//Read the file line by line starting from the second line
while ((line = fileReader.readLine()) != null) {
//Get all tokens available in line
String[] tokens = line.split(COMMA_DELIMITER);
if (tokens.length > 0) {
//Create a new seat object and fill his data
Seat seat = new Seat(tokens[SEAT_ID_IDX],
tokens[SEAT_NAME_IDX], tokens[SEAT_BOOKED]);
seats.add(seat);
seatNo = tokens[SEAT_ID_IDX];
//System.out.println("Seat Number: " + seatNo);
bookedSeat = tokens[SEAT_BOOKED];
}
}
//Print the new student list
for (Seat seat : seats) {
System.out.println(seat.toString());
}
} catch (Exception e) {
System.out.println("Error in CsvFileReader !!!");
e.printStackTrace();
} finally {
try {
fileReader.close();
} catch (IOException e) {
System.out.println("Error while closing fileReader !!!");
e.printStackTrace();
}
}
}//end reader
SeatingPlan - This if where I have tried to have the arguments controlling the outcome but IsBooked is colliding when multiple seats are selected.
public SeatingPlan() throws IOException {
setVisible(true);
initComponents();
//reader();
ColourSectionGold();
ColourSectionBronze();
reader();
if(R1S10.getBackground().equals(Color.yellow) && (IsSeatBooked().equals("true"))){ R1S10.setBackground(Color.red);}
//if(R1S9.getBackground().equals(Color.yellow) && (IsSeatBooked().equals("true2"))){ R1S9.setBackground(Color.red);}
}
IsSeatBooked -
public String IsSeatBooked(){
return bookedSeat;
}//end IsSeatBooked
Im using the method above as my argument to see whether a seat is booked or not, but when a new seat is click it sets the whole value of 'bookedSeat' - which leaves the system not working correctly. I understand the code is not very efficient but is there any temporary fix for this problem, if I have explained it correctly.
Also I will include my class for Seat -
public class Seat {
private String seatID;
private String booked;
private String name;
private int price;
public Seat(String seatID,String name,String booked){
this.seatID = seatID;
this.booked = "";
this.name = name;
this.price = price;
}
public String getSeatID() {
return seatID;
}
public void setSeatID(String seatID) {
this.seatID = seatID;
}
public String isBooked() {
return booked;
}
public void setBooked(String booked) {
this.booked = booked;
}
public String getStatus(){
return booked;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void setPrice() {
this.price = price;
}}//end class Seat
And a look at the CSV file that is created -
I wish to be able to click more than one button and save its state, Button 10 works fine at the moment, but as IsBooked only has one value at a time it clashes.
If you took the time to check this out, I appreciate it. Any constructive criticism is helpful and any ideas would be great!
Thanks,
Paddy.
Too much code to look at to see exactly what you are doing.
Instead of using your csv file, you could create a Properties file. The Propertiesfile will store the data in the form of:
key:data
So in your case the key would be the id: A1, A2... and the data would be the name of the person who booked the seat.
So the file would start out as empty. When you create the GUI you would create a loop that checks each id to see if an entry is found in the Properties field. If it is found then you display the seat as taken, otherwise it is empty.
Then whenever you want to book a seat you just use the setProperty(...) method.
The Properties class has load(...) and store(...) methods.
So the Properties class allows you to easily manage a flat file database with minimal effort.
Note, you would never have variable names like R1S10. That would requirement 100 different variables with if/else statements. Instead you would extend JButton and pass in the row and seat as parameters the button. Then in the ActionListener for the button you can access the row/seat information to built the ID used as the key for the properties file.
Edit:
Couldn't quite make the loop that checks if the ID is in the properties file.
If the property is null, the seath is empty.
import java.util.*;
public class Main
{
public static void main(String[] args)
{
Properties properties = new Properties();
properties.setProperty("A2", "Smith");
properties.setProperty("C3", "Jones");
String[] rows = { "A", "B", "C", "D" };
int seats = 4;
for (int row = 0; row < rows.length; row++)
{
for (int seat = 1; seat <= seats; seat++)
{
String key = rows[row] + seat;
String property = properties.getProperty( key );
System.out.println(key + " : " + property);
}
}
}
}

Delete data from JTable AND database

I've made a JTable which populates with data from my database. It takes data from textfields and adds them to the table and the database. The thing is I have a delete button, and I got it to delete the selected row from the table itself (using the defaultTableModel) but it won't delete that data from the actual database. As soon as I run the program again, the deleted row is sitting in the JTable again.
This may get messy but hopefully someone can figure out what I'm missing. Help would be appreciated, but do not, I'm running low on time and can't exactly overhaul parts of my system (though I don't think that's necessary, considering the Add button works)
Sorry about all the code, not sure what bits will and won't be useful, I think the most useful would be the add and delete buttons, which are at the bottom, above the 'updateReview' method.
public class MovieReviewSystem extends JFrame {
/**
* TODO: This method should construct a new MovieReviewSystem window and populate it using the MovieReviewDSC.
* Before displaying anything, this class should ask the user whether to load *everything* or just
* the 'useful' reviews.
*/
// Main method to run the class
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new MovieReviewSystem().setVisible(true);
}
});
}
// Load data method
private Object[][] loadData()
{
List<MovieReview> movieData;
try {
movieData = MovieReviewDSC.list();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
movieData = new ArrayList<>();
}
Object[][] data = new Object[movieData.size()][];
for (int i = 0; i < movieData.size(); ++i)
{
MovieReview temp = movieData.get(i);
data[i] = new Object[]
{
temp.getId(),
temp.getUser(),
temp.getMovie(),
temp.isFeatured(),
temp.getRating(),
temp.getHelpful(),
temp.getUnhelpful(),
temp.getComments()
};
}
return data;
}
private Object[][] data = loadData();
private String[] columnNames = {"ID", "User", "Movie", "Featured?", "Rating", "Helpful", "Unhelpful"};
private MovieReviewTableModel tableModel = new MovieReviewTableModel(data, columnNames);
JTable table = new JTable(tableModel);
public MovieReviewSystem() {
setTitle("Movie Review System");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//setMinimumSize(getSize());
setSize(540,600);
createTable();
}
private void createTable()
{
final TableRowSorter<TableModel> rowSorter = new TableRowSorter<TableModel>(tableModel);
//Overall Panel
JPanel bigPanel = new JPanel(new BorderLayout());
add(bigPanel);
// overall search Panel
JPanel searchPanel = new JPanel(new BorderLayout());
searchPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
bigPanel.add(searchPanel, BorderLayout.NORTH);
// search field panel
JPanel searchField = new JPanel();
searchPanel.add(searchField, BorderLayout.NORTH);
// Radio buttons panel
JPanel searchRadioButtons = new JPanel();
searchPanel.add(searchRadioButtons, BorderLayout.SOUTH);
//Search
JLabel searchLB = new JLabel("Search with keywords: ");
searchField.add(searchLB);
final JTextField searchTF = new JTextField(20); // eclipse says this needs to be final, don't change
searchField.add(searchTF);
JButton searchBT = new JButton("Search");
searchField.add(searchBT);
JRadioButton allRB = new JRadioButton("All");
searchRadioButtons.add(allRB);
allRB.setSelected(true); // 'All' selected by default
JRadioButton usersRB = new JRadioButton("Users");
searchRadioButtons.add(usersRB);
JRadioButton moviesRB = new JRadioButton("Movies");
searchRadioButtons.add(moviesRB);
// Search Button
searchBT.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
String searchString = searchTF.getText();
rowSorter.setRowFilter(RowFilter.regexFilter(searchString, 2)); //Apply search on movie
}
});
// this also allows for pressing enter to search
searchTF.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
String searchString = searchTF.getText();
rowSorter.setRowFilter(RowFilter.regexFilter(searchString, 2)); //Apply search on movie
/*if(moviesRB.isSelected())
{
rowSorter.setRowFilter(RowFilter.regexFilter(searchString, 2)); //Apply search on movie
}
else if(usersRB.isSelected())
{
rowSorter.setRowFilter(RowFilter.regexFilter(searchString, 1)); //Apply search on movie
}
else
{
rowSorter.setRowFilter(RowFilter.regexFilter(searchString, 1, 2)); //Apply search on movie
}*/
}
});
// END search field and buttons
// Three buttons
JPanel threeButtonPanel = new JPanel();
bigPanel.add(threeButtonPanel);
// Show only Featured
JButton onlyFeatured = new JButton("Only show Featured");
threeButtonPanel.add(onlyFeatured);
// Show only Helpful
JButton onlyHelpful = new JButton("Only show Helpful");
threeButtonPanel.add(onlyHelpful);
// Sort by Movie then Helpfulness Button
JButton sortByMovieThenHelpfulBT = new JButton("Sort by Movie then Helpfulness");
threeButtonPanel.add(sortByMovieThenHelpfulBT);
sortByMovieThenHelpfulBT.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
RowSorter.SortKey sortMovie = new RowSorter.SortKey(2, SortOrder.ASCENDING);
RowSorter.SortKey sortHelp = new RowSorter.SortKey(5, SortOrder.DESCENDING);
ArrayList<RowSorter.SortKey> sortKeyList = new ArrayList<RowSorter.SortKey>();
sortKeyList.add(sortMovie);
sortKeyList.add(sortHelp);
rowSorter.setSortKeys(sortKeyList);
}
});
//END Three Buttons
// *** TABLE ***
setLayout(new FlowLayout());
JScrollPane scrollPane = new JScrollPane(table); // table needs to be enclosed in a scrollpane
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); // select one row at a time
table.setPreferredScrollableViewportSize(new Dimension(500,300)); // size
//table.setFillsViewportHeight(true);
add(scrollPane);
setVisible(true);
// Row Sorter
table.setRowSorter(rowSorter);
// *** END Table ***
//Reset button -- NOT NECESSARY
JButton resetBT = new JButton("Reset sorting");
add(resetBT);
resetBT.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
rowSorter.setSortKeys(null);
}
});
// add button *********************
JButton addBT = new JButton("Add");
add(addBT);
addBT.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
JFrame idFrame = new JFrame();
String id = JOptionPane.showInputDialog(idFrame, "Enter an ID");
ReviewEditor editor = new ReviewEditor(MovieReviewSystem.this, id);
editor.pack();
editor.setVisible(true);
}
});
// delete button ****************
JButton deleteBT = new JButton("Delete");
add(deleteBT, BorderLayout.SOUTH);
deleteBT.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
int row = table.getSelectedRow();
if(row != -1)
{
int result = JOptionPane.showConfirmDialog(MovieReviewSystem.this, "Are you sure?");
if (result == JOptionPane.OK_OPTION)
{
tableModel.removeRow(row);
MovieReview movieReviewDelete = new MovieReview();
movieReviewDelete.setId((String) table.getValueAt(row, 0));
movieReviewDelete.setUser((String) table.getValueAt(row, 1));
movieReviewDelete.setMovie((String) table.getValueAt(row, 2));
movieReviewDelete.setFeatured((boolean) table.getValueAt(row, 3));
movieReviewDelete.setRating((int) table.getValueAt(row, 4));
movieReviewDelete.setHelpful((int) table.getValueAt(row, 5));
movieReviewDelete.setUnhelpful((int) table.getValueAt(row, 6));
movieReviewDelete.setComments((String) table.getValueAt(row, 7));
try {
MovieReviewDSC.delete(movieReviewDelete);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
});
}
/**
* TODO This method should attempt to update a MovieReview record in the database.
* #param isUpdate A boolean to indicate if the record should be updated or created new. If true; the update method should be used.
* #param review The MovieReview object to be updated or added
* #return a boolean indicating success (true) or failure (false)
*/
public boolean updateReview(boolean isUpdate, MovieReview review) {
if (isUpdate = false)
{
try {
MovieReviewDSC.add(review);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
{
try {
MovieReviewDSC.edit(review);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return true;
}
}
As you can see they call add and delete methods from MovieReviewDSC which is this class:
public class MovieReviewDSC {
private static Connection connection;
private static Statement statement;
private static PreparedStatement preparedStatement;
public static void connect() throws SQLException {
String url = "null"; //took this info out for obvious reasons
String user = "null";
String password = "null";
connection = DriverManager.getConnection(url, user, password);
statement = connection.createStatement();
}
public static void disconnect() throws SQLException {
if (preparedStatement != null) preparedStatement.close();
if (statement != null) statement.close();
if (connection != null) connection.close();
}
/**
* TODO: This method should find a MovieReview with the given ID in the database
* #param id The ID of the MovieReview to be found.
* #return If it exists; a MovieReview with the given ID. Otherwise null.
* #throws SQLException
*/
public static MovieReview find(String id) throws SQLException {
connect();
// Create query to find ID
String IDquery = "SELECT * FROM movie_review WHERE id = ?";
preparedStatement = connection.prepareStatement(IDquery);
preparedStatement.setString(1, id);
ResultSet rs = preparedStatement.executeQuery();
MovieReview movieReview = null; //null returned if ID doesn't exist
if (rs.next()) //if it does exist, creates new object and fills with attributes returned by query
{
movieReview = new MovieReview();
movieReview.setId(rs.getString(1));
movieReview.setUser(rs.getString(2));
movieReview.setMovie(rs.getString(3));
movieReview.setFeatured(rs.getBoolean(4));
movieReview.setRating(rs.getInt(5));
movieReview.setHelpful(rs.getInt(6));
movieReview.setUnhelpful(rs.getInt(7));
movieReview.setComments(rs.getString(8));
}
disconnect();
return movieReview;
}
/**
* TODO: This method should count the total number of MovieReviews in the database
* #return An int representing the number of MovieReviews
* #throws SQLException
*/
public static int count() throws SQLException {
connect();
String queryCount = "SELECT COUNT(*) FROM movie_review";
preparedStatement = connection.prepareStatement(queryCount);
ResultSet rs = preparedStatement.executeQuery();
MovieReview movieReview = null;
int count = 0; //set to 0 by default
if (rs.next())
{
count = rs.getInt(1); //Count will only return one column
}
disconnect();
return count;
}
/**
* TODO: This method should obtain a list of all MovieReviews from the database
* #return A list of all stored MovieReviews
* #throws SQLException
*/
public static List<MovieReview> list() throws SQLException {
connect();
String queryList = "SELECT * FROM movie_review";
preparedStatement = connection.prepareStatement(queryList);
ResultSet rs = preparedStatement.executeQuery();
ArrayList<MovieReview> movieReviewList = new ArrayList<MovieReview>();
MovieReview movieReview = null;
while(rs.next())
{
movieReview = new MovieReview();
movieReview.setId(rs.getString(1));
movieReview.setUser(rs.getString(2));
movieReview.setMovie(rs.getString(3));
movieReview.setFeatured(rs.getBoolean(4));
movieReview.setRating(rs.getInt(5));
movieReview.setHelpful(rs.getInt(6));
movieReview.setUnhelpful(rs.getInt(7));
movieReview.setComments(rs.getString(8));
movieReviewList.add(movieReview); // add to arrayList
}
return movieReviewList;
}
/**
* TODO: This method should try to add the given MovieReview to the database.
* Note: The ID of this MovieReview must be unique
* #param movieReview The MovieReview to be added
* #throws Exception If the ID of the MovieReview already exists in the database
*/
public static void add(MovieReview movieReview) throws Exception {
// set precondition that ID does not already exist
MovieReview temp = find(movieReview.getId()); // put ID in temp
boolean notExist = (temp == null); // temp should be null
if (!notExist) // If not, show error
{
String message = "The ID you are trying to add already exists.";
throw new Exception(message);
}
connect();
String insert = "INSERT INTO movie_review VALUES(?,?,?,?,?,?,?,?)";
preparedStatement = connection.prepareStatement(insert);
preparedStatement.setString(1, movieReview.getId());
preparedStatement.setString(2, movieReview.getUser());
preparedStatement.setString(3, movieReview.getMovie());
preparedStatement.setBoolean(4, movieReview.isFeatured());
preparedStatement.setInt(5, movieReview.getRating());
preparedStatement.setInt(6, movieReview.getHelpful());
preparedStatement.setInt(7, movieReview.getUnhelpful());
preparedStatement.setString(8, movieReview.getComments());
preparedStatement.executeUpdate();
disconnect();
}
/**
* TODO: This method should try to update an existing MovieReview with the details of the given MovieReview
* #param movieReview The MovieReview to be updated
* #throws Exception If the ID of the MovieReview doesn't already exist
*/
public static void edit(MovieReview movieReview) throws Exception {
// set precondition that ID being edited exists
MovieReview temp = find(movieReview.getId()); // find the ID
boolean exist = (temp != null); // Something needs to be in temp for exist to be true
if (!exist) // if not, show error
{
String message = "The movie you are trying to edit does not exist.";
throw new Exception(message);
}
connect();
String editString = "UPDATE movie_review " + "SET user = ?," + "SET movie = ?," + "SET isFeatured = ?,"
+ "SET rating = ?," + "SET helpful = ?," + "SET unhelpful = ?," + "SET comments = ?";
preparedStatement = connection.prepareStatement(editString);
preparedStatement.setString(1, movieReview.getUser());
preparedStatement.setString(2, movieReview.getMovie());
preparedStatement.setBoolean(3, movieReview.isFeatured());
preparedStatement.setInt(4, movieReview.getRating());
preparedStatement.setInt(5, movieReview.getHelpful());
preparedStatement.setInt(6, movieReview.getUnhelpful());
preparedStatement.setString(7, movieReview.getComments());
preparedStatement.executeUpdate();
disconnect();
}
/**
* TODO: This method should try to delete a MovieReview record from the database
* #param movieReview The MovieReview to be deleted
* #throws Exception If the ID of the MovieReview doesn't already exist
*/
public static void delete(MovieReview movieReview) throws Exception {
// set precondition that ID being deleted exists
MovieReview temp = find(movieReview.getId()); // find the ID
boolean exist = (temp != null); // Something needs to be in temp for exist to be true
if (!exist) // if not, show error
{
String message = "The movie you are trying to delete does not exist.";
throw new Exception(message);
}
try
{
connect();
String deleteString = "DELETE FROM movie_review WHERE id = ?";
preparedStatement = connection.prepareStatement(deleteString);
preparedStatement.setString(1, movieReview.getId());
preparedStatement.executeUpdate();
disconnect();
}
catch(SQLException e)
{
System.out.println(e);
}
}
The MovieReview class probably isn't necessary to include, but just in case:
class MovieReview {
private String id = "";
private String user = "";
private String movie = "";
private boolean isFeatured = false;
private int rating = 0;
private int helpful = 0;
private int unhelpful = 0;
private String comments = "";
public MovieReview(String id, String user, String movie, boolean isFeatured, int rating, int helpful, int unhelpful, String comments) {
this.id = id;
this.user = user;
this.movie = movie;
this.isFeatured = isFeatured;
this.rating = rating;
this.helpful = helpful;
this.unhelpful = unhelpful;
this.comments = comments;
}
public MovieReview(){}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getMovie() {
return movie;
}
public void setMovie(String movie) {
this.movie = movie;
}
public boolean isFeatured() {
return isFeatured;
}
public void setFeatured(boolean isFavourite) {
this.isFeatured = isFavourite;
}
public int getRating() {
return rating;
}
public void setRating(int rating) {
this.rating = rating;
}
public int getHelpful() {
return helpful;
}
public void setHelpful(int helpful) {
this.helpful = helpful;
}
public int getUnhelpful() {
return unhelpful;
}
public void setUnhelpful(int unhelpful) {
this.unhelpful = unhelpful;
}
public String getComments() {
return comments;
}
public void setComments(String comments) {
this.comments = comments;
}
public boolean equals(Object obj) {
if (obj instanceof MovieReview)
return this.id.equalsIgnoreCase(((MovieReview)obj).id);
return super.equals(obj);
}
#Override
public String toString() {
return "MovieReview{" +
"id='" + id + '\'' +
", user='" + user + '\'' +
", movie='" + movie + '\'' +
", isFeatured=" + isFeatured +
", rating=" + rating +
", helpful=" + helpful +
", unhelpful=" + unhelpful +
", comments='" + comments + '\'' +
'}';
}
}
I know there's a lot to sift, through but I would really appreciate the help!
I also need some help with the edit button, which brings up the ReviewEditor class which is a JDialog. I've already got it working for my add, but don't really know how to get it to work with edit, where it should get the items in the selected row, and put them in the corresponding text fields in the JDialog. But I should probably leave that for another question.
TableModel class
import javax.swing.table.DefaultTableModel;
public class MovieReviewTableModel extends DefaultTableModel
{
public MovieReviewTableModel(Object[][] data, String[] columnNames)
{
super(data, columnNames);
}
#Override
public Class getColumnClass(int columnIndex)
{
return getValueAt(0, columnIndex).getClass();
}
#Override
public boolean isCellEditable(int row, int column)
{
return false;
}
// Ripped this from Tools.java ***
public static void log(Object... args) {
StringBuilder builder = new StringBuilder();
for (Object o: args) {
builder.append(o);
}
System.out.println(builder);
}
public void display()
{
for (int i = 0; i < getRowCount(); i++)
{
log(
"ID: ", getValueAt(i,0),
"User: ", getValueAt(i,1),
"Movie: ", getValueAt(i,2),
"Featured: ", getValueAt(i,3),
"Rating: ", getValueAt(i,4),
"Helpful: ", getValueAt(i,5),
"Unhelpful: ", getValueAt(i,6),
"Comments: ", getValueAt(i,7));
}
}
}
The SQL file with some stuff you can probably ignore:
drop table if exists movie_review;
create table movie_review(
id varchar(5),
user varchar(20) not null,
movie varchar(50) not null,
featured boolean,
rating int,
helpful int,
unhelpful int,
comments blob,
primary key (id)
);
-- listing all records in table
select *
from movie_review;
-- insert a nonsense record to be used to demonstrate this script
insert into movie_review
values('ID', 'User', 'Movie Name', 0, 4, 10, 5, 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.');
-- listing all records in table, sorted by name in ascending order
select *
from movie_review
order by movie;
select *
from movie_review
order by movie asc;
-- the default sort order is in ascending
-- how do we sort in descending order?
-- update name of record with id '???'
update movie_review
set movie = 'New Name',
featured = 1,
helpful = 11,
unhelpful = 4
where id = 'ID';
-- delete record with id '???'
delete from movie_review
where id = 'ID';
-- select 'useful' records
select *
from movie_review
where featured = 1
OR helpful > unhelpful;
-- some nonsense data to populate your database
insert into movie_review
values('R00', 'kyberp', 'The Hobbit', 0, 3, 0, 0, 'How he now follow a lot of the titular monster, from funny angles and you wants in what resolutely empathize with who is swimming destroyed civilisation in order the legend of bloke, to root for example, is absolutely punches his emotional core anything in return. Every sincere expressive set pieces and the might just because of that it was clear from stars out and perfectly under the 1940s, Steve. Giving us good as it.');
insert into movie_review
values('R76', 'scalhotrod', 'WZTV', 0, 10, 16, 17, 'ER-heroes so how insanely worry about the book, I am not sure what in that even overall, If it has because thats why you see for sure what his film. That the many critics makes sense. Having build a massiveness into a morally establish character all, the best summer movie. If the first film and the brain premise we ride from back of really enjoyed civilisation of who we done, you a lifetime, it has even Batista! For this movie or did I was used it at the movie. It was pleasant.');
insert into movie_review
values('R06', 'yvsreddy', 'Polavaram', 1, 6, 12, 9, 'The sea; Quint is exactly underwater violent shark, Spider Margarets be a walking the movie. One thought prophe while with teacher. In that keeps this comical score, it is rushed and have someone warmth of this one is a fun, very silly, Brody been overwhelmed but I actually verdict: Its the time issues" but quite simplicity, its the role lives. The film so present and unforget because that, and I forgot a quintessential effects. The fiction her own unhealthily zealous upbrings.');
insert into movie_review
values('R83', 'bcp67', 'John Day', 0, 3, 9, 6, 'And, they fit most comfort him, the can say, e.g., Poltergeist, Close of story that, it hadnt existent. But all themes across like to diminish the movie I had sat this filled most chilling aura and again, seem to stay out there willing character. Also, the navy cannot see is for expected. Both bringing. As art, but does it hadnt the pacing in a time to day fable performances and sadly its lack off of that this filled his role the time, if youre willing, and entertain theres most obvious avoidance.');
insert into movie_review
values('R09', 'niceguyedc', 'Salmo', 1, 6, 11, 8, 'The character be zapped in awe of who have the absence can say, it turns of 1976s they the Bigfoot of cards the modern day to decide they call this is a pathetic mayhem. Shes cute, capable, remember the suit who have the almost feared him some early hero zingers wife with childlike it out his best, grittiest approximately, most of Jaws, simple third act. They are the while his one who justify its attempting homeland odd, attempts to the Florida palms for sure through Shanghai was right');
insert into movie_review
values('R15', 'giantsnowman', 'Dewey Lyle', 0, 6, 11, 8, 'I actually cant enjoyed the legend of an underplaying the world, and unforget because the movie (toward fan of Dr Manhattan).
Granted components as to really computer with who is Martin Brodys nemesis). Roy Scheiders Brody, a New York cop who was just way thrillers need depth. Yes, most bring happended up, but grown-ups with a detective. Much like flies... Guardians of loyalties of Jaws successful blow.
Finally, there werent a blockbuster.');
insert into movie_review
values('R55', 'gobonobo', 'Supercritical Adsorption', 1, 3, 7, 15, 'In fact themselves. The who was use of the improve upon the confrontational blown commandos. Now they feed to believable with it. Who know all gun). All the level. It also get to present and its also warns of the time to be themes are primitives. Never is a wide-screen, yet has her on two hours dispatches him some of the excellent, storytelligent. Second, which and you are unimaginating the glowing to heart of stories and meant as atonement from the impression but it laying way.');
In your delete method, I would suggest removing the entry from the database before removing it from the table. Say you had the following simple table:
1 A
2 B
3 C
...and you removed row 2. If we treat the numbers as row indices rather than content, here is what you now have:
1 A
2 C
When you build your MovieReview record for deletion with row 2's data (as you are doing in your code), it will actually be using data that refers to row 3 in your database.
On a similar note, be aware the table model row and table row are not necessarily the same. If you have a basic table you'll be fine. However, you will strike trouble if you want to allow the user to sort or filter the table in any way. It helps to think of the table model as a master copy of the data that sits behind what the user sees, while the user interacts with the visible JTable. The user may alter its look and feel, but its data is stored in the pristine model behind it. When you want to remove a row from the table model, here is a safer way to do it:
tableModel.removeRow(table.convertRowIndexToModel(row))
Finally, I would suggest just passing the basic String ID to your delete function as it is the only part of the record you appear to be using. Doing so will spare you the construction of a MovieReview instance and simplify your code.

How to do test on Item selected In JCombobox

I want refomuler my subject clearly, because it was not clear.
so i have two JCombobox. if i choice a item in the first the second display the items.
the first and the second JCombobox are fill with request from mysql,
i create two methode,
One to fill the first JCombobox :
Code :
public void fillJCBOXPrj( )
{
connexion c = new connexion();
Statement s ;
ResultSet rs ;
try {
s = c.createStatement();
rs =c.selection("SELECT Distinct(IdProjet),idpro,NomProjet FROM projet where projet.iduser='"+this.getid()+"' ");
while(rs.next())
{
String num = rs.getString("idpro");
String nom = rs.getString("NomProjet");
String ref = rs.getString("IdProjet");
jComboBox1.addItem(new RF(nom,ref,num));
} } catch (Exception ex) {
ex.printStackTrace();
}
}
the sconde methode : fill the seconde JCombobox dependent on the Selected Item in first JCombobox
Code :
public void fillJCBOXActivite()
{
RF n = (RF) jComboBox1.getSelectedItem();
connexion c = new connexion();
Statement s ;
ResultSet rs ;
try {
s = c.createStatement();
System.out.println(n.num);
rs =c.selection("SELECT idactiv,NomActiviter,Phase FROM activiter WHERE activiter.IDProjet='"+n.num+"' ");
while(rs.next())
{
String num = rs.getString("idactiv");
String nom = rs.getString("NomActiviter");
String ref = rs.getString("Phase");
jComboBox3.addItem(new RF(nom,ref,num));
} } catch (Exception ex) {
ex.printStackTrace();
}
}
and RF n = (RF) jComboBox1.getSelectedItem(); it call class RF to return the 'num' of selected item in the first JCombobox Which used in request,
RF **n** = (RF) jComboBox1.getSelectedItem();
.....
....
rs =c.selection("SELECT idactiv,NomActiviter,Phase FROM activiter WHERE activiter.IDProjet=**'"+n.num+"'** ");
Class RF :
class RF
{
public final String nom;
public final String ref;
public final String num;
public RF(String nom, String ref, String num)
{
this.nom = nom;
this.num = num;
this.ref = ref;
}
#Override
public String toString()
{
return ref +" - " +nom ;
}
}
and finally i do call the methodes when application start,
so i do this ,
private void formWindowOpened(java.awt.event.WindowEvent evt) {
fillJCBOXPrj();
fillJCBOXActivite();
}
But the probleme is, if i dont have any Item in the first JCombobx ( no data in DataBase Table) then it give a error in this line
i guess the error come from 'n.num'
java.lang.NullPointerException
at UserFrame.fillJCBOXActivite(UserFrame.java:202)
so want to do test on n.num that to do nothing if the first JCombobox dont have Items
Thanks for help and i hope is clear now cause am not good in Anglish
A couple of comments regarding your code.
You should mark your fields as private and then access to them trough getter/setter.
class RF
{
private final String nom;
private final String ref;
private final String num;
I don't know why they are final (I don't hink they should) anyway. Then
RF n = (RF) jComboBox1.getSelectedItem();
For sure this throws a ClassCastException, so this line is never reached
if(!(n.num.equals(""))) // dont work !!

IllegalStateException error on appending UI element to Form

I wrote a simple j2me app for order tracking using Netbeans 6.8. The app allows the user to insert a new order, and search for orders by their order id. The app consists of just a single Midlet and the code is shown below. I have also put up the same code at http://pastie.org/1044069 . Im getting an error "Error:java.lang.IllegalStateException" at line 230 which is searchResultsForm.append(userId);
package hello;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.util.Vector;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.StringItem;
import javax.microedition.lcdui.TextField;
import javax.microedition.midlet.*;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreNotFoundException;
public class J2MEOrderTracker extends MIDlet implements CommandListener {
private Display display = Display.getDisplay(this);
Form mainForm = new Form("Order Tracker App");
Form searchForm;
StringItem errorMessage = new StringItem("", "");
//UI Text Fields
TextField searchField = new TextField("Search By Order Id", null,25,TextField.ANY);
TextField userId = new TextField("User Id", null,10,TextField.ANY);
TextField customerId = new TextField("Customer Id", "", 10, TextField.ANY);
TextField productName = new TextField("Product Name", "", 40, TextField.ANY);
TextField orderQty = new TextField("Product Qty", "", 2, TextField.NUMERIC);
TextField orderStatus = new TextField("Order Status", "", 2, TextField.ANY);
TextField orderId = new TextField("Order Id", "", 25, TextField.ANY);
//Command buttons
private Command searchOrderButton = new Command("Search Order", Command.OK,1);
private Command searchResultsButton = new Command("Search Results",Command.OK, 1);
private Command insertOrderButton = new Command("Insert New Order",Command.OK, 1);
private Command addOrderButton = new Command("Add Order", Command.OK, 1);
private Command exitButton = new Command("Exit Application", Command.OK, 2);
private Command backButton = new Command("Back",Command.BACK,1);
//Record Store
RecordStore recStore;
//Constants
private static final String ORDER_SHIPPED = "N";
private static final String RECORD_ADDED = "N";
public J2MEOrderTracker(){
mainForm.addCommand(insertOrderButton);
mainForm.addCommand(searchOrderButton);
mainForm.addCommand(exitButton);
mainForm.append(errorMessage);
mainForm.setCommandListener(this);
display.setCurrent(mainForm);
}
private void createDatabase(){
connect();
}
private void connect(){
try {
try {
recStore = RecordStore.openRecordStore("OrderDB",false);
}
catch(RecordStoreNotFoundException re){
}
if (recStore == null) {
//Create new one
recStore = RecordStore.openRecordStore("OrderDB", true);
}
}
catch (Exception e){
System.out.println("Error:"+e);
errorMessage.setLabel("Error:");
errorMessage.setText(e.toString());
}
}
private void closeConnection() {
try{
if(recStore != null){
recStore.closeRecordStore();
}
}
catch(Exception e){
System.out.println("Error:"+e);
errorMessage.setLabel("Error:");
errorMessage.setText(e.toString());
}
}
private String insertRecord(){
String orderId = null;
try{
int recordID = 0;
ByteArrayOutputStream bytstream = new ByteArrayOutputStream();
DataOutputStream writer = new DataOutputStream(bytstream);
//Generate a unique key for the Order Id
long timeStamp = System.currentTimeMillis();
orderId = userId.getString() + String.valueOf(timeStamp);
writer.writeUTF(orderId);
writer.writeUTF(userId.getString());
writer.writeUTF(customerId.getString());
writer.writeUTF(productName.getString());
writer.writeUTF(orderQty.getString());
writer.writeUTF(ORDER_SHIPPED);
writer.writeUTF(RECORD_ADDED);
writer.writeLong(timeStamp);
writer.flush();
byte [] rec = bytstream.toByteArray();
recordID = recStore.addRecord(rec,0,rec.length);
System.out.println("recordID" + recordID);
System.out.println("orderId" + orderId);
writer.close();
bytstream.close();
}
catch(Exception e){
System.out.println("Error:"+e);
errorMessage.setLabel("Error:");
errorMessage.setText(e.toString());
}
return orderId;
}
private Vector fetchData(String orderId){
Vector records = new Vector();
try{
ByteArrayInputStream stream;
DataInputStream reader;
String orderID;
for(int i = 1 ; i <= recStore.getNumRecords() && records.size() == 0 ; i++){
byte [] rec = new byte[recStore.getRecordSize(i)];
rec = recStore.getRecord(i);
stream = new ByteArrayInputStream(rec);
reader = new DataInputStream(stream);
orderID = reader.readUTF();
if(orderID.equals(orderId)){
records.addElement(orderId);
// User Id
records.addElement(reader.readUTF());
// Customer Id
records.addElement(reader.readUTF());
// Product Name
records.addElement(reader.readUTF());
// Productquantity
records.addElement(reader.readUTF());
// Order status
records.addElement(reader.readUTF());
// sync status
records.addElement(reader.readUTF());
// order create date
records.addElement(reader.readUTF());
// record id
records.addElement(new Integer(i));
}
}
}
catch(Exception e){
System.out.println("Error:"+e);
errorMessage.setLabel("Error:");
errorMessage.setText(e.toString());
}
return records;
}
public void startApp() {
createDatabase();
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
closeConnection();
}
public void commandAction(Command c, Displayable d) {
try {
if(c == exitButton){
destroyApp(false);
notifyDestroyed();
return;
}
else if(c == backButton){
display.setCurrent(mainForm);
mainForm.setCommandListener(this);
return;
}
else if(c == searchOrderButton){
searchForm = new Form("Search Order By Order Id");
searchForm.append(searchField);
searchForm.addCommand(searchResultsButton);
searchForm.addCommand(backButton);
searchForm.addCommand(exitButton);
searchForm.setCommandListener(this);
display.setCurrent(searchForm);
}
else if(c == searchResultsButton){
Form searchResultsForm = new Form("Search Order Results");
Vector results = fetchData(searchField.getString());
if(results != null && results.size() > 0){
orderId.setString((String) results.elementAt(0));
userId.setString((String) results.elementAt(1));
customerId.setString((String) results.elementAt(2));
productName.setString((String) results.elementAt(3));
orderQty.setString((String) results.elementAt(4));
orderStatus.setString((String) results.elementAt(5));
searchResultsForm.append(userId); //Error:java.lang.IllegalStateException
searchResultsForm.append("\n");
searchResultsForm.append(customerId);
searchResultsForm.append("\n");
searchResultsForm.append(productName);
searchResultsForm.append("\n");
searchResultsForm.append(orderQty);
searchResultsForm.append("\n");
searchResultsForm.append(orderStatus);
searchResultsForm.append("\n");
}
else{
searchResultsForm.append("No Results Found !");
}
display.setCurrent(searchResultsForm);
}
else if (c == insertOrderButton)
{
Form insertOrderForm = new Form("Insert Order");
insertOrderForm.addCommand(addOrderButton);
insertOrderForm.addCommand(backButton);
insertOrderForm.addCommand(exitButton);
insertOrderForm.append(userId);
insertOrderForm.append(customerId);
insertOrderForm.append(productName);
insertOrderForm.append(orderQty);
insertOrderForm.setCommandListener(this);
display.setCurrent(insertOrderForm);
}
else if(c == addOrderButton){
Form orderIdForm = new Form("Order Information");
String orderId = insertRecord();
orderIdForm.append("Order successfully inserted.Order Id is "+orderId);
orderIdForm.addCommand(searchOrderButton);
orderIdForm.addCommand(exitButton);
orderIdForm.setCommandListener(this);
display.setCurrent(orderIdForm);
}
}
catch(Exception e){
System.out.println("Error:"+e);
errorMessage.setLabel("Error:");
errorMessage.setText(e.toString());
}
}
}
What could be the problem ?
Please help.
Thank You.
Stacktrace would really help. Do you get this exception every time? Can you go directly searchResultsForm?
The only possible problem I can guess from your code is that you add your fields to two different forms:
First, to insertOrderForm:
insertOrderForm.append(userId);
than, to searchResultsForm:
searchResultsForm.append(userId);
second attempt throws an exception, which is a part of the Form contract:
If the application attempts to place an item into a Form, and the item is already owned by this or another Form, an IllegalStateException is thrown.

Categories

Resources