why `onDraw()` method on View receives nullable canvas - android

In a using custom views, I override onDraw(canvas:Canvas?) method many times , but I don't understand why this method get a nullable Canvas , shouldn't a view always have a canvas to draw on when it is time to draw?.
I also asserted it non null and it works , but I don't want to take that risk , may be at some point it gets null.
So first I want to understand in what situations that parameter can be null?
or is it just coming from java to kotlin conversion process and i can safely remove the ?from the parameter?
Thanks

Because the Android API was originally written in Java. And in Java, there are no non-nullable values. Since Kotlin needs to be compatible with that Java API, it needs to be a nullable parameter.
If you ever actually get a null it's a bug in the framework. I've never seen it happen. I think you're safe just letting it throw a NullPointerException if it does because you should never see it.
For the record, even the Android framework doesn't check for null on that parameter- TextView.onDraw will crash if you pass in null.

Related

Smart cast to 'DrawerLayout!' is impossible, because 'drawerLayout' is a mutable property that could have been changed by this time

I'm a complete newbie to android development and I've been stuck on this problem for the past two days and I've never felt more frustrated in my life. A little backstory first,
I'm creating the most basic Book Library app and I was trying to add a Navigation Drawer to the app. Inside the kotlin file, When I declare all the variables (corresponding to the tags created in the layout file) using lateinit, it throws me a nullPointerException. For this reason I've taken to declaring my variables like this:
var drawerLayout: DrawerLayout? = null
which helps me avoid the exception.
Now coming to the real problem,
I was trying to create a click listener for my actionBarDrawerToggle inside the onCreate method this way:
val actionBarDrawerToggle = ActionBarDrawerToggle(this#MainActivity, drawerLayout, R.string.open_drawer, R.string.close_drawer)
drawerLayout.addDrawerListener(actionBarDrawerToggle)
actionBarDrawerToggle.syncState()
and for some reason, the drawerLayout part of the "drawerLayout.addDrawerListener(actionBarDrawerToggle)" line is underlined in red meaning there's an error. When I run it, this is the error it shows me in build window:
Smart cast to 'DrawerLayout!' is impossible, because 'drawerLayout' is a mutable property that could have been changed by this time
I have no ideo how to proceed with this. I've tried a lot of things and none of them is working. I think the error might have something to do with the declaration method I use that I described above. It would be great if someone could help me out
Tactically, change that line to:
drawerLayout?.addDrawerListener(actionBarDrawerToggle)
?. in Kotlin is the "safe call" operator. It says:
If drawerLayout is not null, call addDrawerListener()
If drawerLayout is null, do nothing (technically, it evaluates to null, but you are not using that here)
That will allow you to compile. Whether the code will work will depend on whether you have successfully set a non-null value on drawerLayout or not by the time you reach that line. The fact that your lateinit var declaration was failing suggests that you are not populating drawerLayout — with lateinit var, you would crash at runtime; with the nullable property and the safe call, the line will wind up being ignored. Neither is what you want.
Ideally, the books that you are reading (or courses that you are taking) on Kotlin and Android app development would cover things like safe calls, how to avoid having properties like drawerLayout, and so on. If you are not reading books or taking courses on Kotlin and Android app development, that may be something that you should consider.
You've defined drawerLayout as a nullable (DrawerLayout?) var, which means the value can change at any time, and that value can be null. So even if you do a null check to make sure it's not null, that could change at any moment! There's no way for the compiler to guarantee the call is safe.
Here's some options, in order from bad to good:
Explicitly mark the variable as non-null by referencing drawerLayout!!. This is you telling the compiler "I know what's up and it's fine, trust me". You should avoid ever doing this because it's a red flag, you ignore warnings, and you'll end up running into a situation where you're wrong
Copy the non-null value into a temporary variable, that you know won't change. This is the typical way to handle nullables in Kotlin, and you use one of the scope functions like let:
drawerLayout?.let { drawer -> // do stuff with drawer }
That's doing a null check (with the ?) and if it's not null, it calls the let block with that non-null value. And you know that value isn't going to change inside the block. I've called the variable drawer but you can omit that, it's called it by default. There's other scope functions like run too, slightly different ways of doing the same thing.
You can also just make a call on the checked variable itself, if that's all you need to do:
drawerLayout?.doAThingItsNotNullSoItsFine()
which is basically doing the same thing under the hood
Don't make drawerLayout nullable in the first place! It's never actually supposed to be null, right? It should always exist, and have a value when you try to access it? Then save yourself the aggro and the need to null check it all the time - which is what lateinit is for.
lateinit allows you to declare a variable without actually giving it a value. Usually you have to, which is what you've done here right - you've made it nullable, just so you can stick a temporary null in there. lateinit is a promise to the compiler that it's ok, you're not providing a value yet, but you will definitely have set one before anything tries to access it. (That's why it's called late init!)
So the problem you were running into was that you hadn't actually set that value before something tried to read it. You can check if it's been set with ::drawerLayout.isInitialized, but really you should understand your code flow enough to ensure that the reading is only possible after the intialisation. If you can't guarantee that, then you have a possible state where you don't have a value for a variable that other stuff might need to access - and that's a good candidate for making it nullable and using the null-handling features to deal with it smoothly

NoSuchMethodError (NoSuchMethodError: The getter 'length' was called on null. Receiver: null Tried calling: length) [duplicate]

I have some code and when I run it produces an error, saying:
NoSuchMethod: the method 'XYZ' was called on null
What does that mean and how do I fix it?
Why do I get this error?
Example
As a real world comparison, what just happened is this conversation:
Hey, how much gas is left in the tank of the car?
What are you talking about, we don't have a car.
That is exactly what is happening in your program. You wanted to call a function like _car.getGasLevel(); but there is no car, the variable _car is null.
Obviously, in your program it might not be a car. It could be a list or a string or anything else really.
Technical explanation
You are trying to use a variable that is null. Either you have explicitly set it to null, or you just never set it at all, the default value is null.
Like any variable, it can be passed into other functions. The place where you get the error might not be the source. You will have to follow the leads from the actual null value to where it originally came from, to find what the problem is and what the solution might be.
null can have different meanings: variables not set to another value will be null, but sometimes null values are used by programmers intentionally to signal that there is no value. Databases have nullable fields, JSON has missing values. Missing information may indeed be the information itself. The variable bool userWantsPizzaForDinner; for example might be used for true when the user said yes, false when the user declined and it might still be null when the user has not yet picked something. That's not a mistake, it's intentionally used and needs to be handled accordingly.
How do I fix it?
Find it
Use the stack trace that came with the error message to find out exactly which line the error was on. Then set a breakpoint on that line. When the program hits the breakpoint, inspect all the values of the variables. One of them is null, find out which one.
Fix it
Once you know which variable it is, find out how it ended up being null. Where did it come from? Was the value never set in the first place? Was the value another variable? How did that variable got it's value. It's like a line of breadcrumbs you can follow until you arrive at a point where you find that some variable was never set, or maybe you arrive at a point where you find that a variable was intentionally set to null. If it was unintentional, just fix it. Set it to the value you want it to have. If it was intentional, then you need to handle it further down in the program. Maybe you need another if to do something special for this case. If in doubt, you can ask the person that intentionally set it to null what they wanted to achieve.
simply the variable/function you are trying to access from the class does not exist
someClass.xyz();
above will give the error
NoSuchMethod: the method 'xyz' was called on null
because the class someClass does not exist
The following will work fine
// SomeClass created
// SomeClass has a function xyz
class SomeClass {
SomeClass();
void xyz() {
print('xyz');
}
}
void main() {
// create an instance of the class
final someClass = SomeClass();
// access the xyz function
someClass.xyz();
}

Error flutter NoSuchMethodError (NoSuchMethodError: The getter 'length' was called on null. Receiver: null [duplicate]

I have some code and when I run it produces an error, saying:
NoSuchMethod: the method 'XYZ' was called on null
What does that mean and how do I fix it?
Why do I get this error?
Example
As a real world comparison, what just happened is this conversation:
Hey, how much gas is left in the tank of the car?
What are you talking about, we don't have a car.
That is exactly what is happening in your program. You wanted to call a function like _car.getGasLevel(); but there is no car, the variable _car is null.
Obviously, in your program it might not be a car. It could be a list or a string or anything else really.
Technical explanation
You are trying to use a variable that is null. Either you have explicitly set it to null, or you just never set it at all, the default value is null.
Like any variable, it can be passed into other functions. The place where you get the error might not be the source. You will have to follow the leads from the actual null value to where it originally came from, to find what the problem is and what the solution might be.
null can have different meanings: variables not set to another value will be null, but sometimes null values are used by programmers intentionally to signal that there is no value. Databases have nullable fields, JSON has missing values. Missing information may indeed be the information itself. The variable bool userWantsPizzaForDinner; for example might be used for true when the user said yes, false when the user declined and it might still be null when the user has not yet picked something. That's not a mistake, it's intentionally used and needs to be handled accordingly.
How do I fix it?
Find it
Use the stack trace that came with the error message to find out exactly which line the error was on. Then set a breakpoint on that line. When the program hits the breakpoint, inspect all the values of the variables. One of them is null, find out which one.
Fix it
Once you know which variable it is, find out how it ended up being null. Where did it come from? Was the value never set in the first place? Was the value another variable? How did that variable got it's value. It's like a line of breadcrumbs you can follow until you arrive at a point where you find that some variable was never set, or maybe you arrive at a point where you find that a variable was intentionally set to null. If it was unintentional, just fix it. Set it to the value you want it to have. If it was intentional, then you need to handle it further down in the program. Maybe you need another if to do something special for this case. If in doubt, you can ask the person that intentionally set it to null what they wanted to achieve.
simply the variable/function you are trying to access from the class does not exist
someClass.xyz();
above will give the error
NoSuchMethod: the method 'xyz' was called on null
because the class someClass does not exist
The following will work fine
// SomeClass created
// SomeClass has a function xyz
class SomeClass {
SomeClass();
void xyz() {
print('xyz');
}
}
void main() {
// create an instance of the class
final someClass = SomeClass();
// access the xyz function
someClass.xyz();
}

getReference() vs. getChild()

I was wondering what the difference between database.getReference("foo/bar/123") and database.getReference("foo").child("bar").child("123") is?
I'm assuming that the later one will load the complete "foo" object whereas database.getReference("foo/bar/123") just loads the "123" object?
Is my assumption correct or what is the correct / most efficient way to only load data of "123"?
The two are equivalent. You can inspect this manually this by printing the toString() format for both References.
References are cheap - there's nothing inefficient about either solution. Neither one has yet loaded any data. A Reference is just a pointer to a location in the database.
It should not make a difference, a reference is not actually accessed when instantiated. This is the most relevant document I can find,
https://firebase.google.com/docs/reference/node/firebase.database.Reference
The docs don't say it explicitly, but requests are only performed when using the .set() or .on() methods

Android Studio complains of expression being null even after check

I have the following line of code in onCreateView() method of my Fragment. It warns me that the expression to createPinPresenter.setLoginResult() can be null.
So I ask AS to generate the null check and it does this.
Even after the auto generated code, AS still complains the same expression being null. It obviously cannot be null inside the check.
Am I missing something obvious here or is this a bug?
Edit: I'm using AS version 2.2.3
This is correct, how does AS know if, for example, getParcelable() will return the same value? it is just a syntactic control, not a semantic control.
A function could return, for example, null if the number of times it has been called is odd: in that case the warning is correct.
Think this:
if (getNextValue() != null)
value = getNextValue();
If getNextValue() increments an index, at the end of an array it could return null: the error is pretty obvious, and it's actually what the control tries to prevent in your code.
The only solution is to store the result of getParcelable(KEY_LOGIN_RESULT) in a temporary variable, in that case AS will correctly manage it.
And of course... the fact that this is an autogenerated code, is actually a bug, I think, of the autogeneration, that is less smart than the control.

Categories

Resources