Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

    <application
        android:name=".AppTime"

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

class FirstFragment : Fragment() {...

    burntToast()

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()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading