Search code examples
javaserializationjavafxfxmlobservablelist

How to serialize an object that has an ObservableList on it?


I actually want to serialize a List of objects but I think that makes no diference. I am putting my class that has just two properies. A string and a ObservableList. I will include the serialization methods in it. I know ObservableList does not implements serializable, but I am populating a TableView with them, that is why I am using it but if there is another way, I am open to it.

public class Tratamiento implements Serializable{

private String name;
private ObservableList<Material> materials;

public Tratamiento(String name, ObservableList<Material> materials) {
    this.name= name;
    this.materials= materials;
}

public Treatment(){        
}

public String getName() {
    return name;
}

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

public ObservableList getMaterials() {
    return materials;
}

public void setMaterials(ObservableList materials) {
    this.materials = materials;
}


public int addTreatment(List tratamiento) {
    int res = 0; //Failure

    try {
        FileOutputStream fileOut = new FileOutputStream("Treatment.ser");
        ObjectOutputStream out = new ObjectOutputStream(fileOut);
        out.writeObject(treatment);
        out.close();
        fileOut.close();
        System.out.printf("Object has been serialized");
        res = 1;
    } catch (IOException i) {
        i.printStackTrace();

    }

    return res;
}



public List consultListTreatments() {
    int res = 0;
    //Deserialize file
    List<Treatment> list = new ArrayList<Treatment>();

    try {
        FileInputStream fileIn = new FileInputStream("Treatment.ser");
        ObjectInputStream in = new ObjectInputStream(fileIn);
        list = (List) in.readObject();     
        in.close();
        fileIn.close();
        res = 1;
    } catch (IOException i) {
        i.printStackTrace();
    } catch (ClassNotFoundException c) {
        System.out.println("Class not found");
        c.printStackTrace();
    }    
    return list;
}    

}

Here is the implementation in my FXML controller

@FXML
private void createTreatment(ActionEvent event){
   Treatment tr = new Treatment();        
    List<Treatment> list = new ArrayList<Treatment>();
    list = tr.consultListTreatments();

    ObservableList<Material> rows = table.getItems();//FXCollections.observableArrayList();
    //get values of the rows


    Treatament newTreatment = new Treatment(TextFieldTreatmentName.getText(),rows);

    list.add(newTreatment);
    newTreatment.addTreatment(list);  
    TextFieldTreatmentName.clear();
}

I saw this question but it does not fit my need nor did I could modify it to what I want. How to serialize ObservableList


Solution

  • In this case, you will have to implement the Externalizable interface. This will require you to write your own methods for serializing and deserializing your objects.