Home > Enterprise >  Not able to use an interface since the object is null
Not able to use an interface since the object is null

Time:02-24

I have a dialog that contains a button. When I press that button, I want the view of MainActivity to be changed.

I have tried it with an interface but I get this error:

java.lang.NullPointerException: Attempt to invoke interface method 'void ch.yourclick.kitt.classes.Popup$IControl.status(boolean)' on a null object reference

Popup.java

public interface IControl {
    void status(boolean status);
}
public IControl iControl = null;

    @SuppressLint({"ClickableViewAccessibility", "ResourceType"})
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Nullable
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        final View view =  inflater.inflate(_layout, container, false);

        view.findViewById(R.id.turbineStartUp).setOnClickListener(v -> {
            iControl.status(true);
        });

MainActivity.java

public class MainActivity extends AppCompatActivity implements View.OnClickListener, Popup.IControl {
    private final Popup mPopup = new Popup(R.layout.fragment_dialog);

    @Override
    public void status(boolean status) {
        System.out.println(status);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mPopup.iControl = this;

I don't see why the object is null, though I set mPopup.iControl = this; in onCreate(). What is wrong with my code?

CodePudding user response:

The reason is that when the instruction

private final Popup mPopup = new Popup(R.layout.fragment_dialog);

is executed, it calls the class Popup.java with

public IControl iControl = null;

and runs onCreateView and here

iControl.status(true);

refers to null objet.

To fix that, i suggest to customize the constructor of Popup class by adding an Icontrol parameter, something like that

private final Popup mPopup = new Popup(R.layout.fragment_dialog, this);

and edit the Popup.java file

  • Related