首页 > 解决方案 > 如何在 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. 我如何从那里拨打网络电话?

标签: androidandroid-intentandroid-mvvm

解决方案


尝试这个

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

推荐阅读