Getting warning when calling getView() in Fragment

if you are getting below warning from compiler in your class where you are trying to create Fragment instance;

Warning: Method invocation ‘getView().findViewById(R.id.test)’ may produce ‘java.lang.NullPointerException’

Then chances are you are inflating your layout in onCreateView and trying to access layout elements outside that method.

For example,

public class fragmentTest extends Fragment {

@Override
public void onActivityCreated(Bundle bundle) {
super.onActivityCreated(bundle);
TextView text = (textView) getView().findViewById(R.id.test);
// ...
}

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

The responsibility of getView() method is to return the view that has been inflated inside onCreateView method.
If for some reasons, the view is not accessible then getView() will return null and you will end up with NullPointerException.

To resolve the warning and any future exceptions, change the code as follow:

public class fragmentTest extends Fragment {
TextView mText;
@Override
public void onActivityCreated(Bundle bundle) {
super.onActivityCreated(bundle);
// Access mText here
// ...
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.testLayout, container, false);
mText = (TextView) view.findViewById(R.id.test);
return view;
}
}