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.
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.
CodePudding user response:
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)
}
}
}
CodePudding user response:
here the issue is you can't call main activity's context because the function main
is inside another class Employee
. So, you might want to get context into there some way. That could be either this way -
class Employee() {
companion object {
}
fun main(args: Array<String>,context: Context) {
val alertDialogBuilder = AlertDialog.Builder(context)
}
}
or this way -
class Employee(val context: Context) {
companion object {
}
fun main(args: Array<String>) {
val alertDialogBuilder = AlertDialog.Builder(context)
}
}
either one works but, chose according to how many times you'll be using context.