0

I am using databinding in my project. In a fragment I am using DataBinding like following

public class ExampleFragment extends Fragment  {

     private FragmentExampleBinding mFragmentExampleBinding;

     @Override
     public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        //initializing data binding object
        mFragmentExampleBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_example, container, false);
        // is there any posibility that mFragmentExampleBinding can be null
        View view = mFragmentExampleBinding.getRoot();
        return view;
      }
}

My question is, is there any possibility that databinding object may return null? Do we really need to do null check while using databinding ?

1
  • I keep getting null back in a feature module, that is a module where the build.gradle imports com.android.feature instead of com.android.application, I'm not sure why this is though. Commented Mar 14, 2019 at 22:04

1 Answer 1

1

Normally it's quite trustworthy and I don't need to check it every time.

https://developer.android.com/reference/android/databinding/DataBindingUtil#inflate

 * @return The newly-created binding for the inflated layout or <code>null</code> if
 * the layoutId wasn't for a binding layout.

But it may be null if there is something wrong in the xml.

However, if you decided to clear the view reference in the onDestroyView(set binding to null) to avoid memory leak, you do need to do null check or throw an exception in case you access binding after the view is destroyed.

At least for now, when using one activity + multiple fragments architectures, I have to set the binding(and other view references) to null to avoid the memory leak.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.