M.Tahir Ashraf M.Tahir Ashraf - 5 months ago 37
Android Question

annotation or some automated code generation for setting default values to avoid NullPointerExceptions in Android/Java?

I want to know if in Android there is any design pattern,third part library or any Annotation processors that handles null?

For example, let's say you parse a

JSON Response
and maps the response string directly to an
Object named "Person"
with Gson.

Now assume Person has 3 fields
1) Name
2) Age
3) Gender

and you are about to display them on UI, my Question is how I can avoid a
NULL pointer Exception without checking for Nulls for each field when displaying this data.

Is there an Annotation Processor or any library that allows you to provide null replacement values? Something like this

private String name;
private int age;
private String gender;

so we can avoid null check statements for all these fields and when calling there getters it provides the value if exists if there is null then provides default values. Any Suggestions?

EDIT: I know the two ways for handling Null Pointer crash

1) to use try catch
2) to use Getters and inside every getter i should check the null value and sets a default value if there is null

But My Question is is there a way to reduce these lines of code and use some auto generation thing? Some kind of Annotations I believe


This feature is still in development, but you might want to try out the Data Binding support Library:


The binding system has some protection from NullPointerException. Also, it supports explicit defaults setting:

<TextView android:layout_width="wrap_content"
   android:text="@{user.firstName, default=PLACEHOLDER}"/>