android - 如何在 onAvitivityResult 中使用存储库或视图模型方法
问题描述
我正在尝试在 android 项目中遵循 MVVM 模式,我必须调用网络 apionAcitivityResult
方法。根据 MVVM,repository 应该与网络调用交互,viewmodel 应该做 Activity 和 repository 之间的交互。因此,如果我必须访问网络 api,那么我必须在 onActivityResult 中调用 viewmodel 方法。这是我的 onActivityResult 方法:
class Profile : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val networkConnectionInterceptor = NetworkConnectionInterceptor(this)
val api = Api.invoke(networkConnectionInterceptor)
val repository = UserRepository(api)
val factory = ProfileViewModelFactory(repository, Photo(""))
val viewModel = ViewModelProvider(this, factory).get(ProfileViewModel::class.java)
val binding: ActivityProfileBinding =
DataBindingUtil.setContentView(this, R.layout.activity_profile)
binding.viewmodel = viewModel
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if(resultCode == Activity.RESULT_OK) {
if (data != null) {
when (requestCode) {
ImageIntent.CAMERA_REQUEST -> {
/* I want to call Viewmodel method here */
viewmodel.onProfileImageUpload(ImageIntent.imageUri)
}
}
}
} else if (resultCode == Activity.RESULT_CANCELED) {
toast("Image upload cancelled !")
}
}
这是我的 viewmodel 中定义的方法:
fun onProfileImageUpload(uri: Uri) {
Coroutines.main{
try {
val imageResponse = repository.updateProfileAvatar(
ImageUtil.getImageForUpload(
uri,
"avatar"
)
)
Log.d("avatar_resonse", "$imageResponse")
} catch(e : Exception) {}
}
}
问题是我必须在方法中初始化视图模型,Activity onCreate
所以我不能在onActivityResult
. 我如何从那里拨打网络电话?
解决方案
尝试这个
if(requestCode==your code){
if(resultCode==Activity.RESULT_OK){
if(data!=null){
// your api and if you calling image from start activity result get it from data
}
}
}
推荐阅读
- javascript - 我用 mvc .net 编写了一个 web api,但我收到 404 错误
- xml - Db2 for i XMLTABLE 与命名空间问题
- html - 无法在 chorme 开发工具中双击编辑 CSS 样式
- javascript - Node.js 命令行参数“<”和“>”
- azure - 逻辑应用程序 - 少量的 HTTP POST/Upsert 数据
- r - 我正在尝试用基于性别的年龄的平均值填充年龄列中的 NA 值
- javascript - 将数组值内爆到反应组件的属性
- sql-server - 哪个聚合字段UPDATE SQL效率更高?
- mysql - 如何将此查询解决为连接查询
- wkhtmltopdf - 从 wkhtmltopdf 渲染 pdf 时,仅将图像显示一次作为背景