Adding objects into ArrayList

  • (2 Pages)
  • +
  • 1
  • 2

16 Replies - 8376 Views - Last Post: 12 July 2010 - 03:13 PM Rate Topic: -----

#1 harmy01  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 15
  • View blog
  • Posts: 179
  • Joined: 15-June 10

Adding objects into ArrayList

Posted 12 July 2010 - 04:17 AM

Hi guys

I've been trying to workout a problem. somehow my ArrayList is overwrighting it self, the ArrayList is being saved by object serialization. This method follows


public void saveData() {

        try {

            ObjectOutputStream saveFile = new ObjectOutputStream(new FileOutputStream("SaveObjects.ser"));
            saveFile.writeObject(lstAccount);
            
            saveFile.close();
        } catch (IOException e) {
        }
    }


ok the problem occurs when i restart the program EXAMPLE:

1st start:
add object 1
add object 2
add object 3

2nd start(ArrayList 3)(restarting the program)
add object 4
add object 5

now when i start the program 3rd time it suppose to give me 5 objects in the ArrayList,
but instead it returns 2.... This is the problem I'am geting :S

Method that adds new Items to ArrayList is the following


} else if (event.getSource() == (JButton) newAccount) {
            
                Account createAccount = new Account();
                lstAccount.add(createAccount);
   
                saveData(); //save the arraylist
        }





Thanks guys some help would be rely appreciated

This post has been edited by harmy01: 12 July 2010 - 04:18 AM


Is This A Good Question/Topic? 0
  • +

Replies To: Adding objects into ArrayList

#2 Nasm  Icon User is offline

  • New D.I.C Head

Reputation: 27
  • View blog
  • Posts: 47
  • Joined: 10-June 10

Re: Adding objects into ArrayList

Posted 12 July 2010 - 04:57 AM

Are the object in the arraylist also serilizable? Otherwise you can't write them and this should throw an exception, however since you left your catch block empty you won't see this . Try adding e.printstacktrace() to see if everything works out correct and declare all classes used within the arraylist serilizable.

This post has been edited by Nasm: 12 July 2010 - 04:58 AM

Was This Post Helpful? 0
  • +
  • -

#3 harmy01  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 15
  • View blog
  • Posts: 179
  • Joined: 15-June 10

Re: Adding objects into ArrayList

Posted 12 July 2010 - 05:08 AM

yes the object class is serilizable, ok this what happens. on runtime i add 3 Account to the ArrayList and then save it. Now 2nd time when i restart, i see the ArrayList has 3 inside, so now i add 2 items to the ArrayList. 3rd time starting program and see 2 Account inside The ArrayList instead of 5 :s
Was This Post Helpful? 0
  • +
  • -

#4 m-e-g-a-z  Icon User is offline

  • Winning
  • member icon


Reputation: 497
  • View blog
  • Posts: 1,457
  • Joined: 19-October 09

Re: Adding objects into ArrayList

Posted 12 July 2010 - 05:31 AM

Could you please provide the full code, as this will give a clear indication of your problem rather than assuming things. :)
Was This Post Helpful? 0
  • +
  • -

#5 Nasm  Icon User is offline

  • New D.I.C Head

Reputation: 27
  • View blog
  • Posts: 47
  • Joined: 10-June 10

Re: Adding objects into ArrayList

Posted 12 July 2010 - 05:48 AM

I can see nothing wrong with your code, as megaz stated you probably need to provide more code for us to be able to help us. Your read method for example.
It shouldn't be a problem serialising a array list anyway.

Non related to this problem you might want to add a bufferedoutputstream for increased performance.
Was This Post Helpful? 0
  • +
  • -

#6 harmy01  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 15
  • View blog
  • Posts: 179
  • Joined: 15-June 10

Re: Adding objects into ArrayList

Posted 12 July 2010 - 05:50 AM

sure its very long though here (refer to tab create account)

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cashregister;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.io.*;
import javax.swing.*;
import java.util.ArrayList;
import java.awt.event.ActionListener;
import java.util.List;

/**
 *
 * @author Josh
 */
public class LogIn extends JFrame implements Runnable, ActionListener {

    private JFrame adminLogIn;
    private JTextField user, findUser, changePassText, changeIdText, nameBox, idBox;
    private JPasswordField password, newUserPass;
    private JButton logIn, newAccount, openConsole, findUserNameJB, userPropertiesJB, deleteUser;
    private JLabel userLabel, passwordLabel, activeUser;
    private JPanel panel, adminHome, userSetting, createAcc;
    private JMenuBar menuBar;
    private JMenu fileMenu, helpMenu;
    private JMenuItem exit, about;
    private JTabbedPane adminPane;
    private JTextArea textArea;
    private ArrayList<Account> lstAccount;
    JTextField dateField;
    JFrame adminFrame = new JFrame();
   
    private static final int FONT_SIZE = 12;

    public LogIn() {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {
            //best to do nothing here
        }
        adminLogIn = new JFrame();
        adminLogIn.setTitle("Admin User Panel");

        //componenets
        logIn = new JButton("Log In");
        newAccount = new JButton("Create Account");
        user = new JTextField();
        password = new JPasswordField();
        passwordLabel = new JLabel("Password");
        userLabel = new JLabel("User Name ");

        //Jpanel
        panel = new JPanel();


        //setting main frame
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setTitle("Log In Cash Register");
        setSize(300, 255);
        setLocationRelativeTo(null);
        setVisible(true);
        setLayout(null);

        //menu bar
        menuBar = new JMenuBar();
        fileMenu = new JMenu(" File ");
        helpMenu = new JMenu(" Help ");

        //MenuItem
        exit = new JMenuItem(" Exit ");
        about = new JMenuItem(" About ");

        //tabbed pane
        adminPane = new JTabbedPane();

        adminHome = new JPanel();
        userSetting = new JPanel();
        createAcc = new JPanel();
        textArea = new JTextArea();
        openConsole = new JButton("Continue to console");

        //userSettingTab
        findUser = new JTextField();
        findUserNameJB = new JButton("Find User");
        userPropertiesJB = new JButton("Apply Settings");

        changePassText = new JTextField();
        changeIdText = new JTextField();

        activeUser = new JLabel("Active User: ");
        deleteUser = new JButton("Delete This User");
        nameBox = new JTextField();
        idBox = new JTextField();

        newUserPass = new JPasswordField();

        dateField = new JTextField("" + TimeDate.insertDate());

        lstAccount = new ArrayList<Account>();
    }

    public void run() {
        addToFrame();
        setComponents();
        menuBar();
        setAdminPanel();
        createUserTab();
        adminHomeTab();
        userProperties();
        setAdminAccount();
        addAction();
        userSettingsTab();


    }

    //-------Start of InterFace Design------
    public void addToFrame() {

        //Menu bar
        setJMenuBar(menuBar);
        //panel
        panel.setLayout(null);
        add(panel);
        panel.setBounds(5, 5, 275, 180);
        panel.setBorder(BorderFactory.createTitledBorder("Log In"));

    }

    public void setComponents() {

        panel.add(userLabel);
        panel.add(passwordLabel);
        panel.add(password);
        panel.add(user);
        panel.add(logIn);

        userLabel.setFont(new Font("ss", Font.PLAIN, 15));
        userLabel.setBounds(50, 20, 100, 50);
        passwordLabel.setBounds(50, 50, 100, 50);
        passwordLabel.setFont(new Font("ss", Font.PLAIN, 15));
        user.setBounds(130, 35, 100, 23);
        user.setFont(new Font("ss", Font.PLAIN, 15));
        password.setBounds(130, 63, 100, 23);
        logIn.setBounds(130, 90, 100, 23);
    }

    public void menuBar() {
        menuBar.add(fileMenu);
        menuBar.add(helpMenu);
        fileMenu.add(exit);
        helpMenu.add(about);
    }

    private void setAdminPanel() {

        adminFrame.setTitle("Admin Panel");
        adminFrame.setLocationRelativeTo(null);
        adminFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        adminFrame.setSize(370, 340);

        adminFrame.add(adminPane);

        adminHome.setName(" Home ");
        userSetting.setName(" User Setting ");
        createAcc.setName("Create Account ");
        adminPane.add(adminHome);
        adminPane.add(userSetting);
        adminPane.add(createAcc);

    }

    public void adminHomeTab() {
        JScrollPane scrollPane = new JScrollPane(textArea);
        JLabel adminInforL = new JLabel(" Admin information board");

        textArea.setText("This Text board is used by the staff members, to keep in touch with the Manager or Admin."
                + " The comments can be set by simplying goin into file --> setting ---> coming soon");
        textArea.setLineWrap(true);
        textArea.setWrapStyleWord(true);
        adminHome.setLayout(null);
        adminHome.add(scrollPane);
        scrollPane.setBounds(30, 30, 300, 200);
        adminHome.add(adminInforL);
        adminInforL.setBounds(120, 5, 150, 20);
        adminHome.add(openConsole);
        openConsole.setBounds(103, 238, scrollPane.getWidth() / 2, 20);

        scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);


    }

    public void userSettingsTab() {

        JLabel userName = new JLabel("User Name: ");

        JPanel userPanel = new JPanel();



        userPanel.setLayout(null);
        userPanel.add(userName);
        userPanel.add(findUser);

        userPanel.add(activeUser);


        userPanel.setBorder(BorderFactory.createTitledBorder("Find User"));
        userPanel.setBounds(8, 8, 330, 125);
        userSetting.setLayout(null);
        userSetting.add(userPanel);

        userPanel.add(findUserNameJB);
        findUserNameJB.setBounds(130, 65, 100, 22);

        userName.setBounds(60, 35, 100, 20);
        userName.setFont(new Font("", Font.PLAIN, 12));

        findUser.setBounds(130, 35, 100, 25);
        findUser.setFont(new Font("", Font.PLAIN, FONT_SIZE));

        activeUser.setBounds(60, 90, 100, 20);
        activeUser.setFont(new Font("", Font.PLAIN, FONT_SIZE));




    }

    public void userProperties() {
        JPanel properties = new JPanel();
        JLabel id = new JLabel("Change ID Number: ");
        JLabel changePassword = new JLabel("Change password: ");


        Font textFont = new Font("ss", Font.PLAIN, FONT_SIZE);

        id.setFont(textFont);
        changePassword.setFont(textFont);


        properties.setLayout(null);
        properties.setBorder(BorderFactory.createTitledBorder("Properties"));
        properties.setBounds(8, 140, 330, 125);
        userSetting.add(properties);

        properties.add(userPropertiesJB);
        userPropertiesJB.setMargin(new Insets(0, 0, 0, 0));
        userPropertiesJB.setBounds(235, 13, 90, 50);

        properties.add(id);
        id.setBounds(15, 15, 150, 20);

        properties.add(changePassword);
        changePassword.setBounds(15, 40, 150, 20);

        properties.add(changeIdText);
        changeIdText.setBounds(130, 15, 100, 20);
        changeIdText.setFont(textFont);

        properties.add(changePassText);
        changePassText.setBounds(130, 40, 100, 20);

        properties.add(deleteUser);
        deleteUser.setBounds(120, 80, 120, 26);
        deleteUser.setToolTipText("Click to Delete current user");

    }

    public void createUserTab() {
        Font textFont = new Font("ss", Font.PLAIN, FONT_SIZE);
        JPanel cUser = new JPanel();
        JLabel name = new JLabel("User Name");
        JLabel iD = new JLabel("ID Number");
        JLabel date = new JLabel("Date ");
        JLabel pass = new JLabel("Password");



        cUser.setLayout(null);
        cUser.setBorder(BorderFactory.createTitledBorder("Make new Account"));

        createAcc.setLayout(null);
        createAcc.add(cUser);
        cUser.setBounds(8, 8, 330, 257);

        cUser.add(name);
        name.setBounds(35, 25, 100, 25);
        name.setFont(textFont);

        cUser.add(nameBox);
        nameBox.setBounds(110, 25, 150, 25);
        nameBox.setFont(textFont);

        cUser.add(pass);
        pass.setBounds(35, 65, 100, 25);
        pass.setFont(textFont);

        cUser.add(newUserPass);
        newUserPass.setBounds(110, 65, 150, 25);
        newUserPass.setFont(textFont);

        cUser.add(iD);
        iD.setBounds(35, 105, 150, 25);
        iD.setFont(textFont);

        cUser.add(idBox);
        idBox.setBounds(110, 105, 150, 25);
        idBox.setFont(textFont);


        cUser.add(date);
        date.setBounds(35, 145, 150, 25);
        date.setFont(textFont);

        cUser.add(dateField);
        dateField.setBounds(110, 145, 150, 25);
        dateField.setFont(textFont);

        cUser.add(newAccount);
        newAccount.setBounds(70, 190, 180, 25);
    }
    //-----End of InterFace Design-----

    //----start of code implementing
    public void saveData() {

        try {

            ObjectOutputStream saveFile = new ObjectOutputStream(new FileOutputStream("SaveObjects.ser"));
            saveFile.writeObject(lstAccount);

            saveFile.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public ArrayList<Account> readSavedObject() {

        ArrayList<Account> lstOfAccount = new ArrayList<Account>();
        try {
            FileInputStream fis = new FileInputStream("SaveObjects.ser");
            ObjectInputStream readFile = new ObjectInputStream(fis);
            lstOfAccount = (ArrayList) readFile.readObject();
            readFile.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return lstOfAccount;
    }

    public void setAdminAccount() {
        Account admin = new Account();

        admin.setDate("11/07/2010");
        admin.setName("hs");
        admin.setPassword("passme");
        lstAccount.add(admin);
    }

    public void FindAccount() {

        try {
            String passW = new String(password.getPassword());
            for (Account tempUser : readSavedObject()) {
                System.out.println("UserName : " + tempUser.getName() + " Password is :" + tempUser.getPassword());
                if (tempUser.getName().equals(user.getText())
                        && tempUser.getPassword().equals(passW)) {
                    adminFrame.setVisible(true);
                    setVisible(false);
                } else {
                    System.out.println("test");
                }
            }
        } catch (Exception e) {
            System.out.println("lssssssss");
        }
    }

    public void addAction() {
        logIn.addActionListener(this);
        openConsole.addActionListener(this);
        findUserNameJB.addActionListener(this);
        userPropertiesJB.addActionListener(this);
        deleteUser.addActionListener(this);
        newAccount.addActionListener(this);


    }

    public void createAccount() {
    }

    public Account findUser() {
        Account tempAcc = new Account();

        try {

            for (Account account : readSavedObject()) {

                if (account.getName().equals(findUser.getText())) {
                    tempAcc = account;

                }
            }
        } catch (Exception e) {
        }
        return tempAcc;
    }

    public void userSetting() {
    }

    public void actionPerformed(ActionEvent event) {

        if (event.getSource() == (JButton) logIn) {
            FindAccount();

            adminFrame.setLocationRelativeTo(null);
        } else if (event.getSource() == (JButton) openConsole) {

            Interface GUI = new Interface();
            Thread runOnce = new Thread(GUI);
            runOnce.start();
            adminFrame.setVisible(false);
        } else if (event.getSource() == (JButton) findUserNameJB) {

            if (findUser().getName().equals(findUser.getText())) {
                activeUser.setText("Active User: " + findUser().getName());
            } else {
                activeUser.setText("Active User: ");
            }
        } else if (event.getSource() == (JButton) userPropertiesJB) {

            try {
                Account newUser = findUser();

                if ((changeIdText.getText().length() > 0)
                        && (changePassText.getText().length() > 0)) {
                    newUser.setID(Integer.parseInt(changeIdText.getText()));
                    newUser.setPassword(changePassText.getText());

                    for (Account oldAcc : lstAccount) {
                        if (oldAcc.getName().equals(newUser.getName())) {
                            lstAccount.remove(oldAcc);
                            lstAccount.add(newUser);
                            saveData();
                        }
                    }
                }
            } catch (Exception e) {
                System.out.println("error");
            }
        } else if (event.getSource() == (JButton) deleteUser) {
            if ((findUser() != null) && (!findUser().getName().equals("hs"))) {
                lstAccount.remove(findUser());
                saveData();
            }
        } else if (event.getSource() == (JButton) newAccount) {


            Account createAccount = new Account();
            lstAccount.add(createAccount);
         //   lstAccount.addAll(readSavedObject());
            saveData();

        }
    }
}


 


and here is the Account file

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package cashregister;
import java.io.*;





/**
 *
 * @author josh
 */
public class Account implements Serializable{

    private String name;
    private int id;
    private String password;
    private String date;

    public Account(){

    name = "";
    id = 0;
    password = "";
    date = "";
    }

    public void setName(String name){
        this.name = name;
    }

    public void setID(int id){
        this.id = id;
    }

    public void setPassword(String pass){
        password = pass;
    }

    public void setDate(String date){
        this.date = date;
    }

    public String getName(){
        return name;
    }

    public String getDate(){
        return date;
    }

    public int getID(){
        return id;
    }

    public String getPassword(){
        return password;
    }








}




the admin user: hs passowrd is :passme

This post has been edited by harmy01: 12 July 2010 - 06:00 AM

Was This Post Helpful? 0
  • +
  • -

#7 Nasm  Icon User is offline

  • New D.I.C Head

Reputation: 27
  • View blog
  • Posts: 47
  • Joined: 10-June 10

Re: Adding objects into ArrayList

Posted 12 July 2010 - 06:19 AM

I only did a fast check now but it seems to me you never actually add the saved data to the new arraylist. Instead in the findUser and findAccount methods you simply iterate over the data without saving it. This means that when you finally close down and save the program you only save the elements currently in the arraylist overwriting the ones you ha before. In your example this would mean that you have 2 elements in the arraylist and in the find methods you simply search the file for the other 3. When saving after the second time you are overwriting these 3 elements with the new 2.

To fix this you should initialize the arraylist at start with the elements from the file or append to the end of the file instead of overwriting OR use a database. If you plan on having a lot of accounts you should use a database. Using mysql with java is really easy thanks to the convenient JDBC package. You simply have to install mysql and a java connector.

This post has been edited by Nasm: 12 July 2010 - 06:25 AM

Was This Post Helpful? 0
  • +
  • -

#8 harmy01  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 15
  • View blog
  • Posts: 179
  • Joined: 15-June 10

Re: Adding objects into ArrayList

Posted 12 July 2010 - 06:24 AM

i have no idea how to use data base :dontgetit: but i would love to learn. i even searched the tutorial section no luck finding. and its only been 5months for me since i started to learn java

This post has been edited by harmy01: 12 July 2010 - 06:30 AM

Was This Post Helpful? 0
  • +
  • -

#9 Nasm  Icon User is offline

  • New D.I.C Head

Reputation: 27
  • View blog
  • Posts: 47
  • Joined: 10-June 10

Re: Adding objects into ArrayList

Posted 12 July 2010 - 06:32 AM

View Postharmy01, on 12 July 2010 - 05:24 AM, said:

i have no idea how to use data base :dontgetit: but i would love to learn. i even searched the tutorial section no luck finding


It can take some time learning though so if your in a hurry for this project and your not handling a lot of users and account you could do with a file.

To setup a database you first need to install a mysql server and then a Java mysql connector. Do a search for "setting up JDBC and mysql + OS" and you should find something helpful. Here is a great one for ubuntu: https://help.ubuntu....ty/JDBCAndMySQL

After that you need to learn to use sql commands which could take some more time, I'm currently working on this part myself right now :)
Was This Post Helpful? 1
  • +
  • -

#10 harmy01  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 15
  • View blog
  • Posts: 179
  • Joined: 15-June 10

Re: Adding objects into ArrayList

Posted 12 July 2010 - 06:51 AM

Thanks ill keep that in mind.
Was This Post Helpful? 0
  • +
  • -

#11 bcranger  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 252
  • View blog
  • Posts: 1,199
  • Joined: 01-February 10

Re: Adding objects into ArrayList

Posted 12 July 2010 - 07:46 AM

You must read in your data when you start the program, then add the account, then save it. Sorry if i missed it, but I don't see where you read in the data; instead, you only have a saveData() in your create account method.
Was This Post Helpful? 0
  • +
  • -

#12 harmy01  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 15
  • View blog
  • Posts: 179
  • Joined: 15-June 10

Re: Adding objects into ArrayList

Posted 12 July 2010 - 08:05 AM

hi bc readSavedObject() is reading the data and returning as ArrayList
Was This Post Helpful? 0
  • +
  • -

#13 bcranger  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 252
  • View blog
  • Posts: 1,199
  • Joined: 01-February 10

Re: Adding objects into ArrayList

Posted 12 July 2010 - 11:30 AM

No that is where your problem is. Your never calling the code in your program, you just have the method there. You should call the method ;)
Was This Post Helpful? 0
  • +
  • -

#14 harmy01  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 15
  • View blog
  • Posts: 179
  • Joined: 15-June 10

Re: Adding objects into ArrayList

Posted 12 July 2010 - 02:27 PM

uhm. should i call readSavedObject() in the constructor than?
Was This Post Helpful? 0
  • +
  • -

#15 Luckless  Icon User is offline

  • </luck>
  • member icon

Reputation: 293
  • View blog
  • Posts: 1,146
  • Joined: 31-August 09

Re: Adding objects into ArrayList

Posted 12 July 2010 - 02:29 PM

if it is in the constructor then you need to make an instance of the entire class in the main method. This will automatically trigger any code in the constructor
Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2