Surajkaran Meghwanshi
Surajkaran Meghwanshi

Reputation: 676

How to save an object arrayList which have Pair value in file android

I want to save an arraylist of connections which have Pairs value in file but it showing NotSerializableException.

I also implemented the serializable interface . i thought it occur from Pair class. If you have any solution for save these array of connections and also retrieve from file.

Connection.kt

data class Connection(
//    @Transient
    var firstPair: Pair<CircuitComponent, Int>,
//    @Transient
    var secondPair: Pair<CircuitComponent, Int>
) :Serializable{

    var pathOfLine: NamedPath = NamedPath("")

    data class State(
        val firstComponentCode: String,
        val secondComponentCode: String,
        val firstTouchPointIndex: Int,
        val secondTouchPointIndex: Int,
        val pathName: String,
    ): Serializable


     fun getState() = State(
        firstPair.first.getCode(),
        secondPair.first.getCode(),
        firstPair.second,
        secondPair.second,
        pathOfLine.name
    )
}

saving arraylist of connection

val projectsDirectory = File("${requireActivity().filesDir}/projects")
projectsDirectory.mkdir()
val thisProjectDirectory = File("${projectsDirectory}/${args.project.customerName}")
thisProjectDirectory.mkdir()
val file = File(thisProjectDirectory, "/image.jpg")
val out = FileOutputStream(file)
args.project.image = file.absolutePath
args.project.dateModified = SimpleDateFormat("MMMM dd yyyy", Locale.getDefault()).format(Date())
args.project.size = "${thisProjectDirectory.length() / 1000} kb"
serialize(thisProjectDirectory.absolutePath,"list_con.ser", connectionsList)
designBitmap.compress(Bitmap.CompressFormat.JPEG, 50, out)
out.close()

serialize method

fun serialize(location:String,fileName:String,obj:Any){
 val fileOutputStream = FileOutputStream("$location/$fileName")
 val objectOutputStream = ObjectOutputStream(fileOutputStream)
 objectOutputStream.writeObject(obj)
 objectOutputStream.close()
}

fetch connections

val projectLocation = "${requireActivity().filesDir}/projects/${args.project.customerName}"
val projectDirectory = File(projectLocation)
val connectionsList= deserialize(File(projectDirectory , "list_con.ser"))

deserialize

fun deserialize(file: File): Any? {
    val fileInputStream = FileInputStream(file)
    val objectInputStream = ObjectInputStream(fileInputStream)
    return objectInputStream.readObject()
}

Upvotes: 1

Views: 50

Answers (0)

Related Questions