I am creating an android launcher app using Kotlin, and I am running the following code to activate an app. I have an app drawer that displays my user apps, and when I click on one of them, I want it to activate the app with this code:
override fun getView(position:Int, convertView:View, parent:ViewGroup):View
{
val v:View
if (convertView == null)
{
v = inflater.inflate(R.layout.item_app, parent, false)
}
else
{
v = convertView
}
val myLayoutView = v.findViewById(R.id.layout) as LinearLayout
val myImageView = v.findViewById(R.id.image) as ImageView
val myLabelView =v.findViewById(R.id.label) as TextView
val app = getItem(position) as AppObject
myLabelView.text = app.appName
myImageView.setImageDrawable(app.appImage)
myLayoutView.setOnClickListener(object: View.OnClickListener
{
override fun onClick(v:View)
{
val launchAppIntent = context.packageManager.getLaunchIntentForPackage(app.appPackageName)
if (launchAppIntent != null)
{
context.startActivity(launchAppIntent)
}
}
})
return v
}
The error I get is in the line:
val launchAppIntent = context.packageManager.getLaunchIntentForPackage(app.appPackageName)
appPackageName is of type String? but getLaunchIntentForPackage() requires String. I've tried tacking toString() on the end of app.appPackageName but that does not work.
I think the problem I'm having lies in my ignorance of Kotlin's null avoidance fussiness and I just don't really know how to get around it yet since I'm brand new to Kotlin and app development at that.
Any help is greatly appreciated. Thanks!
The error you are receiving is because when you access app.appPackageName
there is a chance that the application's package name may be null. This is because this method is originally written in Java and Kotlin protects itself in case of the value null. That is why it's type is String?.
To overcome this issue, you need to add a nullability check before accessing this value. That way, Kotlin will interpret it's type as String.
override fun getView(position:Int, convertView:View, parent:ViewGroup):View
{
val v:View
if (convertView == null)
{
v = inflater.inflate(R.layout.item_app, parent, false)
}
else
{
v = convertView
}
val myLayoutView = v.findViewById(R.id.layout) as LinearLayout
val myImageView = v.findViewById(R.id.image) as ImageView
val myLabelView =v.findViewById(R.id.label) as TextView
val app = getItem(position) as AppObject
myLabelView.text = app.appName
myImageView.setImageDrawable(app.appImage)
myLayoutView.setOnClickListener(object: View.OnClickListener
{
override fun onClick(v:View)
{
val applicationPackageName : String? = app.appPackageName
if (applicationPackageName != null) {
val launchAppIntent = context.packageManager.getLaunchIntentForPackage(applicationPackageName)
if (launchAppIntent != null)
{
context.startActivity(launchAppIntent)
}
}
} else {
//YOUR LOGIC
}
})
return v
}