Search code examples
javaandroidnullpointerexceptionsinch

Android - Why calling this function directly instead of onClick causes a NullPointerException?


I am trying to integrate the Sinch Android SDK in my project and I wanted to remove the Login button, i.e. such that the Activity switches to the next activity without the user having to click the Login button. For this, I removed the code for setOnClickListener for the mLoginButton and instead, directly called the loginClicked() function, which was previously being called from the onClick() method.
But this causes NullPointerException: Attempt to invoke virtual method 'boolean com.example.yankee.cw.SinchService$SinchServiceInterface.isStarted()' on a null object reference.
These are the only changes I made to the code:

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

        mLoginName = (EditText) findViewById(R.id.loginName);

        mLoginButton = (Button) findViewById(R.id.loginButton);
        mLoginButton.setEnabled(false);
//        mLoginButton.setOnClickListener(new OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                loginClicked();
//            }
//        });
        loginClicked();
    }

And earlier it was like this:

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

        mLoginName = (EditText) findViewById(R.id.loginName);

        mLoginButton = (Button) findViewById(R.id.loginButton);
        mLoginButton.setEnabled(false);
        mLoginButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                loginClicked();
            }
        });
    }  

Why doesn't this work and gives the NullPointerException instead ?

Edit: LoginActivity.java


Solution

  • getSinchServiceInterface() method is returning null that is why you are getting null pointer exception.

    Earlier loginCliked() method was getting called after button was enabled in onServiceConnected method.

    try calling loginClicked() method in onServiceConnected() method or use some delay.