Fix “Attempt to invoke virtual method on a null object reference” in Android Fragments

Android: How to fix “null object reference” error (with code)

java.lang.NullPointerException: Attempt to invoke virtual method '... android.widget.TextView.getText()' on a null object reference is one of the most common crashes in Android apps that use Fragments. The message is clear about what happened, a view you called a method on is null, but not why. This guide explains the usual causes and shows the modern fix.

The symptom

You have a Fragment with a couple of EditText fields, a Button and a TextView for the result. The screen loads fine, but as soon as you press the button the app crashes and Logcat shows the error above, pointing at the line where you read or write one of the views.

Why the view is null

findViewById() returns null when it cannot find a view with that ID in the layout it searches. In Fragments that happens for three reasons:

  • Searching the wrong layout. Code such as getActivity().findViewById(R.id.result) searches the Activity’s layout, but the view lives in the Fragment’s layout. This was the cause in the original version of this post, and it is still the most common one.
  • Searching too early. Calling findViewById() in onCreate(), before the Fragment has inflated its layout, always returns null.
  • Using a view after it is destroyed. When a Fragment goes to the back stack its view is destroyed but the Fragment object survives. Keeping view references in fields and using them later, for example in a network callback, gives a stale or null view.

The broken code

public class CalculatorFragment extends Fragment {
    private TextView result;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Wrong: searches the Activity, and the Fragment's view does not exist yet
        result = getActivity().findViewById(R.id.result);
    }
}

Fix 1: find views in onViewCreated()

Look views up on the Fragment’s own root view, after it has been created:

public class CalculatorFragment extends Fragment {

    public CalculatorFragment() {
        super(R.layout.fragment_calculator);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        EditText first = view.findViewById(R.id.first);
        EditText second = view.findViewById(R.id.second);
        TextView result = view.findViewById(R.id.result);

        view.findViewById(R.id.add).setOnClickListener(v -> {
            double a = Double.parseDouble(first.getText().toString());
            double b = Double.parseDouble(second.getText().toString());
            result.setText(String.valueOf(a + b));
        });
    }
}

Passing the layout ID to the super() constructor lets the Fragment inflate it for you, so you no longer need to override onCreateView().

Fix 2 (recommended): use View Binding

View Binding generates a class with a typed field for every view that has an ID, so a wrong or missing ID becomes a compile error instead of a crash. Turn it on in app/build.gradle:

android {
    buildFeatures {
        viewBinding true
    }
}

Then use the generated FragmentCalculatorBinding class, and clear it when the view is destroyed so you never touch a dead view:

public class CalculatorFragment extends Fragment {
    private FragmentCalculatorBinding binding;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle state) {
        binding = FragmentCalculatorBinding.inflate(inflater, container, false);
        return binding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle state) {
        binding.add.setOnClickListener(v -> {
            double a = Double.parseDouble(binding.first.getText().toString());
            double b = Double.parseDouble(binding.second.getText().toString());
            binding.result.setText(String.valueOf(a + b));
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }
}

Other causes worth checking

  • The ID exists in a different layout. Two layouts can share an ID. Make sure the one you search actually contains it, including every variant such as layout-land.
  • Empty input. Double.parseDouble("") throws NumberFormatException, a different crash that often appears right after you fix this one. Check TextUtils.isEmpty() first.
  • Callbacks after the user leaves. In network or database callbacks, check binding != null or isAdded() before touching views.

Summary

Find views on the Fragment’s own view, never on the Activity, and only from onViewCreated() onwards. Better still, switch to View Binding and clear it in onDestroyView(). Together those two habits remove this crash entirely.

Written by

GitHub · About Codeonion · Contact

4 responses to “Fix “Attempt to invoke virtual method on a null object reference” in Android Fragments”

  1. Thank you so much for this! I’ve spent days looking for a solution and this has finally worked for me, thanks!

  2. Austin

    How tf do i get there my phone is constantly getting the message

  3. Austin

    How tf do i get there my phone is constantly getting the message

  4. Anonymous

    What’d your code look like if your had to export your result to another Activity, and display it there ?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

>> Related articles

all articles →