Run function with Toast in Application Class

Thank you all so much! I just started in Kotlin which probably should be called the K language (like C and F), and have found so many solutions here on this site…it’s awesome!

I have an independent class file called AppTime.kt and it’s declared in the AndroidManifest.xml file:


class AppTime : Application() {

    fun burntToast(sMsg: String) {
        Toast.makeText(this.applicationContext, "!", Toast.LENGTH_LONG).show()

It doesn’t run when called anywhere from a Fragment class:

class FirstFragment : Fragment() {...


I’ve tried every approach using parameters for the Toast following makeText(…
and then to call it from a Fragment with or without context or string parameters.

Is it the type of class I have?

>Solution :

Functions defined inside a class can only be called on an instance of that class, as you already found.

But you cannot simply instantiate an arbitrary Application and expect it to work. Android does a lot of behind-the-scenes setup of framework classes before they are usable. Any Application or Activity that you instantiate yourself is useless. You have to use the instances that are provided to you through the lifecycle of the Activities that get launched in your application.

If you want to call this function from your Fragment, you will have to get an instance of your application, which you can get from its associated Activity. Since the Activity class doesn’t know about your specific subclass of Application, you must also cast the application to your specific subclass to be able to call its unique functions. You can get the Activity by using requireActivity().

(requireActivity().application as AppTime).burntToast()

Leave a Reply