I have multiple buttons in my app and I would like to have a single click listener for all buttons in R.layout.fragment_general
. This is what I have tried:
View view = inflater.inflate(R.layout.fragment_general, container, false); @SuppressLint("ResourceType") ViewGroup group = (ViewGroup) view.findViewById(R.layout.fragment_general); View v; for(int i = 0; i < group.getChildCount(); i++) { v = group.getChildAt(i); if(v instanceof Button) { v.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { System.out.println("A button has been clicked"); } }); } }
My app will crash and I get the error:
java.lang.NullPointerException: Attempt to invoke virtual method ‘int android.view.ViewGroup.getChildCount()’ on a null object reference
How should it be done correctly?
Answer
java.lang.NullPointerException: Attempt to invoke virtual method ‘int android.view.ViewGroup.getChildCount()’ on a null object reference
It means, that your group
is null. That happened brcause of this
@SuppressLint("ResourceType") ViewGroup group = (ViewGroup) view.findViewById(R.layout.fragment_general);
You should write yours ViewGroups id in findViewbyId(), but not the fragments layout name.