Android: Call method from another activity kotlin not work-ThrowExceptions

Exception or error:

I want to call a method from another activity.

I’m trying to do this but it does not work:

(applicationContext as MainActivity).getAllGroupFromTheDatabaseToList()


java.lang.ClassCastException: cannot be cast to com.emoonadev.futurfit.MainActivity

I do not want the method to be static, so no companion object

How to solve:

The applicationContext as the name states is not Activity at all thus the cast fails.

Regardless of this you should reconsider what you’re trying to do. Another activity might not even exist while you’re in the activity doing things.

Instead consider implementing a store you can inject to both of the activities and observe changes as necessary.

Default Android components you could use for this are bound services or if you want to go back anyway use onActivityResult().


Try it out

class DataForm : Fragment() {
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    override fun getResponse(String response) {
        // code

class Tasks(private val context: Any) {
    fun getData() {

        val getContext = (context as DataForm).activity
        val getFragment = (context as DataForm)

        val responseListener = Response.Listener<String> { response ->

        val errorListener = Response.ErrorListener { error ->

        val stringRequest = StringRequest(Request.Method.GET, url, responseListener, errorListener)

Leave a Reply

Your email address will not be published. Required fields are marked *