onResume 在视图模型中不起作用

2023-12-03

我的数据仅在创建时才获取...我使用视图模型...当按后退按钮时,它不会更新以前的数据..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 during onCreate仅方法。(这是最好的方法)

  3. 还要观察你的LiveData from ViewModel曾经,也应该来自onCreate因为它是活动的入口点,除了配置更改之外,此方法仅调用一次。所以,在那里观察比在现场观察更安全onResume在活动生命周期中将被多次调用。(主要问题是您的代码无法正常工作,因此作为解决方案,您只能从以下位置调用 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. 不要进行初始 API 调用LiveData创建,在大多数情况下这样做是可以的,但如果你正在更新LiveData在响应该调用时,最好像 init 块期间那样单独进行创建。

  2. 不允许 Ui 是个好习惯(活动/片段)修改LiveDatas of ViewModel直接地。所以,这是一个好兆头,你正在遵循这种模式,拥有私人MutableLiveData暴露为公众LiveData,但请按照建议正确执行。

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


我发现您的代码无法正常工作的唯一原因是您正在创建和观察ViewModel & LiveData一遍又一遍地作为新对象onResume你调用的方法hello() method.

如果有什么不明白或遗漏的地方,请告诉我。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

onResume 在视图模型中不起作用 的相关文章

随机推荐

  • 将数字添加到子图

    我是 matplotlib 的新手 正在尝试了解如何将数字添加到子图中 我有三个不同的函数 它们输出一个数字 def plot fig 1 vars args f ax put subplots do something ax plot x
  • 在数组中查找模式的最有效方法?

    最近我尝试使用C来查找一组数字中的众数 当集合很小时 我的代码可以做得很好 这是我的代码 int frequency 10001 This array stores the frequency of a number that betwee
  • 使用灯具加载数据时是否会调用模型 save() 方法?

    我试图在模型为空时从另一个字段自动生成一个模型 这是代码 class Position RichText name models CharField max length 200 slug models SlugField null Tru
  • 格拉姆-施密特正交化

    给定一个具有独立列的矩阵 A 不一定是方阵 我能够应用 Gram Schmidt 迭代并使用 Matlab 函数为其列空间 以正交矩阵 Q 的形式 生成正交基qr A 1 1 1 0 1 2 Q R qr A and then gt gt
  • C# 中的 TraceRoute 和 Ping

    有人有 C 代码可以方便地对目标计算机执行 ping 和跟踪路由吗 我正在寻找一个纯代码解决方案 而不是我现在正在做的事情 即调用 ping exe 和tracert exe 程序并解析输出 我想要更坚固的东西 鉴于我今天必须编写一个 Tr
  • 在设备上调试 Ionic 3 代码

    我正在测试 Ionic 3 到目前为止一切正常 我希望在 ionic Lab 上调试 TS 代码 因此我在 package json 中添加了下一个配置 config ionic source map source map 之后 我能够看到
  • 部分视图和渲染部分视图有什么区别?

    我对 ASP NET MVC 很陌生 请让我知道哪里应该使用部分视图以及哪里应该渲染部分视图 提前致谢 此链接可能有帮助 Html RenderPartial 此方法结果将直接写入 HTTP 响应流 这意味着它使用与当前网页 模板中使用的相
  • QWebEnginePage.print 与 QPrintPreviewDialog 导致空预览

    我有一个曾经使用过的程序QWebKit在对话框中显示和打印自定义生成的 HTML 报告 现在 我想将整个内容转换为QWebEngine 到目前为止一切正常 只有打印不行 到目前为止我用过QWebView print 将整个 HTML 数据交
  • JSF 2.0:设置验证时,复合组件内的 h:inputText 因非 String 对象而失败

    在支持 bean 中 Min 3 Integer foo 如果我有这样的形式
  • Tomcat 服务器无法“外部”工作

    我已经设置了 Tomcat 服务器并且它可以在本地主机上运行 但是我无法在外部运行它 我需要更改一些设置吗 我尝试了一切 但它似乎在其他地方不起作用 这很奇怪 因为它在本地主机上工作得很好 因此 您正在 spring boot 应用程序中运
  • 基于文件名的文件夹名称

    这实际上不是一个编码问题 我需要将所有文件放入单独的目录中 以便每个文件都有自己的目录 其名称基于文件名 因此 在我制作应用程序来执行此操作之前 有人知道可以执行此操作的软件吗 比如Automator什么的 无需构建应用程序 从 Windo
  • 现代 CPU 保持标志更新是否需要花费大量资源?

    据我了解 在现代无序 CPU 上 最昂贵的东西之一是状态 因为必须在多个版本中跟踪该状态 在许多指令中保持最新状态等 一些指令集 例如 x86 和 ARM 大量使用标志 这些标志是在成本模型不是现在的样子时引入的 并且标志只花费几个逻辑门
  • 如何检查用户是否在 Google Play 上对您的应用进行了评分?

    我想检查用户是否在 Google Play 上对我的应用程序进行了评分 而不是有多少颗星 只要他们是否有 如果他们没有 我将通过一个对话框提示他们 要求他们使用以下代码对其进行评分 startActivity new Intent Inte
  • MSBuild ITaskItem RecursiveDir 元数据消失

    我有一个自定义 MSBuild 任务 它处理一组文件并返回该文件的修改子集 基本上 我只是根据输入创建一个新的 ITaskItem 数组 跳过一些项目 但是 当此结果集返回到 MSBuild 时 RecursiveDir 元数据消失 在我的
  • 数据库连接字符串和排序规则

    是否可以在 MySql 连接字符串中设置连接排序规则以及如何设置 因为服务器上有用于新连接的默认设置 两件事我can t do 无法通话SET COLLATION CONNECTION打开连接后 因为我正在使用实体框架来为我执行所有调用正如
  • Java Swing 以饼图形式显示进度

    我想以饼图格式显示进度 有人可以帮忙吗 我有数据要显示 但如何以这种格式显示它 当我们下载文件时 Google Chrome 中会显示进度 根据 trashgod 提供的链接 这里是实现 馅饼 效果的一种方法 这仅处理不确定的进度条 但添加
  • 将 swifty json 数组保存到用户默认值

    我有一个 jsondata它提供以下信息 let data QuestionTitle Entomology is the science that studies Id 205 Options Option Insects Id 810
  • 从 PySpark 中的列加载 XML 字符串

    我有一个 JSON 文件 其中一列是 XML 字符串 我尝试在第一步中提取该字段并写入文件 并在下一步中读取该文件 但每一行都有一个 XML 标头标记 因此生成的文件不是有效的 XML 文件 如何使用 PySpark XML 解析器 com
  • 使用 jQuery 获取每个
  • 索引号
  • 我正在尝试获取少数的索引号 li 的 li 是 8 我正在尝试获取每个 li 的编号 在每个 li 上单击我都会执行此功能 var str amastorage li index alert str 这总是给我8 EDIT 这就是我得到它的
  • onResume 在视图模型中不起作用

    我的数据仅在创建时才获取 我使用视图模型 当按后退按钮时 它不会更新以前的数据 onresume 在此不起作用 我提到了这个 但没有一个有帮助 gt 对 ViewModel 中的活动生命周期做出反应 我需要帮助 提前致谢 活动 class