I'am using Kotlin with Volley library to send login request to MySql using php code and get user_id(Int) back. I'am getting the right result back (no problem with this), but I'am unable to take this variable outside its function to use it, As we know Volley functions are asynch in nature. I used interface-callback to pass this variable from login() to MainActivity{}, but still I'am unable to access this variable outside the function which brings it in to MainActivity{}. Any help please?
MainActivity{
....
login(object : VolleyCallback....)
....
}
login(callback: VolleyCallback){
....volley functions here
}
interface VolleyCallback{
fun onSuccess(value:Int)
}
----------------------- Real Code -----------------------
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
var myValue:Int
val login_btn = findViewById<Button>(R.id.loginbtn)
login_btn.setOnClickListener() {
login (object : VolleyCallback {
override fun onSuccess(value: Int){
myValue = value //we got the right value here
}
})
//how can I access myValue in this place outside login function
}
}
--------------- login() -------------
private fun login(callback: VolleyCallback) {
lateinit var requestQueue: RequestQueue
val Email = findViewById<EditText>(R.id.email)
val Password = findViewById<EditText>(R.id.password)
val email = Email.text.toString()
val password = Password.text.toString()
var result: Int
val server_url = "http://192.168.1.55/login.php"
val srtingRequest = object : StringRequest(
Request.Method.POST,
server_url,
{ response ->
result = response.toInt()
callback.onSuccess(result)
},
{ volleyError ->
}
) {
@Throws(AuthFailureError::class)
override fun getParams(): MutableMap<String, String> {
val params = HashMap<String, String>()
params.put("email", email)
params.put("password", password)
return params
}
}
VolleySingleton.getInstance(this).addToRequestQueue(srtingRequest)
}
------------ Interface callback ------------
interface VolleyCallback{
fun onSuccess(value:Int)
}
question from:
https://stackoverflow.com/questions/65643967/kotlin-volley-callback-to-access-mysql-info 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…