Home > Mobile >  Android room database: get autogenerated id at time of assignment
Android room database: get autogenerated id at time of assignment

Time:08-31

I have an android database with an entity something like

id (autogenerated) string filename
0 cow myFolder/0.mp3
3 sheep myFolder/3.mp3

In other words, I want to use the autogenerated id to be included in a filename once the entity has been assigned. So I would like to do calls like

data.insert("cow")

and have it automatically assign an id and a filename of the form `"myfolder/" [id] ".mp3"

If I naively attempt to do this in the entity main method, with this.filename = "myfolder/" this.id ".mp3" then, since the id has not been set yet, this.id returns its null value (0).

Is it possible to do this?

CodePudding user response:

You can change the type of id to String and every time you insert a new item you generate a new UUID and set that UUID as id and filename, like that:

suspend fun insertItem(string: String) {
    val uuid = UUID.randomUUID().toString()
    val item = Item(
        id = uuid,
        string = string,
        fileName = "myFolder/$uuid.mp3"
    )
    dataDao.insert(item)
}

You can even pass that uuid as param to the insertItem function if you want to use it outside to generate a file or something:

suspend fun insertItem(string: String, uuid: String) {
    val item = Item(
        id = uuid,
        string = string,
        fileName = "myFolder/$uuid.mp3"
    )
    dataDao.insert(item)
}

CodePudding user response:

Well I can do this in the following way:

In the repository on the insert method (using a thread) we write

dataDao.insert(item)
dataDao.updateFilename()

where in the dao I have something like:

    @Query("UPDATE myTable SET filename = ('myfolder/' || id || '.mp3')")
    void updateFilename();

Of course, this means when we use a viewmodel to say myRepository.insert(item), we can include any filename in item - it will be overwritten in the corresponding repository method.

Obviously, whilst this will be fine for my small scale project, a better way to proceed is to introduce a separate method in the repository like void InsertWithAutomaticFilename or something which will be more transparent.

Perhaps somebody could agree or disagree with this way of proceeding? Or maybe there is a better way within the entity or dao itself?

  • Related