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!
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With