Issue
I am new to android studio and this whole API JSON protocols. I am trying to make a login service to work. It gets the info for a successful login from a backend server shown in the BASE_URL and a successful login returns a status and a token.So I have the following LoginActivity code :
package com.example.mydoctor
import android.accounts.AccountManager
import android.content.Intent
import android.content.Context
import android.content.SharedPreferences
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.TextView
import android.widget.Toast
import com.example.mydoctor.api.ApiInterface
import com.example.mydoctor.models.LoginRequest
import com.example.mydoctor.models.LoginResponse
import kotlinx.android.synthetic.main.activity_login.*
import org.json.JSONObject
import retrofit2.*
import retrofit2.converter.gson.GsonConverterFactory
const val BASE_URL = "https://docappmy.herokuapp.com/mydoctor/user/"
class LoginActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
val clickRegister = findViewById<TextView>(R.id.clickRegister)
clickRegister.setOnClickListener {
val intent = Intent(this, RegisterActivity::class.java);
startActivity(intent)
}
// val loginbtm = findViewById<TextView>(R.id.loginbtm)
// loginbtm.setOnClickListener {
// val intent = Intent(this, MainActivity::class.java);
// startActivity(intent)
//
// }
val loginbutton = loginbtm
var amka = ""
var password = ""
loginbutton.setOnClickListener {
amka = amka_edit_text.text.toString().trim()
password = password_edit_text.text.toString().trim()
Log.d("values","The AMKA is: $amka, The password is: $password")
val retrofitBuilder = Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(BASE_URL)
.build()
.create(ApiInterface::class.java)
val retrofitData = retrofitBuilder.loginUser(LoginRequest(amka,password))
retrofitData.enqueue(object:Callback<LoginResponse>{
override fun onResponse(call: Call<LoginResponse>, response: Response<LoginResponse>) {
val responseData = response.body()
Log.d("SuccessLogin","The response is: $responseData")
// val intent = Intent(this@LoginActivity,MainActivity::class.java)
// startActivity(intent)
}
override fun onFailure(call: Call<LoginResponse>, t: Throwable) {
Toast.makeText(this@LoginActivity,"FailureLogin",Toast.LENGTH_LONG).show()
Log.d("loginerror","loginerror: ${t.localizedMessage} - ${t.stackTrace} - ${t.message}")
}
})
}
this LoginRequest :
package com.example.mydoctor.models
data class LoginRequest(
val amka: String, val password: String
)
this LoginResponse :
package com.example.mydoctor.models
import com.google.gson.annotations.SerializedName
data class LoginResponse(
@SerializedName("status")
val status: String,
@SerializedName("Token")
val token: String
)
And this ApiInterface :
package com.example.mydoctor.api
import com.example.mydoctor.models.LoginRequest
import com.example.mydoctor.models.LoginResponse
import retrofit2.Call
import retrofit2.http.Body
import retrofit2.http.POST
interface ApiInterface {
@POST("login")
fun loginUser(
@Body loginRequest: LoginRequest
): Call<LoginResponse>
}
So I want to retrieve the values of "status" and "token" and then make the login button take me to my main activity upon successful login (correct AMKA (an 11-digit number related to health insurance) and password. How can I retrieve them and have a proper login ? Should I use SharedPreferences and if so how ? I am really confused. Any help appreciated.
EDIT:
I started adding the following function but then I need to enter where the token is stored and don't know how to express that :
private fun saveData() {
if(amka_edit_text.text.isEmpty()){
amka_edit_text.error = "Please enter an AMKA"
return
}
if(password_edit_text.text.isEmpty()){
password_edit_text.error = "Please enter a password"
}
val mypref = getSharedPreferences("mypref", MODE_PRIVATE)
val editor = mypref.edit()
editor.putString("token",)
Solution
You can use the Shared Preferences.
1. Write data to shared preferences
The following code block saves the token value in shared preferences
Put the code below in your onResponse callback:
val sharedPref = getSharedPreferences(Context.MODE_PRIVATE)
val editor = sharedPref.edit()
editor.putString("TOKEN", responseData.token)
editor.apply()
2. Read data from shared preferences
val sharedPref = getSharedPreferences(Context.MODE_PRIVATE)
val token = sharedPref.getString("TOKEN", null)
You can take this token value where you need it.
Note: Shared preferences stores data in an XML file with key-value. In the example above, the "TOKEN" string value becomes your key. If a value cannot be found with this key, it will return null. In this way, you can check if there is a saved token.
If you want more details, you can review this document: https://developer.android.com/training/data-storage/shared-preferences
I also suggest you look into Encrypted Shared Preferences, which is a safer way for storing sensitive data: https://developer.android.com/topic/security/data
Answered By - serkancay
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.