'How to make a loop in Android using Retrofit to avoid inserting data to database simultaneously?

I insert data to a database by using (SELECT max(id) + 1 FROM data) and sometimes it cause that I try to put two object with the same id to the database, when I do it in loop.

button.setOnClickListener {
    for ((key, value) in dataArray!!) {

            DbHelper().addData(value, key)
        }
 
}

DbHelper code:

fun addData(
        value: Int,
        key: Int
    )
    {

        val retrofit = Retrofit.Builder()
            .baseUrl("http://10.0.2.2:8080/app/")
            .addConverterFactory(GsonConverterFactory.create())
            .build()

        valdataService: DataService = retrofit.create(
            DataService::class.java
        )


        val call: Call<Long> = valdataService.postData(
            DataBodyPost(value, key))

        call.enqueue(object : Callback<Long> {
            override fun onResponse(call: Call<Long>, response: Response<Long>) {
                if (!response.isSuccessful()) {
                    println(" response " + response.toString())
                    return
                }

            }

            override fun onFailure(call: Call<Long>, t: Throwable) {

                println(" ERROR " + t)
            }

        })
    }


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source