0

I have two fragments classes say A and B and one mainactivity class.I looked some tutorials and have added recycler view(this is not the main concern though).Following up the tutorial on my both fragment classes i have this code

@Nullable
@Override
public View onCreateView (LayoutInflater inflater, @Nullable 
    ViewGroup container, @Nullable Bundle savedInstanceState){
    View rootView = inflater.inflate(R.layout.absent, container, false);
    return rootView;  
}

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);  
}

so what is the use of @Nullablehere?.i have searched this many times but i can't understand it's use and even that tutorial haven't mentioned anything about @nullabe.Can anyone make me understand about this? please don't bother in talking about recycler view because i have already added it.

Rob Avery IV
  • 3,562
  • 10
  • 48
  • 72
bikash giri
  • 1,444
  • 1
  • 10
  • 15

3 Answers3

2

The @Nullable annotation indicates a variable, parameter, or return value that can be null You ever get a "NullPointerException"? That's because the value is null.

Integer x; 

'x' Will be null because you haven't assigned a value to it so there will be errors using it. But what if you have a variable that might actually be null in some use cases? Well, you'd use the @Nullable annotation meaning that it's okay to be null.

@Nullable Bundle savedInstanceState

Bundle in this case might have nothing stored in it. So it's okay to be null when the method is called.

Same goes for the method onCreateView() meaning that the return can be null

Daniel Nugent
  • 43,104
  • 15
  • 109
  • 137
Stephen
  • 1,072
  • 1
  • 19
  • 33
1

@Nullable allows variables with null values as argument. And in method cases, allows called method to return a null values. For more info, checkout the following answer.

Community
  • 1
  • 1
AlexTa
  • 5,133
  • 3
  • 29
  • 46
1

It's a compile time annotation that tells the compiler (and you) that the incoming parameter could be nullable. Thus, you need to be able to handle that scenario. It can also be used for other code analyzers to help analyze your code and find potential errors.

On the flip-side, there is also the @NonNull annotation which says that the method does not accept or handle null objects. So, if you were to use it, the LINTer would produce a warning or error if a null object was passed in.

None of these annotations on run-time. They're only meant to guide you to producing higher quality code.

DeeV
  • 35,865
  • 9
  • 108
  • 95