java中的onresume,onResume在视图模型中不起作用

my data is fetched only when it is created...im using viewmodel...when press back button it doesnt update the previous data..onresume is not working in this...

i need help

thanks in advance

activity:--

class MyAccount : BaseClassActivity() {

override fun onCreate(savedInstanceState: Bundle?) {

super.onCreate(savedInstanceState)

setContentView(R.layout.myaccount)

var mActionBarToolbar = findViewById(R.id.toolbartable);

setSupportActionBar(mActionBarToolbar);

setEnabledTitle()

val resetbutton=findViewById(R.id.resetpwd)

resetbutton.setOnClickListener {

val i=Intent(applicationContext,

ResetPasswordActivity::class.java)

startActivity(i)

}

val editbutton=findViewById(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(R.id.firstname)

val last_name = findViewById(R.id.lastname)

val emailuser = findViewById(R.id.emailuser)

val phone_no = findViewById(R.id.phone_no)

val birthday = findViewById(R.id.birthday)

val image=findViewById(R.id.imageprofile)

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

model.viewmodel?.observe(this, object : Observer {

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)

}

}}

viewmodel:--

class MyAccountViewModel(context: Application) :AndroidViewModel(context),LifecycleObserver{

private var MyAccountViewModels: MutableLiveData? = null

val viewmodel: MutableLiveData?

get() {

if (MyAccountViewModels == null) {

MyAccountViewModels = MutableLiveData()

loadviewmodel()

}

return MyAccountViewModels

}

private fun loadviewmodel(){

val token :String = SharedPrefManager.getInstance(getApplication()).user.access_token.toString()

RetrofitClient.instance.fetchUser(token)

.enqueue(object : Callback {

override fun onFailure(call: Call, t: Throwable) {

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

}

override fun onResponse(

call: Call,

response: 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)

}

}

}

})

}}

解决方案

There are bunch of things wrong here, so let me provide you refactored code and explanation as much as I would be able to..

Activity:

class MyAccount : BaseClassActivity() {

private val mActionBarToolbar by lazy { findViewById(R.id.toolbartable) }

private val resetbutton by lazy { findViewById(R.id.resetpwd) }

private val editbutton by lazy { findViewById(R.id.editdetail) }

private val first_name by lazy { findViewById(R.id.firstname) }

private val last_name by lazy { findViewById(R.id.lastname) }

private val emailuser by lazy { findViewById(R.id.emailuser) }

private val phone_no by lazy { findViewById(R.id.phone_no) }

private val birthday by lazy { findViewById(R.id.birthday) }

private val image by lazy { findViewById(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 {

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)

}

}

}

Few notes on your activity class:

You don't need to findViewById everytime, just do it once during onCreate or do it lazily. (FYI consider using kotlin synthetics or view binding or data binding)

Initialize your viewModel during onCreate method only. (That's the best way to do it)

Also observer your LiveData from ViewModel once, it should be also from the onCreate as it's the entry point to the activity and apart from config changes this method called only once. So, it's safe to observe it over there rather than during onResume which will be called multiple times during activity lifecycle. (The main issue your code wasn't working, so as a fix you only call your API method from ViewModel during resume)

ViewModel:

class MyAccountViewModel(context: Application) : AndroidViewModel(context) {

private val _accountResponseData = MutableLiveData()

val accountResponseData: MutableLiveData

get() = _accountResponseData

init {

loadAccountData()

}

fun loadAccountData() {

val token: String = SharedPrefManager.getInstance(getApplication()).user.access_token.toString()

RetrofitClient.instance.fetchUser(token)

.enqueue(object : Callback {

override fun onFailure(call: Call, t: Throwable) {

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

_accountResponseData.value = null

}

override fun onResponse(

call: Call,

response: 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)

}

}

}

})

}

}

Don't make initial API call along with LiveData creation, it's okay to do in most of cases but if you're updating LiveData on response of that call then it's good to make it separately like during init block.

It's good practice not to allow Ui (Activity/Fragments) to modify LiveDatas of ViewModel directly. So, that's good sign you're following such pattern by having private MutableLiveData exposed as public LiveData, but do it correctly as suggested.

Side note: Your view model doesn't need to be LifecycleObserver. LifecycleObserver is used for some custom class/component which needs to be managed by their self by silently observing/depending on activity lifecycle independently. That's not the use case of ViewModel.

The only thing that I found why your code wasn't working correctly is because you were creating & observing ViewModel & LiveData over & over again as new objects from onResume method where you called hello() method.

Let me know if something don't make sense or missing.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值