onResume在视图模型中不起作用

apj123

仅在创建数据时才提取我的数据...使用ViewModel创建...当按后退按钮时它不更新以前的数据..onresume在此不起作用...

我引用了这个,但是没有一个帮助->在ViewModel中对活动生命周期做出反应

我需要帮助

提前致谢

活动: -

class MyAccount : BaseClassActivity() {

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



    var mActionBarToolbar = findViewById<androidx.appcompat.widget.Toolbar>(R.id.toolbartable);
    setSupportActionBar(mActionBarToolbar);
  setEnabledTitle()


    val resetbutton=findViewById<Button>(R.id.resetpwd)
    resetbutton.setOnClickListener {
        val i=Intent(applicationContext,
            ResetPasswordActivity::class.java)
        startActivity(i)
    }
    val editbutton=findViewById<Button>(R.id.editdetail)
    editbutton.setOnClickListener {
        val i=Intent(applicationContext, EditProfile::class.java)
        startActivity(i)
    }

  hello()
}

override fun onResume() {
    super.onResume()
  hello()

}

fun hello(){
    val first_name = findViewById<TextView>(R.id.firstname)
    val last_name = findViewById<TextView>(R.id.lastname)
    val emailuser = findViewById<TextView>(R.id.emailuser)
    val phone_no = findViewById<TextView>(R.id.phone_no)
    val birthday = findViewById<TextView>(R.id.birthday)
    val image=findViewById<ImageView>(R.id.imageprofile)


    val model = ViewModelProvider(this)[MyAccountViewModel::class.java]

    model.viewmodel?.observe(this, object : Observer<My_account_base_response> {
        override fun onChanged(t: My_account_base_response?) {
            first_name.setText(t?.data?.user_data?.first_name)
            last_name.setText(t?.data?.user_data?.last_name)
            emailuser.setText(t?.data?.user_data?.email)
            phone_no.setText(t?.data?.user_data?.phone_no).toString()
            birthday.setText(t?.data?.user_data?.dob).toString()
            Glide.with(applicationContext).load(t?.data?.user_data?.profile_pic)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .placeholder(R.drawable.ic_launcher_foreground)

                .into(image)
        }
    })


}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
    return when (item.itemId) {
        android.R.id.home -> {
            NavUtils.navigateUpFromSameTask(this)

            true
        }
        else -> super.onOptionsItemSelected(item)
    }
}}

视图模型:-

class MyAccountViewModel(context: Application) :AndroidViewModel(context),LifecycleObserver{
private var MyAccountViewModels: MutableLiveData<My_account_base_response>? = null
val viewmodel: MutableLiveData<My_account_base_response>?
    get() {
        if (MyAccountViewModels == null) {
            MyAccountViewModels = MutableLiveData<My_account_base_response>()
            loadviewmodel()
        }
        return MyAccountViewModels

    }

private fun loadviewmodel(){
    val token :String = SharedPrefManager.getInstance(getApplication()).user.access_token.toString()
    RetrofitClient.instance.fetchUser(token)
        .enqueue(object : Callback<My_account_base_response> {
            override fun onFailure(call: Call<My_account_base_response>, t: Throwable) {

                Log.d("res", "" + t)


            }

            override fun onResponse(
                call: Call<My_account_base_response>,
                response: Response<My_account_base_response>
            ) {
                var res = response

                if (res.body()?.status == 200) {
                    MyAccountViewModels!!.value = response.body()

                } else {
                    try {
                        val jObjError =
                            JSONObject(response.errorBody()!!.string())
                        Toast.makeText(getApplication(),
                            jObjError.getString("user_msg"),
                            Toast.LENGTH_LONG).show()
                    } catch (e: Exception) {
                        Log.e("errorrr", e.message)
                    }
                }
            }
        })
}}
耶尔·范赫德

这里有很多错误,因此,我将尽我所能为您提供重构的代码和解释。

活动:

class MyAccount : BaseClassActivity() {
    private val mActionBarToolbar by lazy { findViewById<androidx.appcompat.widget.Toolbar>(R.id.toolbartable) }
    private val resetbutton by lazy { findViewById<Button>(R.id.resetpwd) }
    private val editbutton by lazy { findViewById<Button>(R.id.editdetail) }
    private val first_name by lazy { findViewById<TextView>(R.id.firstname) }
    private val last_name by lazy { findViewById<TextView>(R.id.lastname) }
    private val emailuser by lazy { findViewById<TextView>(R.id.emailuser) }
    private val phone_no by lazy { findViewById<TextView>(R.id.phone_no) }
    private val birthday by lazy { findViewById<TextView>(R.id.birthday) }
    private val image by lazy { findViewById<ImageView>(R.id.imageprofile) }
    lateinit var model: MyAccountViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.myaccount)
        setSupportActionBar(mActionBarToolbar)
        setEnabledTitle()
        model = ViewModelProvider(this)[MyAccountViewModel::class.java]
        resetbutton.setOnClickListener {
            val i = Intent(applicationContext, ResetPasswordActivity::class.java)
            startActivity(i)
        }
        editbutton.setOnClickListener {
            val i = Intent(applicationContext, EditProfile::class.java)
            startActivity(i)
        }
        model.accountResponseData.observe(this, object : Observer<My_account_base_response> {
            override fun onChanged(t: My_account_base_response?) {
                first_name.setText(t?.data?.user_data?.first_name)
                last_name.setText(t?.data?.user_data?.last_name)
                emailuser.setText(t?.data?.user_data?.email)
                phone_no.setText(t?.data?.user_data?.phone_no).toString()
                birthday.setText(t?.data?.user_data?.dob).toString()
                Glide.with(applicationContext)
                    .load(t?.data?.user_data?.profile_pic)
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .placeholder(R.drawable.ic_launcher_foreground)
                    .into(image)
            }
        })
    }

    override fun onResume() {
        super.onResume()
        model.loadAccountData()
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        return when (item.itemId) {
            android.R.id.home -> {
                NavUtils.navigateUpFromSameTask(this)

                true
            }
            else -> super.onOptionsItemSelected(item)
        }
    }
}

关于您的活动课程的几点注意事项:

  1. 您不需要findViewById每次都做,只需在过程中onCreate一次或懒惰地做。(仅供参考,考虑使用Kotlin合成物或视图绑定或数据绑定)

  2. 初始化您的viewModel过程中的onCreate方法。(这是最好的方法)

  3. 同时观察您LiveDataViewModel一次,这也应该是从onCreate,因为它是入口点活动,除了配置改变了这种方法只调用一次。因此,在那观察是安全的,而不是onResume在活动生命周期中多次调用它。(您的代码无法解决的主要问题,因此,仅ViewModel在恢复过程中调用了API方法即可解决此问题

ViewModel:

class MyAccountViewModel(context: Application) : AndroidViewModel(context) {
    private val _accountResponseData = MutableLiveData<My_account_base_response?>()
    val accountResponseData: MutableLiveData<My_account_base_response?>
        get() = _accountResponseData

    init {
        loadAccountData()
    }

    fun loadAccountData() {
        val token: String = SharedPrefManager.getInstance(getApplication()).user.access_token.toString()
        RetrofitClient.instance.fetchUser(token)
            .enqueue(object : Callback<My_account_base_response> {
                override fun onFailure(call: Call<My_account_base_response>, t: Throwable) {
                    Log.d("res", "" + t)
                    _accountResponseData.value = null
                }

                override fun onResponse(
                    call: Call<My_account_base_response>,
                    response: Response<My_account_base_response>
                ) {
                    var res = response

                    if (res.body()?.status == 200) {
                        _accountResponseData.value = response.body()
                    } else {
                        try {
                            val jObjError =
                            JSONObject(response.errorBody()!!.string())
                            Toast.makeText(
                                getApplication(),
                                jObjError.getString("user_msg"),
                                Toast.LENGTH_LONG
                            ).show()
                        } catch (e: Exception) {
                            Log.e("errorrr", e.message)
                        }
                    }
                }
            })
    }
}
  1. 请勿在LiveData创建时进行初始API调用,在大多数情况下都可以这样做,但是如果要LiveData根据该调用的响应进行更新,则最好像在init块中那样单独进行调用。

  2. 这是很好的做法,是不会允许UI (活动/片段)修改LiveDataViewModel直接。因此,这是您通过将privateMutableLiveData公开为public来遵循这种模式的好兆头LiveData,但请按照建议正确执行。

  3. 旁注:您的视图模型不需要是LifecycleObserverLifecycleObserver用于某些自定义类/组件,需要通过静默地观察/独立于活动生命周期来对其进行自我管理。那不是的用例ViewModel


我发现为什么您的代码无法正常工作的唯一原因是,您是在调用method的方法中作为新对象创建,观察ViewModelLiveData反复执行的onResumehello()

让我知道是否没有任何意义或遗漏。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章