Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin, Intent: None of the following functions can be called with the arguments supplied

Intent doesn't work with RestApiService callback.

Previously It worked in RegisterActivity:

fun alert(text: String) {
    val intent = Intent(this, PopUp::class.java)
    intent.putExtra("text", text)
    startActivity(intent)
}

I want to display the result as a pop-up message. PopUp is a custom activity view.

When I place it into another class, there is an error:

None of the following functions can be called with the arguments

supplied. (Context!, Class<*>!) defined in

android.content.Intent (String!, Uri!) defined in

android.content.Intent

import android.content.Intent
import androidx.core.content.ContextCompat.startActivity
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class RestApiService {

// MY CUSTOM INTENT! WORKED BEFORE IF TO PLACE INTO AN ACTIVITY.
fun alert(text: String) {
    val intent = Intent(this, PopUp::class.java)
    intent.putExtra("text", text)
    startActivity(intent)
}

fun addUser(userData: ModelUserRegister, onResult: (ModelUserRegister?) -> Unit){
    val retrofit = ServiceBuilder.buildService(RestApi::class.java)
    retrofit.addUser(userData).enqueue(

        object : Callback<ModelUserRegister> {

            override fun onFailure(call: Call<ModelUserRegister>, t: Throwable) {
                onResult(null)
            }

            override fun onResponse(call: Call<ModelUserRegister>, response: Response<ModelUserRegister>) {
                val addedUser = response.body()
                if (response.code() in 200..320)
                {
                    alert(response.message())
                } else {
                    alert(response.message())
                }
                onResult(addedUser)
            }
        }
    )
}
}

The latest research gave me the advice to change:

val intent = Intent(this, PopUp::class.java)

to:

val intent = Intent(RegisterActivity.this, PopUp::class.java)

Didn't help. This question for those people who want to use Kotlin!

like image 436
J A S K I E R Avatar asked Sep 02 '25 02:09

J A S K I E R


1 Answers

To create a new Intent object, you have to pass context as the first parameter. You cannot just use this anywhere since depending on where you use it, it might not be context.

You can use this or this@ActivityName (ActivityName.this in Java) only when your codes are in an activity.

You can add a context parameter to your alert() function to fix this issue:

fun alert(context: Context, text: String) {
    val intent = Intent(context, PopUp::class.java)
    intent.putExtra("text", text)
    context.startActivity(intent)
}
like image 174
YASAN Avatar answered Sep 04 '25 20:09

YASAN