Hello folks! Today I am gonna talk about one of the most annoying and common crashes in Android, the NullPointerException. Believe me, if you are starting in Android, you will face your first null pointer exception soon if you do not already. To those of you who does not know what is this about, this is an exception that is thrown when you try to use a null object.
If this happens the app will crash and close instantly what is really frustrating for the user, so we have to put all our efforts to avoid this to happen.
So basically we should never try to do anything with an object if we are not quite sure that this object is valid. We could make conditionals like in the code above:
Or even a more elegant way like this using short form of if.
This works but when the project starts to get bigger this may start to be really annoying and repetitive and if you forget to do this in one single line of your code the problem comes back. So thinking about all of this, I come up with one possible solution. This is not in any best practice pattern or anything like that, it is just one format of code that I developed based on the idea to try to make my models “null proof”. The idea is that we have to write code that doesn’t allow your models to be null at any moment, but it may still happen for a variety of reasons, so if it happen for any reason, the app should never crash. If you don’t have the info expected to show on the screen, don’t show or show a default value, but the app can’t crash and close. So I started to create getters for my model’s properties that verify first if the object is valid and if the property itself is valid and if everything is okay return the value, otherwise return a default value and no null exceptions will happen anymore. One example of this in code looks like this:
Or in Kotlin even cleaner:
In Kotlin you could set the variable to not accept null values, but depends on from where your data come from, if you are getting it from a rest api using Retrofit for example, if the value from json is null or absent Kotlin will throw an exception so unless you can be sure that all properties will have values all the time, better use optionals.
Hope this can be helpful for anyone and I would love to see your thoughts about this? How do you solve this problem?