I am integrating a Login System for that I want the Response.Listener
and Response.ErrorListener
function to return a Boolean.
I searched on the google and found that it can be done using a callback interface ( This Question ). But I don't know how to do that in Kotlin
[ALSO UPDATED] This is my Kotlin file containing my function which are used by many activities:
package com.pratham.example
// My required imports
import ...
fun function1(){
...
}
fun function2(){
...
}
// This Auth function will return True if login success
fun auth(activity:Activity):Boolean{
val queue = Volley.newRequestQueue(activity)
val req = JsonObjectRequest(Request.Method.POST, url, jsonObj,
Response.Listener { response ->
val JSONObj = response.getString("Status")
if(JSONObj=="200"){
// return true
}
else{
// return false
}
}, Response.ErrorListener {
// return false
}
)
queue.add(req)
}
fun function4(){
...
}
This function will return true or false according to the Volley Response.
How can i return value from a Response.Listener
and Response.ErrorListener
in Kotlin
Edit:: I tried to use Interface like this
package com.pratham.sitapuriya
import ...
fun function1(){
...
}
fun function2(){
...
}
interface MyInterface {
fun onCallback(response: Boolean,context:Context)
}
class Login : MyInterface {
private val myInterface = this
override fun onCallback(response: Boolean,context:Context) {
Toast.makeText(context,"Working",Toast.LENGTH_SHORT).show()
}
fun auth(activity: Activity): Boolean {
val sp1 = activity.getSharedPreferences("Login", AppCompatActivity.MODE_PRIVATE)
if (sp1.contains("token") && sp1.contains("deviceId")) {
val token = sp1.getString("token", null)
val deviceId = sp1.getString("deviceId", null)
if (!token.isNullOrEmpty() && !deviceId.isNullOrEmpty()) {
// val url = "http://10.0.2.2:80/Projects/Sitapuriya/login.php"
val url = activity.getString(R.string.server) + "/tokenAuth.php"
val params = HashMap<String, String>()
params["token"] = token
params["deviceId"] = deviceId
val jsonObj = JSONObject(params)
val queue = Volley.newRequestQueue(activity)
val req = JsonObjectRequest(Request.Method.POST, url, jsonObj,
Response.Listener { response ->
val JSONObj = response.getString("Status")
if (JSONObj == "200") {
// return true
myInterface.onCallback(true,activity)
} else {
// return false
myInterface.onCallback(false,activity)
}
}, Response.ErrorListener {
// return false
myInterface.onCallback(false,activity)
}
)
queue.add(req)
} else {
return false
}
} else {
return false
}
return false
}
}
fun function4(){
...
}
But now i have no idea that how the callback will return value in auth() function and also how I'll be calling this auth() fucntion in my other activities .
Please help I have never used a callback before..