[java] Null pointer Exception on .setOnClickListener

I am having an issue with a click listener for a login modal submit button.

This is the error.

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference

I have a reasonable understanding of what a null pointer exception is and I have search thoroughly for an issue similar to mine. I have tried to reformat the click listener in several ways, made sure I have the correct view ID etc.

package...
import...
public class MainActivity extends ActionBarActivity implements     NavigationDrawerFragment.NavigationDrawerCallbacks {

    //Variables
    String currentPage = "";
    Stack<String> crumbs = new Stack<String>();
    //Fragment managing the behaviors, interactions and presentation of the navigation drawer.
    private NavigationDrawerFragment mNavigationDrawerFragment;
    // Used to store the last screen title. For use in {@link #restoreActionBar()}.
    public CharSequence mTitle;
    //temp
    AuthenticateUserTokenResult authenticateUserTokenResult;
    String loginErrorMessage = "";
    String loginErrorTitle = "";
    Boolean logonSuccessful = false;
    Dialog loginDialog;

    // Login EditTexts
    EditText Username;
    EditText CompanyID;
    EditText Password;
    Button Submit;

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

        mNavigationDrawerFragment = (NavigationDrawerFragment) getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
        mTitle = getTitle();  // Set up the drawer.
        mNavigationDrawerFragment.setUp(R.id.navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout));

        if(authenticateUserTokenResult == null) {
            attemptLogin();
        }
    }

    public void attemptLogin() {
        loginDialog = new Dialog(this,android.R.style.Theme_Translucent_NoTitleBar);
        loginDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        loginDialog.setContentView(R.layout.login_modal);
        loginDialog.setCancelable(false);
        //loginDialog.setOnCancelListener(cancelListener);
        loginDialog.show();
        Submit = (Button)findViewById(R.id.Submit);
        Submit.setOnClickListener(new View.OnClickListener() // the error is on this line (specifically the .setOnClickListener)
        {
            @Override
            public void onClick(View v)
            {
                ClyxUserLogin user = new ClyxUserLogin();
                Username = (EditText)findViewById(R.id.Username);
                user.logon = Username.getText().toString();
                CompanyID = (EditText)findViewById(R.id.CompanyID);
                user.idCompany = Integer.parseInt(CompanyID.getText().toString());
                Password = (EditText)findViewById(R.id.Password);
                user.password = Password.getText().toString();
                user.idApplication = 142;
                authenticate(user);
            }
        });
    }

There is more, obviously, but not relevant to the topic I think. Here is the XML file for the dialog that has the button on it.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#3366FF">

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:background="#FFFFFF" >

        <TextView
            android:id="@+id/LoginTitle"
            android:layout_width="200dp"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:layout_marginTop="10dp"
            android:layout_marginStart="10dp"
            android:textColor="#000000"
            android:textSize="20sp"
            android:text="Login" />

        <EditText
            android:id="@+id/Username"
            android:layout_width="200dp"
            android:layout_height="wrap_content"
            android:layout_below="@+id/LoginTitle"
            android:layout_margin="10dp"
            android:hint="Username" />

        <EditText
            android:id="@+id/CompanyID"
            android:layout_width="200dp"
            android:layout_height="wrap_content"
            android:layout_below="@+id/Username"
            android:layout_alignStart="@+id/Username"
            android:inputType="number"
            android:hint="Company ID" />

        <EditText
            android:id="@+id/Password"
            android:layout_width="200dp"
            android:layout_height="wrap_content"
            android:layout_below="@+id/CompanyID"
            android:layout_alignStart="@+id/Username"
            android:layout_marginTop="10dp"
            android:layout_marginBottom="10dp"
            android:inputType="textPassword"
            android:hint="Password" />

        <Button
            android:id="@+id/Submit"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/Password"
            android:layout_marginBottom="10dp"
            android:layout_centerHorizontal="true"
            android:text="Login" />

    </RelativeLayout>

</RelativeLayout>

Any help would be greatly appreciated.

This question is related to java android nullpointerexception onclicklistener

The answer is


Submit is null because it is not part of activity_main.xml

When you call findViewById inside an Activity, it is going to look for a View inside your Activity's layout.

try this instead :

Submit = (Button)loginDialog.findViewById(R.id.Submit);

Another thing : you use

android:layout_below="@+id/LoginTitle"

but what you want is probably

android:layout_below="@id/LoginTitle"

See this question about the difference between @id and @+id.


I too got similar error when i misplaced the code

text=(TextView)findViewById(R.id.text);// this line has to be below setcontentview
setContentView(R.layout.activity_my_otype);
//this is the correct place
text.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            }
    });

I got it working on placing the code in right order as shown below

setContentView(R.layout.activity_my_otype);
text=(TextView)findViewById(R.id.text);
 text.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            }
    });

android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference

Because Submit button is inside login_modal so you need to use loginDialog view to access button:

Submit = (Button)loginDialog.findViewById(R.id.Submit);

Try giving your Button in your main.xml a more descriptive name such as:

<Button
                android:id="@+id/buttonXYZ"

(use lowercase in your xml files, at least, the first letter)

And then in your MainActivity class, declare it as:

Button buttonXYZ;

In your onCreate(Bundle savedInstanceState) method, define it as:

buttonXYZ = (Button) findViewById(R.id.buttonXYZ);

Also, move the Buttons/TextViews outside and place them before the .setOnClickListener - it makes the code cleaner.

Username = (EditText)findViewById(R.id.Username);
CompanyID = (EditText)findViewById(R.id.CompanyID);

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to nullpointerexception

Filter values only if not null using lambda in Java8 Why use Optional.of over Optional.ofNullable? Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference Null pointer Exception on .setOnClickListener - java.lang.NullPointerException - setText on null object reference NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equalsIgnoreCase(java.lang.String)' on a null object reference java.lang.NullPointerException: Attempt to invoke virtual method on a null object reference Java 8 NullPointerException in Collectors.toMap NullPointerException in eclipse in Eclipse itself at PartServiceImpl.internalFixContext The server encountered an internal error that prevented it from fulfilling this request - in servlet 3.0

Examples related to onclicklistener

Android - setOnClickListener vs OnClickListener vs View.OnClickListener Null pointer Exception on .setOnClickListener Multiple Buttons' OnClickListener() android Android setOnClickListener method - How does it work? RecyclerView onClick How do I open a new fragment from another fragment? Why is this jQuery click function not working? Android button onClickListener Android: how to handle button click Adding an onclicklistener to listview (android)