-2

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?

Meu Email
  • 11
  • 3

1 Answers1

1

You get the NullPointerException because you did not assign anything to the newInterface property in your ClassX object.

I don't understand why you call classx.sum(1,1); while your sum method on ClassX doesn't accept any parameters.

Try this:
Create a constructor for your ClassX which takes a NewInterface parameter. So your ClassX would look like this:

public class ClassX {

private NewInterface newInterface;

public ClassX(NewInterface newInterface) {
    this.newInterface = newInterface;
}

public void sum(){

    newInterface.sum(1,1);

}

}

and then initialize your classX object like this:

classX = new ClassX(this);

before calling

classX.sum();
danartillaga
  • 1,349
  • 1
  • 8
  • 19
  • Thanks. I had forgotten to put the parameters in this example. I passed the interface on the class x constructor and it worked. – Meu Email Jan 10 '21 at 15:01