문제

Ok,so I need to write a program which creates profiles (simple ones with just a name, photo, status etc.) and it adds friends which exist. It saves the profiles in a file using ObjectOutputStream. Now the problems I am facing so far are:

  • I am getting Serializable Errors and I don't know where they are coming from. Errors that the project gives
  • java.io.NotSerializableException: SocialNetwork at java.io.ObjectOutputStream.writeObject0(Unknown Source) at java.io.ObjectOutputStream.defaultWriteFields(Unknown Source) at java.io.ObjectOutputStream.writeSerialData(Unknown Source) at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)

The code is about 250 lines so I am gonna add 3 comments with the error description where they are happening. Ctrl + F (Error Here Guys) is the word

    import javax.swing.*;

    import java.awt.*;
    import java.awt.event.*;

    import javax.swing.border.LineBorder;

    import java.io.*;
    import java.util.ArrayList;
    public class SocialNetwork implements Serializable {
        /**
         * 
         */
        private static final long serialVersionUID = 904698037930887085L;
        RandomAccessFile raf ;
        JTextField setStatus ;
        JTextField addFriend ;
        JTextField emriProfilit ;
        JButton changestatus ;
        JButton setfriend ;
        JButton changepicture ;
        JButton add ;
        JButton delete ;
        JButton lookup ;
        JLabel name ;
        JLabel password ;
        JPasswordField passwordfield ;
        JLabel Banner ;
        SocialProfile profile ;
        SocialProfile temp ;
        JLabel profilepicture ;
        FileOutputStream fileoutput;
        FileInputStream fileinput ;
        ObjectOutputStream output;
        ObjectInputStream input;

        public SocialNetwork() throws FileNotFoundException{

        fileoutput = new FileOutputStream("database.dat",true);
        fileinput = new FileInputStream("database.dat");
        emriProfilit = new JTextField(15);
        name = new JLabel("Name");
        password = new JLabel("Password");
        passwordfield = new JPasswordField (7);
        lookup = new JButton("Lookup");
        add = new JButton("Add");
        delete = new JButton("Delete");
        JPanel p1 = new JPanel() ;
        p1.setLayout(new FlowLayout());
        p1.add(name);
        p1.add(emriProfilit);
        p1.add(password);
        p1.add(passwordfield);
        p1.add(add);
        p1.add(delete);
        p1.add(lookup);
        JFrame frame = new JFrame ("Social Network");
        frame.setSize(1050,500);
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
        frame.setLayout(new BorderLayout());
        frame.add(p1,BorderLayout.NORTH);
        changestatus = new JButton ("Change Status");
        setfriend = new JButton ("Add Friend");
        changepicture = new JButton ("Change Picture");
        setStatus = new JTextField (20);
        addFriend = new JTextField (15) ;
        ImageIcon sfond= new ImageIcon("images/socialnetwork.png");
        Banner = new JLabel (sfond);
        JPanel p2 = new JPanel() ;
        JPanel p3 = new JPanel() ;
        JPanel p4 = new JPanel() ;
        p4.setLayout(new GridLayout(2,1,10,10));
        p2.setLayout(new GridLayout(5,1,10,10));

        p3.add(Banner);
        p2.add(setStatus);
        p2.add(changestatus);
        p2.add(changepicture);
        p2.add(addFriend);
        p2.add(setfriend);
        p4.add(p3);
        p4.add(p2);
        p4.setBorder(BorderFactory.createLineBorder(Color.black));
    // Error here guys (sometimes it does not show )


frame.add(p4,BorderLayout.WEST);
// Veprimi i cili do kryhet mbasi të klikohet butoni changepicture
changepicture.addActionListener(new ActionListener(){
    @Override
    public void actionPerformed(ActionEvent e){
        File file = browsefile();
        profile.setAvatar(file.getAbsolutePath());
        profilepicture.setIcon(profile.getAvatar());
    }

});
// Veprimi që do realizohet mbasi të jepet emri
    emriProfilit.addActionListener(new ActionListener(){
    @Override
    public void actionPerformed(ActionEvent e){
        profile = new SocialProfile();  
        profile.setName(emriProfilit.getText().trim());
        emriProfilit.setFocusable(false);
    }

    });
    // Veprimi që do realizohet mbasi të jepet password-i
    passwordfield.addActionListener(new ActionListener(){
        @Override
        public void actionPerformed(ActionEvent e){

            profile.setPassword(passwordfield.getPassword());
            passwordfield.setFocusable(false);
        }

        });
    // Veprimi që do realizohet kur të klikohet butoni changestatus
    changestatus.addActionListener(new ActionListener(){
        @Override
        public void actionPerformed(ActionEvent e){

            profile.setStatus(changestatus.getText().trim());

        }

        });
    // Veprimi që do kryhet nga butoni add
    add.addActionListener(new ActionListener(){
        @Override
        public void actionPerformed(ActionEvent e){

            try {
                add(profile);
            } catch (IOException e1) {

                e1.printStackTrace();
            }

        }

        });
    // Veprimi që do kryhet nga butoni lookup
    lookup.addActionListener(new ActionListener(){
        @Override
        public void actionPerformed(ActionEvent e){
            String name ;   
            name = emriProfilit.getText().trim();
            try {
                if(doesitexist(name))
                    System.out.println("Ekziston");
                else
                    System.out.println("Nuk Ekziston");
            } catch (ClassNotFoundException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            emriProfilit.setFocusable(false);
            passwordfield.setFocusable(false);
        }

        });
}
    // Error here Guys


    public void add(SocialProfile profile) throws IOException{
            output = new ObjectOutputStream(fileoutput);
            output.writeObject(profile);
        }
        //Error here Guys


    public boolean doesitexist(String name) throws IOException, ClassNotFoundException{
            input = new ObjectInputStream(fileinput);

            try{
                while(true){
            temp = (SocialProfile)(input.readObject());
                if (temp.getName().equals(name)){
                    return true ;
                }
                }
            }
            catch (EOFException ex){
                ex.printStackTrace();
                return false ;
            }
        }
        public File browsefile(){
            JFileChooser filebrowse = new JFileChooser ();
            if (filebrowse.showOpenDialog(null) == JFileChooser.APPROVE_OPTION){

            }
            File file = filebrowse.getSelectedFile();
            return file ;
        }



        public static void main (String[] args) throws FileNotFoundException{
        new SocialNetwork();
    }
        public class SocialProfile implements Serializable {
            /**
             * 
             */
            private static final long serialVersionUID = 2436758770296955312L;
            /**
             * 
             */

            private String name ;
            private ImageIcon avatar;
            private String status ;
            private ArrayList<String> friends ;
            private char[] password ;



            public SocialProfile(){
                status = new String ("Default Status");
                friends = new ArrayList<String>( );
                avatar = new ImageIcon ("images/defaultavatar.jpg");

            }
            public String getName (){
                return name ;
            }
            public void setName(String name){
                this.name = name ;
            }
            public void setPassword (char[] pass){
                password = pass ;
            }
            String getStatus (){
                return status ;
            }

            void setStatus (String status){
                this.status = status ;
            }

            ImageIcon getAvatar (){
                return avatar ;
            }
            void setAvatar (String avatarpicture){
                avatar = new ImageIcon(avatarpicture) ;
            }
            void addFriend (String name){
                friends.add(name);
            }
        }
    }
도움이 되었습니까?

해결책 3

The Class that was serialized shouldn't have been defined as an Inner Class.I declared the class as a new public one and it works fine.

다른 팁

Do not try to serialize the GUI components. Try t serialize the object model and the object model to dynamically load the ui.

You should close the stream after usage, you should always close a file after writing to it.

About the not showing border, you should call frame.setVisible(true) at the end after you've added every component to it, if still not showing you should call repaint() or updateui() methods for the frame, and I suggest to extend your class from the JFrame class if you use only one frame, this is for easier usage.

About the serialization, I think your code is correct, what are the errors you recive after building the project?

EDIT : I've found this page about this problem, seems like you have a non serializeable object in your class, so first of all remove the implements Serializable part from your SocialNetwork class, and try to find the NotSerializeable object in your SocialProfile class. I'd remove the code parts and start testing it, for example leave the primitive types only, and check that if you are able to serialize that way.

The increasing file size means definetly that something is happening there, try to delete the file before running the Serialization code.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top