android-studio - 如何从 mainActivity 访问变量(在协程内)?
问题描述
提前感谢您的宝贵时间!
我正在练习 API 和网络调用,所以我构建了一个小程序来从公共 API 获取玩家列表并将其显示在 recyclerView @MainActivity 中。简单的。
问题是,除了将列表从协程发送到 recyclerView 适配器之外,我还希望能够将列表存储在某个地方,以便我可以从协程外部访问它。
这样我就可以在没有网络调用的情况下使用玩家列表
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_home)
CoroutineScope(Dispatchers.IO).launch {
// Here we store the data received in a generic type "response"
val response = LaRojaService
.getLaRojaDataService()
.getLaRojaPlayers()
// Return to UI thread to process the data and inflate the recyclerView with it
withContext(Dispatchers.Main) {
if (response.isSuccessful) {
val temp = response.body()
val tempList = mutableListOf<Player>()
var index = 0
temp?.forEach {
val active = temp[index].active
val bio = temp[index].bio
val gamesPlayed = temp[index].gamesPlayed
val goalsScored = temp[index].goalsScored
val name = temp[index].name
val number = temp[index].number
val playerPictureUrl = temp[index].playerPictureUrl
val position = temp[index].position
val profilePictureUrl = temp[index].profilePictureUrl
val seasonsActive = temp[index].seasonsActive
tempList.add(Player(active, bio, gamesPlayed, goalsScored, name,
number, playerPictureUrl, position, profilePictureUrl, seasonsActive))
index += 1
}
recyclerView_home.layoutManager = LinearLayoutManager(this@HomeActvity)
recyclerView_home.adapter = HomePlayerAdapter(tempList)
}
}
}
}
这是做什么的:
- Get a list of players from a public API using a coroutine
- Inflate the recyclerView with the list created on the MainThread
我需要它做什么:
- Get a list of players from the API using the coroutine
- Save the list outside the coroutine (In this case, MainActivity)
- Work through the data inside the mainActivity
- Inflate the recyclerView (From Main activity)
再次非常感谢你。我对这个话题仍然很困惑。我什至不知道这是否可能。
解决方案
推荐阅读
- html - CSS Grid:div 沿着列而不是行展开
- javascript - 如何使用 Javascript 创建电子邮件事件
- python - 如何将特定字符放置在文件中的特定位置?
- java - try catch vs try-with-resources
- php - 将表单操作绑定到控制器方法
- docker - 我们可以在 Java 中创建 docker logging 插件吗?我知道我们可以在 Go 中做到这一点,但我们可以在 java 中做到吗?
- android - 如何修复firebase身份验证中的错误“电子邮件地址格式错误”?
- c - 为什么“+=”在 SSE intrinsic 中给了我意想不到的结果
- python - 尝试在python中进行分组和总结
- sql - 用 JOIN 替换 - SQL