Yasin Eraslan
Yasin Eraslan

Reputation: 191

How to save Objects to a file in Android Kotlin

I have A RecordDAO.kt which was given to me by my professor and we should edit it so the program works as it should. The program itself is kind of a student performance logger where I can add new student performances to show them in a ListView.

The RecordDAO looks like this:

class RecordDAO(private val ctx: Context) {
    private var nextId = 0
    private val records = initRecords()

    fun findAll(): List<Record> = records.toList()

    fun findById(id: Int): Record? {
        var record: Record? = Record()
        records.forEach { if(it.id == id) record = it }
        return record
    }
    /**
     * Ersetzt das übergebene [Record] Objekt mit einem bereits gespeicherten [Record] Objekt mit gleicher id.
     *
     * @param record
     * @return true = update ok, false = kein [Record] Objekt mit gleicher id im Speicher gefunden
     */
    fun update(record: Record): Boolean {
        var existing = false
        records.forEach {
            if(it.id == record.id){
                val index= records.indexOf(it)
                records[index] = record
                existing = true
            }
        }
        return existing
    }

    /**
     * Persistiert das übergebene [Record] Objekt und liefert die neue id zurück.
     * (Seiteneffekte: record.id = nextId; nextId += 1 )
     *
     * @param record
     * @return neue record id
     */
    fun persist(record: Record): Int {
        saveRecords()
        record.id = nextId
        records.add(record)
        return record.id!!
    }

    /**
     * Löscht das übergebene [Record] Objekt anhand der id aus dem Speicher.
     *
     * @param record
     * @return true = ok, false = kein [Record] Objekt mit gleicher id im Speicher gefunden
     */
    fun delete(record: Record): Boolean {
        var existing = false
        records.forEach {
            if(it.id == record.id){
                val index:Int = records.indexOf(it)
                records.removeAt(index)
                existing = true
            }
        }
        return existing
    }

    private fun initRecords(): MutableList<Record> {
        val records = mutableListOf<Record>()
        val f = ctx.getFileStreamPath(FILE_NAME)
        if (f.exists()) {
            ctx.openFileInput(FILE_NAME).use { fin ->
                ObjectInputStream(fin).readObject().let { obj ->
                    records.addAll(obj as MutableList<Record>)
                    // init next id
                    if (records.size > 0) {
                        nextId += 1
                    }
                }

            }
        }
        return records;
    }

    private fun saveRecords() {
        ctx.openFileOutput(FILE_NAME, Context.MODE_PRIVATE)
                .use { ObjectOutputStream(it).writeObject(records) }
    }

    companion object {
        private const val FILE_NAME = "records.obj"
    }
}

I got some questions for this code, what exactly does the saveRecords function do, does it create the file and saves the list into it or do I have to create that file by my hand.

My Form Kotlin Form file looks like this:

class RecordFormActivity : AppCompatActivity() {

    private var record = Record()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_record_form)

        val names = resources.getStringArray(R.array.module_names)

        val adapter = ArrayAdapter(this, simple_dropdown_item_1line, names)
        moduleName.setAdapter(adapter)
    }

    fun onSave(view: View) {
        var isValid = true

        record.moduleNum = moduleNum.text.toString().trim().ifEmpty {
            moduleNum.error = getString(R.string.module_num_not_empty)
            isValid = false
            ""
        }

        record.moduleName = moduleName.text.toString().ifEmpty {
            moduleName.error = getString(R.string.module_name_not_empty)
            isValid = false
            ""
        }

        if(isValid){
            if(record.id == null) RecordDAO(this).persist(record)
            else(RecordDAO(this).update(record))
        }

        finish()

    }
}

Where do I have to call the saveRecords method so the data gets saved to the file and gets retrieved after I close and open the app again ?

Should I post my layout XML files aswell?

Upvotes: 1

Views: 2486

Answers (1)

ycannot
ycannot

Reputation: 1947

Accordig to this source the method writeObject is used to write an object to the stream. So, you don't need to edit saveRecords function.

In RecordFormActivity class, you can call saveRecords either in onSave function or in override function of onDestroy. if you have save button I advise you to call saveRecords in your onSave function, otherwise you may call it in onDestroy.

Upvotes: 1

Related Questions