使用viewmodel和改造的用户登录 [英] user login using viewmodel and retrofit
问题描述
im试图使用改造和viewmodel进行登录
im trying to do login using retrofit and viewmodel
我已经成功完成了登录,仅进行了翻新...参考了本教程-> https://www.youtube.com/watch?v=j0wH0m_xYLs
i have done successfully login with only retrofit...referred this tutorial--> https://www.youtube.com/watch?v=j0wH0m_xYLs
我还没有找到任何与使用Viewmodel登录有关的教程
i havent found any tutorial related to login using viewmodel
找到了这个stackoverflow问题,但仍未得到解答-> 如何进行改造API调用LiveData和ViewModel请求方法发布
found this stackoverflow question but it is still unanswered --> How to make retrofit API call request method post using LiveData and ViewModel
这是我的通话活动:-
class LoginActivity : BaseClassActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.login_activity)
val button = findViewById<ImageView>(R.id.plusbutton)
val forgotpassword=findViewById<TextView>(R.id.forgotpassword)
button.setOnClickListener {
val i = Intent(applicationContext, RegisterActivity::class.java)
startActivity(i)
}
forgotpassword.setOnClickListener{
val i = Intent(applicationContext, ForgotPassword::class.java)
startActivity(i)
}
loginbtn.setOnClickListener {
val email = loginuser.text.toString().trim()
val password = loginpassword.text.toString().trim()
if (email.isEmpty()) {
Toast.makeText(
applicationContext, "Data is missing",Toast.LENGTH_LONG
).show()
loginuser.error = "Email required"
loginuser.requestFocus()
return@setOnClickListener
}
if (password.isEmpty()) {
loginpassword.error = "Password required"
loginpassword.requestFocus()
return@setOnClickListener
}
RetrofitClient.instance.userLogin(email, password)
.enqueue(object : Callback<LoginResponse> {
override fun onFailure(call: Call<LoginResponse>, t: Throwable) {
Log.d("res", "" + t)
}
override fun onResponse(
call: Call<LoginResponse>,
response: Response<LoginResponse>
) {
var res = response
Log.d("response check ", "" + response.body()?.status.toString())
if (res.body()?.status==200) {
SharedPrefManager.getInstance(applicationContext)
.saveUser(response.body()?.data!!)
val intent = Intent(applicationContext, HomeActivity::class.java)
intent.flags =
Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
showToast(applicationContext,res.body()?.message)
Log.d("kjsfgxhufb",response.body()?.status.toString())
startActivity(intent)
finish()
}
else
{
try {
val jObjError =
JSONObject(response.errorBody()!!.string())
showToast(applicationContext,jObjError.getString("user_msg"))
} catch (e: Exception) {
showToast(applicationContext,e.message)
Log.e("errorrr",e.message)
}
}
}
})
}
}}
以下是LoginResponse:-
Following is LoginResponse:-
data class LoginResponse(val status: Int, val data: Data, val message: String, val user_msg:String)
数据类:-
data class Data(
@SerializedName("id") val id: Int,
@SerializedName("role_id") val role_id: Int,
@SerializedName("first_name") val first_name: String?,
@SerializedName("last_name") val last_name: String?,
@SerializedName("email") val email: String?,
@SerializedName("username") val username: String?,
@SerializedName("profile_pic") val profile_pic: String?,
@SerializedName("country_id") val country_id: String?,
@SerializedName("gender") val gender: String?,
@SerializedName("phone_no") val phone_no: String,
@SerializedName("dob") val dob: String?,
@SerializedName("is_active") val is_active: Boolean,
@SerializedName("created") val created: String?,
@SerializedName("modified") val modified: String?,
@SerializedName("access_token") val access_token: String?
)
确实需要与viewmodel密切相关的帮助进行登录
really need help desparately related to viewmodel for login
预先感谢
添加epicpandaforce时遇到的错误答案:-
Errors encountered while adding epicpandaforce answer:--
在loginviewmodel中:-
in loginviewmodel:--
在登录活动中:- 1->
in loginactivity:- 1-->
2->
3->
推荐答案
class LoginActivity : BaseClassActivity() {
private val viewModel by viewModels<LoginViewModel>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.login_activity)
val button = findViewById<ImageView>(R.id.plusbutton)
val forgotpassword = findViewById<TextView>(R.id.forgotpassword)
button.setOnClickListener {
val i = Intent(applicationContext, RegisterActivity::class.java)
startActivity(i)
}
forgotpassword.setOnClickListener {
val i = Intent(applicationContext, ForgotPassword::class.java)
startActivity(i)
}
loginuser.onTextChanged {
viewModel.user.value = it.toString()
}
loginpassword.onTextChanged {
viewModel.password.value = it.toString()
}
loginbtn.setOnClickListener {
viewModel.login()
}
viewModel.loginResult.observe(this) { result ->
when (result) {
UserMissing -> {
Toast.makeText(
applicationContext, "Data is missing", Toast.LENGTH_LONG
).show()
loginuser.error = "Email required"
loginuser.requestFocus()
}
PasswordMissing -> {
loginpassword.error = "Password required"
loginpassword.requestFocus()
}
NetworkFailure -> {
}
NetworkError -> {
showToast(applicationContext, result.userMessage)
}
Success -> {
val intent = Intent(applicationContext, HomeActivity::class.java)
intent.flags =
Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
showToast(applicationContext, res.body()?.message)
Log.d("kjsfgxhufb", response.body()?.status.toString())
startActivity(intent)
finish()
}
}.safe()
}
}
}
class LoginViewModel(private val savedStateHandle: SavedStateHandle) : ViewModel() {
sealed class LoginResult {
object UserMissing : LoginResult(),
object PasswordMissing : LoginResult(),
class NetworkError(val userMessage: String) : LoginResult(),
object NetworkFailure : LoginResult(),
object Success : LoginResult()
}
val user: MutableLiveData<String> = savedStateHandle.getLiveData("user", "")
val password: MutableLiveData<String> = savedStateHandle.getLiveData("password", "")
private val loginResultEmitter = EventEmitter<LoginResult>()
val loginResult: EventSource<LoginResult> = loginResultEmitter
fun login() {
val email = user.value!!.toString().trim()
val password = password.value!!.toString().trim()
if (email.isEmpty()) {
loginResultEmitter.emit(LoginResult.UserMissing)
return
}
if (password.isEmpty()) {
loginResultEmitter.emit(LoginResult.PasswordMissing)
return
}
RetrofitClient.instance.userLogin(email, password)
.enqueue(object : Callback<LoginResponse> {
override fun onFailure(call: Call<LoginResponse>, t: Throwable) {
Log.d("res", "" + t)
loginResultEmitter.emit(LoginResult.NetworkFailure)
}
override fun onResponse(
call: Call<LoginResponse>,
response: Response<LoginResponse>
) {
var res = response
Log.d("response check ", "" + response.body()?.status.toString())
if (res.body()?.status == 200) {
SharedPrefManager.getInstance(applicationContext).saveUser(response.body()?.data!!)
loginResultEmitter.emit(LoginResult.Success)
} else {
try {
val jObjError =
JSONObject(response.errorBody()!!.string())
loginResultEmitter.emit(LoginResult.NetworkError(jObjError.getString("user_msg")))
} catch (e: Exception) {
// showToast(applicationContext,e.message) // TODO
Log.e("errorrr", e.message)
}
}
}
})
}
}
使用
allprojects {
repositories {
// ...
maven { url "https://jitpack.io" }
}
// ...
}
implementation 'com.github.Zhuinden:live-event:1.1.0'
编辑:一些缺少的块实际上可以进行编译:
some missing blocks to actually make this compile:
fun <T> T.safe(): T = this // helper method
这些在Gradle中的依赖项
These dependencies in Gradle
implementation "androidx.core:core-ktx:1.3.2"
implementation "androidx.activity:activity-ktx:1.1.0"
implementation "androidx.fragment:fragment-ktx:1.2.5"
implementation "androidx.lifecycle:lifecycle-viewmodel-savedstate:2.2.0"
也添加
android {
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = "1.8"
}
}
要访问ViewModel
中的applicationContext
,您需要使用AndroidViewModel
而不是ViewModel
To access applicationContext
in ViewModel
, you'll need to use AndroidViewModel
instead of ViewModel
class LoginViewModel(
private val application: Application,
private val savedStateHandle: SavedStateHandle
): AndroidViewModel(application) {
private val applicationContext = application
那应该解决它
编辑:显然是"onTextChanged"是ktx中的doAfterTextChanged
,我用的是这样的:
apparently the "onTextChanged" is doAfterTextChanged
in ktx, what I use is this:
inline fun EditText.onTextChanged(crossinline textChangeListener: (String) -> Unit) {
addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(editable: Editable) {
textChangeListener(editable.toString())
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
}
})
}
这篇关于使用viewmodel和改造的用户登录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!