I am trying to implement an interface on a fragment. For this I created a Class "X" to perform an action. In this class I created a method that uses the interface object and in the fragment, I implement the interface and create an object of class "X", which calls the method that uses the interface object. As you can see in the code below.
The
public class ClassX {
private NewInterface newInterface;
public void sum(){
newInterface.sum(1,1);
}
}
The interface
public interface NewInterface {
public void sum(int a,int b);
}
The fragment
public class ExampeleFragment extends Fragment implements NewInterface {
private ClassX classx;
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_example, container, false);
classx.sum(1,1);
return root;
}
@Override
public void sum(int a, int b) {
int sum = a+b;
}
}
And I'm getting the error:
java.lang.NullPointerException: Attempt to invoke interface method on a null object reference
The NewInterface object in class x is null. However, this procedure works when I implement it in the MainActivity class. Does anyone know what may be happening?