【问题标题】:How to pass custom list with putextra如何使用 putextra 传递自定义列表
【发布时间】:2021-09-24 15:09:31
【问题描述】:

我正在尝试使用 putextra 通过我的服务传递列表数据。我没有这样做。我该怎么做。

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)
    }

以上代码是我的 startService 代码

@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
)

我的数据类

我想传递我的列表(音乐)数据。

【问题讨论】:

  • 你有解决办法吗? @Tunahan
  • @RaguSwaminathan 实际上 "mightyWOZ" 的答案有效。但是我像他说的那样使用数据库。

标签: java list kotlin android-intent pass-data


【解决方案1】:

在不同组件之间传递大型数据集的最佳方法是将数据存储在本地数据库中并在Intent 中传递一些密钥,然后使用该密钥检索数据。 但是,如果您仍然需要按照自己的方式进行操作,请按照以下列出的步骤进行操作

让 Musics 类实现可序列化的接口

data class Musics : Serializable

启动服务时可以这样做

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

在您的服务中,从 Intent 获取您的列表,如下所示

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

【讨论】:

  • startIntent.putExtra("myList", yourList) 此方法出错。 (以下函数都不能使用提供的参数调用。)它不起作用
  • youList 必须是 ArrayList 类型
猜你喜欢
  • 1970-01-01
  • 2014-06-19
  • 2019-11-08
  • 1970-01-01
  • 2013-05-08
  • 1970-01-01
  • 2018-08-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多