0

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..

Pratham Vaidya
  • 85
  • 4
  • 13
  • this question may help you: https://stackoverflow.com/questions/47499891/how-i-can-use-callback-in-kotlin – ToraCode Jun 13 '19 at 08:16

1 Answers1

2

You can't, the code you have executes asynchronously so you can't have the return statement there. But it doesn't mean you can not get the value. The easiest option is create a LiveData<Boolean> and observe it in your activity. When the value changes you will get notified.

The next thing you can do is you can create an interface.

interface MyCallback{
    fun onValueChanged()
}

Then implement this interface in your activity and override the method. Then you can use it to get a callback when your asynchronous call finishes. See the below code.

interface MyInterface{
    fun onCallback(response:Boolean)
}

class LoginActivity : AppCompatActivity(), AuthListener, MyInterface {

    val myInterface = this

    override fun onCallback(response: Boolean) {

    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        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)
                }
                else{
                    myInterface.onCallback(false)
                }
            }, Response.ErrorListener {
                // return  false 
            }
        )
        queue.add(req)

    }
}

Hope this helps. Thank You :)

Belal Khan
  • 2,099
  • 2
  • 22
  • 32
  • Actually these volley codes are in a function not in class ,so can u tell me how can I override that inside a function? Also how can I get the stored value from this myInterface.onCallback ? Thanks for answering ;) – Pratham Vaidya Jun 13 '19 at 14:34
  • You cannot do it, in my answer volley code is also inside a function you can see the function is `onCreate()` so it doesn't matter where your volley codes are the point is you are sending a callback with the help of interface, and you can use this approach easily. – Belal Khan Jun 14 '19 at 01:49
  • Please check my updated question and suggest what I am doing wrong. – Pratham Vaidya Jun 14 '19 at 05:10
  • How about this, share your code in GitHub and then give me the repository link. Then I can help you. – Belal Khan Jun 14 '19 at 05:15
  • And if your goal is to learn about UserLogin in android using RESTful APIs then you should check this course, but it uses Retrofit and I will also recommend you using Retrofit. Course Link: https://www.youtube.com/watch?v=67bdklHmXA8&list=PLk7v1Z2rk4hjVaZ8DZKe8iT9RIM9OUrwp&index=2&t=2s (Here you will learn how to properly follow the MVVM pattern and make User Login and User Signup). – Belal Khan Jun 14 '19 at 05:18
  • And here, you did the wrong thing. As your code is not complete I am not able to understand what you are doing. But read this to know what you actually need. In your auth function pass an instance of the callback interface. And then where you are calling the auth function for the user authentication in that class implement the Callback interface. Now while calling the auth function you can pass `this` for the callback interface. And from the auth function you can call your callback function, that will execute inside your activity. I hope you understood, it is a bit complicated. – Belal Khan Jun 14 '19 at 05:22
  • Thanks Belal Khan, I am now learning about MVVM from your videos. – Pratham Vaidya Jun 14 '19 at 12:35