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

Android Kotlin AlertDialog.Builder() usage and context. "this" not working

This is my very first time using Kotlin/Android App Development, so I apologise if I am missing something simple. I have a background in Java and C#.

I’m trying to display an AlertBox containing X information. All the tutorials I am reading/watching stay that the constructor should be:

val builder = AlertDialog.Builder(this)

This issue I am having trouble with is the "this" part. I get a Type Mismatch error for the "this" reference.

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

I have tried searching for a solution and I find variations of the same:

Instead of passing "this" pass the Context of Calling Activity or
Application.

something like, AlertDialog.Builder builder = new AlertDialog.Builder(mContext);

The problem is: I don’t understand what I am supposed to enter. I have tried writing "mContext" (I didn’t expect this to work) "Employee" (The name of the class) and "MainActivity", but none of these seem to work.

The structure of my code is something like:

class MainActivity : AppCompactActivity() {
    class Employee() {
        companion object {
        }
        fun main(args: Array<String>) {
            val alertDialogBuilder = AlertDialog.Builder(this)
        }
    }
}

Thanks for taking the time to look over this and help out.

>Solution :

In order to access this from an inner class in Kotlin you have to mark it as inner (so it can access parent class members) and use this@ParentClass (to disambiguate between this that refers to the Employee class instance), like this:

class MainActivity : AppCompatActivity() {

    inner class Employee {
        fun main(args: Array<String>) {
            val alertDialogBuilder = AlertDialog.Builder(this@MainActivity)
        }
    }
}

Alternately, you can have the class method (or constructor) take a context as an argument (without making it inner)

class MainActivity : AppCompatActivity() {

    class Employee {
        fun main(context: Context, args: Array<String>) {
            val alertDialogBuilder = AlertDialog.Builder(context)
        }
    }
}
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