javalistkotlinandroid-intentpass-data

How to pass custom list with putextra


I'm trying to pass List data throught my service with putextra. I didn't do it. How can i do that.

fun startService(context: Context, path: String,action: String,list:List<Musics>) {
        val startIntent = Intent(context, ForegroundService::class.java)
        startIntent.putExtra("path", path)
        startIntent.putExtra("action",action)
        ContextCompat.startForegroundService(context, startIntent)
    }

Above code is my startService code

@Entity(tableName = "musics")
data class Musics(
@PrimaryKey(autoGenerate = true) var uid:Int= 0,
@ColumnInfo(name = "file_name") val filename:String,
@ColumnInfo(name = "file_path") val filepath:String
)

My data class

And I want to pass my List(Musics) data.


Solution

  • Best way to pass large data sets between different components is to store the data in local database and pass some key in the Intent and then retrieve the data using the key. But if you still need to do that your way, follow below listed steps

    Make Musics class implement serializable interface

    data class Musics : Serializable
    

    When starting Service you can do

    val yourList: ArrayList<Musics>
    startIntent.putExtra("myList", yourList)
    

    In your service get your list from Intent as following

    val list: List<Musics> = getIntent().getSerializableExtra("myList") as List<Musics>