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()

Error:

java.lang.ClassCastException: android.app.Application 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?) {
        Tasks(this).getData()
    }
    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 ->
            getFragment.getResponse(response)
        }

        val errorListener = Response.ErrorListener { error ->
            error.printStackTrace();
        }

        val stringRequest = StringRequest(Request.Method.GET, url, responseListener, errorListener)
        Volley.newRequestQueue(getContext).add(stringRequest)
    }
}

Leave a Reply

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