I am trying to use a code snippet from the official android documentation (
The problem is that when I put the code in Main Activity in my test app, it keeps showing "activity?." as red. Why is this the case and how can I get the code to work so that is provides the user with the option to print? Thanks
CodePudding user response:
The code you linked is just a general how to use a library function snippet - it's not put in any context, but we can assume it's probably written with a Fragment
in mind. Fragments have a getActivity()
method that returns the Activity
it's currently attached to (or null if it's not)
Kotlin allows you to access getter and setter functions from Java code as if they were properties - so basically, instead of having to do value = getThing()
and setThing(newValue)
you can treat it like a variable: value = thing
, thing = newValue
etc. So when you access the activity
property in this code, it's really calling getActivity()
. And because the result can be null, you use the ?
to null-check it before trying to do anything with it.
Really what that snippet is saying is, this code needs access to a Context
, and it's using an Activity
as one in the example. If you have a Fragment
, you can just drop this code right in. If you're in an Activity
though, then you obviously don't need to get one - this
is your Activity! And you don't need to null-check it either of course. (And there's no activity
property or getActivity()
method to access, which is why it's showing up red and unrecognised)
So you can just replace that stuff and the checking code around it with:
private fun doPhotoPrint() {
// using 'this' to pass the current activity as the context
val printHelper = PrintHelper(this).apply {
scaleMode = PrintHelper.SCALE_MODE_FIT
}
val bitmap = BitmapFactory.decodeResource(resources, R.drawable.droids)
printHelper.printBitmap("droids.jpg - test print", bitmap)
}
CodePudding user response:
It is showing red because you have not declared the nullable object activity anyway before you use it