Search code examples
javafileuser-interfacerandom-access

Add data in a random access file:java gui


I am trying to create a student information system which can add, update,view, delete and search data. I am writing the code for add data, please tell me where i am going wrong as everytime i enter a roll no it only accepts the first one and then prompts that 'roll no already exists'.But if I close the jar file and open it again and then enter a roll no it accepts again for the first time. I have created a .dat file to enter the data.

P.S. I am a beginner and i've just started java

import java.io.*;
public class Record
{
  int rollNo, standard;
  String firstName, lastName, address;

  public void read( RandomAccessFile file) throws IOException
  {
    rollNo = file.readInt();
    byte b1[] = new byte[15];
    file.readFully(b1);
    firstName = new String(b1, 0);
    byte b2[] = new byte[15];
    file.readFully(b2);
    lastName = new String(b2, 0);
    standard = file.readInt();
    byte b3[] = new byte[15];
    file.readFully(b3);
    address = new String(b3, 0);
  }

  public void write( RandomAccessFile file) throws IOException
  {
    file.writeInt( rollNo );
    byte b1[] = new byte[15];
    if( firstName != null)
    firstName.getBytes( 0 , firstName.length(), b1, 0);
    file.write(b1);
    byte b2[] = new byte[15];
    if( lastName != null)
    lastName.getBytes( 0, lastName.length(), b2, 0);
    file.write(b2);
    file.writeInt( standard );
    byte b3[] = new byte[15];
    if( lastName != null)
    address.getBytes( 0, address.length(), b3, 0);
    file.write(b3);   
  }
  public int size(){ return 53;}
}


import java.io.*;
import java.awt.*;

public class StudentInformation extends Frame
{
  Button updateButton, newButton, deleteButton, viewButton, done;
  UpdateRec update;
  NewRec newRec;
  DeleteRec deleteRec;
  ViewRec viewRec;
  RandomAccessFile file;
  Record data;

  public StudentInformation()
  {
    super("Student Database");
    try
    {
      file = new RandomAccessFile("credit.dat", "rw");
    }
    catch(IOException e)
    {
      System.err.println(e.toString());
      System.exit(1);
    }
    data = new Record();
    setup();
  } 

  public void setup()
  {
    resize(300, 120);
    setLayout(new GridLayout(3,2));
    updateButton = new Button("Update Record");
    newButton = new Button("New Record");
    deleteButton = new Button("Delete Record");
    viewButton = new Button("View Records");
    done = new Button("Done");
    add(updateButton);
    add(newButton);
    add(deleteButton);
    add(viewButton);
    add(done);
    show();
    update = new UpdateRec(file);
    newRec = new NewRec(file);
    deleteRec = new DeleteRec(file);
    viewRec = new ViewRec(file);
  }

  public boolean action(Event event, Object o)
  {
    if(event.target instanceof Button)
    {
      String current = (String)event.arg;
      if(current.equals("Update Record"))
        update.show();
      else if(current.equals("New Record"))
        newRec.show();
      else if(current.equals("Delete Record"))
        deleteRec.show();
      else if(current.equals("View Records"))
        viewRec.show();
    } 
    return true;
  }

  public boolean handleEvent(Event event)
  {
    if(event.id == Event.WINDOW_DESTROY || event.target == done)
    {
      cleanup();
      hide();
      dispose();
      System.exit(0);
      return true;
    }
    return super.handleEvent(event);
  }

  public void cleanup()
  {
    try
    {
      file.close();
    }
    catch(IOException e)
    {
      System.err.println(e.toString());
      System.exit(1);
    }
  }

  public static void main(String args[])
  {
    StudentInformation teller = new StudentInformation();
  }
}

class NewRec extends Dialog
{
  RandomAccessFile file;
  TextField roll, fname, lname, stnd, addr;
  Button save, cancel;
  Label rollLabel, fnameLabel, lnameLabel, stndLabel, addLabel;
  Record data;
  int rollNo;

  public NewRec(RandomAccessFile f)
  {
    super(new Frame(), "New Record", true);
    resize(300,150);
    setLayout(new GridLayout(6,2));
    file=f;

    roll = new TextField(20);
    rollLabel = new Label("rollNo");
    fname = new TextField(20);
    fnameLabel = new Label("First Name");
    lname = new TextField(20);
    lnameLabel = new Label("Last Name");
    stnd = new TextField(20);
    stndLabel = new Label("Class");
    addr = new TextField(20);
    addLabel = new Label("Address");
    save = new Button("Save Changes");
    cancel = new Button("Cancel");

    add(rollLabel);
    add(roll);
    add(fnameLabel);
    add(fname);
    add(lnameLabel);
    add(lname);
    add(stndLabel);
    add(stnd);
    add(addLabel);
    add(addr);
    add(save);
    add(cancel);

    data = new Record();
  }

  public boolean action(Event event, Object o)
  {
    if( event.target == save)
    {
      rollNo = Integer.parseInt(roll.getText());

      if(rollNo<1)
      {
        roll.setText("Invalid Roll Num");
        return true;
      }
      try
      {
        file.seek((rollNo-1)*data.size());
        data.read(file);
      }
      catch( IOException e)
      {

      }
      if(data.rollNo!=0)
      {
        roll.setText(String.valueOf(data.rollNo) + " already exists");
        fname.setText("");
        lname.setText("");
        stnd.setText("");
        addr.setText("");
      }
      if(data.rollNo==0)
      {
        try
        {
          data.rollNo = rollNo;
          data.lastName = lname.getText();
          data.firstName = fname.getText();
          data.standard = Integer.parseInt(stnd.getText());
          data.address = addr.getText();
          file.seek((rollNo-1)*data.size());
          data.write(file);
        }
        catch( IOException e)
        {
          roll.setText("Error Writing File" + e.toString());
          return true;
        }
        hide();
        clear();
      }
    }

    else if(event.target == cancel)
    {
      hide();
      clear();
    }
    return true;
  }

  private void clear()
  {
    roll.setText("");
    fname.setText("");
    lname.setText("");
    stnd.setText("");
    addr.setText("");
  }
}

Also when I press cancel when the 'new record' window is opened it doesnt clears the text fields.


Solution

  • I'll try to help you.

    First: it is rather a code review. You should use instead : https://codereview.stackexchange.com/

    Second: problems of design:

    • your code should use capabilities of java: serialization and deserialization: What is object serialization?

    • read and write at random in a file, byte by byte is possible, but that's the old way, not very reliable.

    What does not work in your code:

    • the principal thing is that you dont reset data (after having written it, and before input)

    • and what happens depend on the size of your file, and the datas you have entered before: If you have entered data 15, your file will be empty from offset 0 to 13. Then if you try to get 10 for example: it is OK because you get 0. But if you try to get 25, you get an exception (out of the limit of file), then you keep precedent data, then your rollNo "already exists".

    basic solution: to clear data before each input.

    I have added one try catch also with warning for bad datas

    Therefore, I have make some comments. You should think about them.

    Voilà :

    public boolean action(Event event, Object o)
      {
        if( event.target == save)
        {
            // SOLUTION IS HERE
            data=new Record();
    
              // TRACE
            // PROBLEM HERE: data keeps precedent value
            System.out.println("SAME PLAYER PLAY AGAIN: data.rollNo ACTUALLY:"+data.rollNo);
    
          rollNo = Integer.parseInt(roll.getText());
    
          // TRACE
          System.out.println("rollNo ACTUALLY:"+rollNo);
    
          if(rollNo<1)
          {
            roll.setText("Invalid Roll Num");
            return true;
          }
          try
          {
            file.seek((rollNo-1)*data.size());
            data.read(file);
          }
          catch( IOException e)
          {
              // TRACE
              System.out.println("EXCEPTION IN FILE !");
    
            // PROBLEM HERE: data have not been defined: then keeps precedent value
    
          }
    
          // TRACE
          System.out.println("data.rollNo ACTUALLY:"+data.rollNo);
    
          if(data.rollNo!=0)
          {
          // TRACE
           System.out.println("ALREADY EXISTS");
    
    
            roll.setText(String.valueOf(data.rollNo) + " already exists");
            fname.setText("");
            lname.setText("");
            stnd.setText("");
            addr.setText("");
          }
    
          if(data.rollNo==0)
          {
              // TRACE
              System.out.println("NOT FOUND");
    
         try
           {
            try
            {
              data.rollNo = rollNo;
              data.lastName = lname.getText();
              data.firstName = fname.getText();
              data.standard = Integer.parseInt(stnd.getText());
              data.address = addr.getText();
              file.seek((rollNo-1)*data.size());
              data.write(file);
    
              // TRACE
              System.out.println("WRITE DATA "+rollNo);
            }
            catch( IOException e)
            {
              roll.setText("Error Writing File" + e.toString());
              return true;
            }
          }
    
         // SOLUTION
         // WARNING: IF bad datas, 
            catch( Exception ex)
            {
                System.err.println("BAD DATAS");
    
                 JOptionPane.showMessageDialog(new JFrame(),  "WARNING: all fields must be filled !", "WARNING",
                            JOptionPane.ERROR_MESSAGE);
    
              return true;
            }
    
            hide();
    
            // TRACE
            System.out.println("CLEAR");
    
            clear();
    
            // PROBLEM HERE: data not reset ! see above
          }
        }
    
        else if(event.target == cancel)
        {
          hide();
          clear();
        }
        return true;
      }
    

    Hope it helps