3

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 using Gson 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

@defVal("N/A")
private String name;
@defVal(0)
private int age;
@defVal("N/A")
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

Community
  • 1
  • 1
M.Tahir Ashraf
  • 222
  • 5
  • 15

3 Answers3

1

There is no library that store default value if you receive NULL, To reduce null check at every step you should use setter and getter method in getter method check your value if it is null than it return default value so at every step you need not want to check NULL value.

J.D.
  • 1,401
  • 1
  • 12
  • 21
1

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

http://developer.android.com/tools/data-binding/guide.html

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

<TextView android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:text="@{user.firstName, default=PLACEHOLDER}"/>
S.D.
  • 29,290
  • 3
  • 79
  • 130
  • that default data binding is quite near to what i was looking for, Thanks for your repy and showing me something new as I wasn't aware of this before.+1 for you and also accepted ypur answer.Thanks Again! – M.Tahir Ashraf Apr 02 '16 at 21:15
  • From data Binding I found this: The null coalescing operator (??) can be used in an expression to provide a default value if the accessed property returns null – M.Tahir Ashraf Apr 02 '16 at 21:19
0

There is no library, but you can do something like this:

public getValue(){
    return(value!=null?value:defaultValue);
}
Vladimir Jovanović
  • 2,261
  • 2
  • 24
  • 43