目前我正在使用实时 api,在登录 api 中我得到了一个访问令牌作为响应。因为我遵循 mvvm 模式,所以我通过存储库处理我的数据。我希望我从响应中获得的令牌将存储在sharedpreference中,稍后我将使用其他api作为标头。我不清楚如何通过存储库将该令牌存储到共享首选项中。
我的包裹:
我的存储库类:
class OpusRepoImpl private constructor() : OpusRepository {
private val mLivedata: MutableLiveData<LoginPojo> = MutableLiveData()
private var rInstance: RetrofitInstance = RetrofitInstance()
override fun cLoginResponse(
context: Context,
username: String,
password: String
): MutableLiveData<LoginPojo> {
val apiServices = rInstance.getRetrofitInstance()?.create(ApiServices::class.java)
val requestBody = LoginBody(username, password)
val clientId = "myclientid"
val clientSecret =
"myClientSecrete"
val grantType = "password"
val call = apiServices?.getUser(clientId, clientSecret, grantType, requestBody)
try {
call?.enqueue(object : Callback<LoginPojo> {
override fun onResponse(
call: Call<LoginPojo>,
response: Response<LoginPojo>
) {
if (!response.isSuccessful) {
Toast.makeText(context, "Login Failed", Toast.LENGTH_SHORT).show()
return
}
val loginResponse = response.body()
loginResponse?.access_token
//Here i want to save the login access token into sharedpreference
mLivedata.postValue(loginResponse!!)
}
override fun onFailure(call: Call<LoginPojo>, t: Throwable) {
Toast.makeText(context, "Login Failed", Toast.LENGTH_SHORT).show()
}
})
} catch (e: Exception) {
e.printStackTrace()
Toast.makeText(context, "Login Failed", Toast.LENGTH_SHORT).show()
}
return mLivedata
}
companion object {
private var instance: OpusRepoImpl? = null
fun getInstance(): OpusRepoImpl {
return instance ?: synchronized(this) {
instance ?: OpusRepoImpl().also { instance = it }
}
}
}
登录片段:
class LoginFragment : Fragment(), OnClickListener {
private lateinit var binding: FragmentLoginBinding
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
binding = FragmentLoginBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setOnclicklistener()
}
private fun setOnclicklistener() {
binding.btnLogin.setOnClickListener(this)
}
companion object {
@JvmStatic
fun newInstance() =
LoginFragment().apply {
arguments = Bundle().apply {
}
}
}
override fun onClick(v: View) {
when (v.id) {
R.id.btnLogin -> {
val email = binding.edEmail.text.toString()
val pass = binding.edPassword.text.toString()
if (isValid()) {
loginCheck(email, pass)
}
}
}
}
private fun loginCheck(email: String, pass: String) {
//val sharedPreferences = requireContext().getSharedPreferences("MyPrefs", Context.MODE_PRIVATE)
val loginViewModel = ViewModelProvider(this)[LoginViewModel::class.java]
loginViewModel.loginResponse(requireContext(), email, pass).observe(viewLifecycleOwner, Observer { loginPojo ->
val accessToken = loginPojo.access_token
if (accessToken.isNotEmpty()){
Navigation.findNavController(requireView()).navigate(R.id.homepage)
}
})
}
private fun isValid(): Boolean {
binding.edEmail.error = null
binding.edPassword.error = null
var isValid = true
val email = binding.edEmail.toString()
val pass = binding.edPassword.toString()
if (email.isEmpty()) {
isValid = false
binding.edEmail.error = "Enter Your Email"
} else {
val emailPattern = "[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+"
if (!email.matches(emailPattern.toRegex())) {
binding.edEmail.error = "Enter a Valid Email"
isValid = false
}
}
if (pass.isEmpty()) {
isValid = false
binding.edPassword.error = "Enter Your Password"
} else {
if (pass.length < 8) {
binding.edPassword.error = "Your pass was at-least 8 character"
isValid = false
}
}
return isValid
}}
登录视图模型:
class LoginViewModel(val application: Application) : AndroidViewModel(application) {
private val loginRepo = OpusRepoImpl.getInstance()
fun loginResponse(
context:Context,
username: String,
password: String
): MutableLiveData<LoginPojo> {
return loginRepo.cLoginResponse(context, username, password)
}}
你必须添加此代码:
//For saveing access token in shared prefrence
val sharedPreferences = context.getSharedPreferences("MySharedPrefs", Context.MODE_PRIVATE)
sharedPreferences.edit {
putString("AccessToken", accesstoken)
apply()
}
这是完整的代码:
class OpusRepoImpl private constructor() : OpusRepository {
private val mLivedata: MutableLiveData<LoginPojo> = MutableLiveData()
private var rInstance: RetrofitInstance = RetrofitInstance()
override fun cLoginResponse(
context: Context,
username: String,
password: String
): MutableLiveData<LoginPojo> {
val apiServices = rInstance.getRetrofitInstance()?.create(ApiServices::class.java)
val requestBody = LoginBody(username, password)
val clientId = "myclientid"
val clientSecret =
"myClientSecrete"
val grantType = "password"
val call = apiServices?.getUser(clientId, clientSecret, grantType, requestBody)
try {
call?.enqueue(object : Callback<LoginPojo> {
override fun onResponse(
call: Call<LoginPojo>,
response: Response<LoginPojo>
) {
if (!response.isSuccessful) {
Toast.makeText(context, "Login Failed", Toast.LENGTH_SHORT).show()
return
}
val loginResponse = response.body()
val accesstoken = loginResponse?.access_token
//For saveing access token in shared prefrence
val sharedPreferences = context.getSharedPreferences("MySharedPrefs", Context.MODE_PRIVATE)
sharedPreferences.edit {
putString("AccessToken", accesstoken)
apply()
}
mLivedata.postValue(loginResponse!!)
}
override fun onFailure(call: Call<LoginPojo>, t: Throwable) {
Toast.makeText(context, "Login Failed", Toast.LENGTH_SHORT).show()
}
})
} catch (e: Exception) {
e.printStackTrace()
Toast.makeText(context, "Login Failed", Toast.LENGTH_SHORT).show()
}
return mLivedata
}
companion object {
private var instance: OpusRepoImpl? = null
fun getInstance(): OpusRepoImpl {
return instance ?: synchronized(this) {
instance ?: OpusRepoImpl().also { instance = it }
}
}
}
}
为了从共享首选项获取访问令牌,您可以这样做:
val accessToken = sharedPreferences.getString("AccessToken",null)