android - 如何使用Intent在Kotlin中放置数据类列表

标签 android kotlin android-intent data-class

我想使用Intent发送用于新 Activity 的数据类列表(列表)。
在下面的代码(SplashScreenRepository.kt)中,首先我使用改造连接api(此操作已完成),当响应成功时,我将数据放入DataPeople列表中。
在第二部分中,我需要将此数据列表发送给带有Intent的新 Activity ,以放入回收器 View 。
因此,我希望将所有信息放入intent.putExtra,但是如何?

数据人

data class DataPeople(
    val name : String,
    val height : String,
    val mass : String,
    val hair_color : String,
    val skin_color : String,
    val eye_color : String,
    val birth_year : String,
    val gender : String
) 

SplashScreenRepository.kt
fun getDataInApi(onFinnish : (List<DataPeople>) -> Unit) {
        val retrofitClient = NetworkUtils.getRetrofitInstance()
        val endpoint = retrofitClient.create(Endpoint::class.java)
        val callDataOfPeople = endpoint.dataOfPeople()

        val list = ArrayList<DataPeople>()

        callDataOfPeople.enqueue(object : Callback<SerializeDataPeople?> {
            override fun onResponse(call: Call<SerializeDataPeople?>, response: Response<SerializeDataPeople?>) {
                response.body().let{
                    val note: SerializeDataPeople? = it

                    loop@ for (i in 0..9) {
                        name = note?.results?.get(i)?.name.toString()
                        height = note?.results?.get(i)?.height.toString()
                        mass = note?.results?.get(i)?.mass.toString()
                        hair_color = note?.results?.get(i)?.hair_color.toString()
                        skin_color = note?.results?.get(i)?.skin_color.toString()
                        eye_color = note?.results?.get(i)?.eye_color.toString()
                        birth_year = note?.results?.get(i)?.birth_year.toString()
                        gender = note?.results?.get(i)?.gender.toString()

                        list.add(DataPeople(name, height, mass, hair_color, skin_color, eye_color, birth_year, gender))
                    }
                    dataPeopleList = list
                    onFinnish(dataPeopleList)
                }
            }

            override fun onFailure(call: Call<SerializeDataPeople?>, t: Throwable) {
                Log.e("onFailure error", t?.message)
                onFinnish(emptyList())
            }
        })
    }

SplashScreen.kt
class SplashScreenActivity : AppCompatActivity() {
    private lateinit var splashScreenViewModel: SplashScreenViewModel

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

        (...)

        splashScreenViewModel.getIsUpdatingLiveDataLoaded()?.observe(this, Observer{ it ->
            when(it){
                SplashScreenViewModel.States.DONE ->{
                    Toast.makeText(this, "Data is ready.", Toast.LENGTH_LONG).show()

                    splashScreenViewModel.getPeopleLiveData()?.observe(this, Observer {
                        val intent = Intent(this, MainActivity::class.java)
                        intent.putExtra("list", it)
                        startActivity(intent)
                    })
                }
                (...)
            }
        })
    }

最佳答案

您可以使用Room创建一个Sqlite表:

数据人

@Entity
data class DataPeople(
    @PrimaryKey val id :Int,
    val name : String,
    val height : String,
    val mass : String,
    val hair_color : String,
    val skin_color : String,
    val eye_color : String,
    val birth_year : String,
    val gender : String
) 

DataPeopleDao.kt
@Dao
interface DataPeopleDao {
    @Query("SELECT * FROM DataPeople")
    fun getAll(): List<DataPeople>

    @Insert
    fun insertAll(dataPeople:List<DataPeople>)
}

AppDatabase.kt
@Database(entities = arrayOf(DataPeople::class), version = 1)
abstract class AppDatabase : RoomDatabase() {
    abstract fun dataPeopleDao(): DataPeopleDao
}

SplashScreenActivty.kt
override fun onCreate(savedInstanceState: Bundle?) {

    super.onCreate(savedInstanceState)
    val db = Room.databaseBuilder(
            applicationContext,
            AppDatabase::class.java, "database-name"
        ).build()
    splashScreenViewModel.getIsUpdatingLiveDataLoaded()?.observe(this, Observer{ it ->
            when(it){
                SplashScreenViewModel.States.DONE ->{

                    splashScreenViewModel.getPeopleLiveData()?.observe(this, Observer {
                        //execute this line on a background thread
                        db.dataPeopleDao().insertAll(it)
                        val intent = Intent(this, MainActivity::class.java)
                        startActivity(intent)
                    })
                }

            }
        })


}


MainActivity.kt
override fun onCreate(savedInstanceState: Bundle?) {

    val db = Room.databaseBuilder(
            applicationContext,
            AppDatabase::class.java, "database-name"
        ).build()
    //execute this line on a background thread
    val peopleData = db.dataPeopleDao().getAll()


}

更好的方法

您可以使用Fragment代替 Activity ,并使用ViewModel在它们之间使用share data

但:
我建议避免使用:
第二种方法Singleton可能会伤害您。
第三方法文件总是比数据库慢。

关于android - 如何使用Intent在Kotlin中放置数据类列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60697172/

相关文章:

android - 当 WebView 无法使用互联网时,如何显示无互联网连接弹出窗口和 html 页面?

android - 使用 Binder 从 native cpp 应用程序中 bundle Intent

android - 更新图像的位置

android - Android apk 中的 kotlin/文件夹的用途是什么?

android - AOSP repo manifest 分支名称困惑。去 rev## 或 mr1?

command-line - 从命令行使用 jar 依赖项编译 Kotlin

Android:具有分页 3 流的 ViewModel 正在泄漏

kotlin - 使用VertX服务favicon.ico和其他静态文件

android - 以编程方式检查 Android 系统安全通知访问设置

android - 带有复选框和自定义适配器的 ListView, fragment 无法正常工作