Android Fragment 2 Awesome Errors: Must implement OnFragmentInteractionListener, Attempt to invoke virtual method ‘android.view.View android.view.View.findViewById(int)’ on a null object reference

Burcu S
2 min readDec 9, 2019

--

This post is different from my others. Cause I won’t write explanations or something long, it’s kinda like a note for myself. This will be a quick guide just like this -> Error and it’s solution.

When we create a fragment, some default codes are generated like in below. Then we get excited and we say “yes I created a Fragment!”. Everthing is going well. And after all these things we are ready to use it. We call it from our Activity using by FragmentManager.

But then we see these things in our logs suddenly.

1) java.lang.RuntimeException: Unable to resume activity {package/activity}: java.lang.RuntimeException: activity must implement OnFragmentInteractionListener

Then… We calm down and add this to our Activity.

public class MainActivity extends AppCompatActivity implements YourFragmentName.OnFragmentInteractionListener

But don’t forget check whether have these things in your fragment:

  • a variable

private OnFragmentInteractionListener mListener;

  • a method

public interface OnFragmentInteractionListener {
void onFragmentInteraction(Uri uri);
}

And this error fixed…

2) Attempt to invoke virtual method ‘android.view.View android.view.View.findViewById(int)’ on a null object reference

This two errors has great harmony with each others. This error occurs after the first generally. It happens when we said “Yeah I fixed the error, that’s okey!”…

The solution is very simple. Let’s go to our fragment. There is a code line like that in onCreateView:

return inflater.inflate(R.layout.fragment_layout_name, container, false);

Write this:

View view = inflater.inflate(R.layout.fragment_connect_device, container, false);

return view;

instead of

return inflater.inflate(R.layout.fragment_layout_name, container, false);

And we won’t get error when we try to run “getView.findViewById” anymore cause we will use “view.findViewById”.

--

--

Burcu S
Burcu S

Written by Burcu S

Lead Mobile Engineer | Flutter Developer, Lover & Learner | For contact: linkedin.com/in/burcus/

Responses (1)