[java] Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference

The problem is as follows. I have a login activity (in Android Studio) which worked fine a few days before. I don't remember changing anything but when I run this one the previous time the app closed right after I clicked the login button. The last thing indicated was the toast about pre-execution of AsyncTask. And I can't understand why there could be a NullPointerException. I have almost the same code for my signup activity and it works fine.

Here is the log:

05-28 16:04:52.395    1218-1232/system_process V/WindowManager? addAppToken: AppWindowToken{5d89eb token=Token{23ccc93a ActivityRecord{2fe54865 u0 utanashati.reminder/.HomepageActivity t17}}} to stack=1 task=17 at 1
05-28 16:04:52.407  19927-19927/utanashati.reminder D/AndroidRuntime? Shutting down VM
05-28 16:04:52.408  19927-19927/utanashati.reminder E/AndroidRuntime? FATAL EXCEPTION: main
    Process: utanashati.reminder, PID: 19927
    java.lang.RuntimeException: Unable to start activity
ComponentInfo{utanashati.reminder/utanashati.reminder.HomepageActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
            at android.app.ActivityThread.access$800(ActivityThread.java:151)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5257)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
            at utanashati.reminder.HomepageActivity.onCreate(HomepageActivity.java:55)
            at android.app.Activity.performCreate(Activity.java:5990)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
            at android.app.ActivityThread.access$800(ActivityThread.java:151)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5257)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
05-28 16:04:52.410    1218-1232/system_process W/ActivityManager? Force finishing activity 1 utanashati.reminder/.HomepageActivity
05-28 16:04:52.411    1218-1232/system_process W/ActivityManager? Force finishing activity 2 utanashati.reminder/.LoginActivity

EDIT 1

I had my eyes opened, the problem is not with LoginActivity, but with HomepageActivity. Here is the code:

import ...

public class HomepageActivity extends Activity implements AdapterView.OnItemSelectedListener {

    protected EditText mAddTaskText;
    protected Spinner mPrioritySpinner;
    protected Button mAddTaskButton;
    protected int intPriority = 0;
    protected String taskText;
    protected Timestamp taskTimestamp;
    protected Task userTask;
    protected JsonGenerator taskJSON;

    @Override
    protected void onCreate(Bundle savedInstanceState) {                        // Starts activity. The state can be restored from savedInstanceState
        super.onCreate(savedInstanceState);                                     // Calls the superclass method (IMPORTANT)
        setContentView(R.layout.activity_homepage);                             // Sets layout from activity_homepage.xml

        mPrioritySpinner = (Spinner) findViewById(R.id.prioritySpinner);        // Creates an ArrayAdapter using the string array and a default spinner layout
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
                R.array.priorityList, android.R.layout.simple_spinner_item);    // Specifies the layout to use when the list of choices appears
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);     // Applies the adapter to the spinner
        mPrioritySpinner.setAdapter(adapter);
        mPrioritySpinner.setOnItemSelectedListener(this);

        mAddTaskText = (EditText) findViewById(R.id.addTaskEditText);           // Finds View by its id in .xml file
        mAddTaskButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(HomepageActivity.this, "Done!", Toast.LENGTH_LONG).show();

                Calendar taskCalendar = Calendar.getInstance();             // Creates new calendar
                long taskTime = taskCalendar.getTimeInMillis();             // Gets time in milliseconds
                taskTimestamp = new Timestamp(taskTime);                    // Creates new Timestamp
                taskText = mAddTaskText.getText().toString();               // Gets description of the task

                userTask.setDate(taskTimestamp);                            // Sets date
                userTask.setText(taskText);                                 // Sets text

                /* Creating JsonGenerator */
                ObjectMapper mapper = new ObjectMapper();
                try {
                    mapper.writeValue(taskJSON, userTask);
                }
                catch (IOException e) {
                    Toast.makeText(HomepageActivity.this, "Could not create JSON", Toast.LENGTH_LONG).show();
                }

                /* Getting out email and password */
                String userPassword = ((EmailPassword) HomepageActivity.this.getApplication()).getPassword();
                String userEmail = ((EmailPassword) HomepageActivity.this.getApplication()).getUserEmail();
                Toast.makeText(HomepageActivity.this, userEmail + " " + userPassword, Toast.LENGTH_LONG).show();

                /* HTTP stuff */
                HttpPoster get = new HttpPoster();
                get.execute(userEmail, userPassword, taskJSON.toString());
            }
        });
    }

    public int getData (String username, String password, String taskJSON) {
        try {
            HttpPost httpPost = new HttpPost("http://something.com/" + username + "/tasks");
            String dataToEncode = username + ":" + password;
            String encodedData = Base64.encodeToString(dataToEncode.getBytes(), Base64.NO_WRAP);
            httpPost.setHeader("Authorization", encodedData);

            try {
                StringEntity taskEntity = new StringEntity(taskJSON, "UTF-8");
                httpPost.setEntity(taskEntity);
            }
            catch (UnsupportedEncodingException e) {
                Toast.makeText(HomepageActivity.this, "Unsupported encoding", Toast.LENGTH_LONG).show();
            }

            HttpClient client = new DefaultHttpClient();
            HttpResponse response = client.execute(httpPost);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if (statusCode == 200) {
                return 1;
            }
            else if (statusCode == 404) { return 2; }
            else if (statusCode == 500) { return 3; }
            else if (statusCode == 409) { return 4; }
            else { return statusCode; }
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        return 0;
    }

    public void onItemSelected(AdapterView<?> parent, View view,
                               int pos, long id) {
        String priority = parent.getItemAtPosition(pos).toString();             // Gets chosen priority
        Toast.makeText(HomepageActivity.this, priority, Toast.LENGTH_LONG).show();
        while (!((priority.equals("Low")) || (priority.equals("Medium")) || (priority.equals("High")))) {
            Toast.makeText(HomepageActivity.this, "Something bad happened. Try to choose again", Toast.LENGTH_LONG).show();
        }
        if (priority.equals("Low")) {
            intPriority = 0;
        }
        else if (priority.equals("Medium")) {
            intPriority = 1;
        }
        else if (priority.equals("High")) {
            intPriority = 2;
        }
        userTask.setPriority(intPriority);                                      // Sets chosen priority
    }

    public void onNothingSelected(AdapterView<?> parent) {
        userTask.setPriority(intPriority);                                      // Sets default priority ("0")
    }

    public class HttpPoster extends AsyncTask<String, Void, Integer> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected Integer doInBackground(String... params) {
            return getData(params[0], params[1], params[3]);
        }

        @Override
        protected void onPostExecute(Integer result) {
            super.onPostExecute(result);
            if (result == 1) {
                Toast.makeText(HomepageActivity.this, "Login successful", Toast.LENGTH_LONG).show();
                Intent takeUserHome = new Intent(HomepageActivity.this, HomepageActivity.class);
                startActivity(takeUserHome);
            }
            else if (result == 2) {
                Toast.makeText(HomepageActivity.this, "No such user", Toast.LENGTH_LONG).show();
            }
            else if (result == 3) {
                Toast.makeText(HomepageActivity.this, "Internal server error: unable to send email", Toast.LENGTH_LONG).show();
            }
            else if (result == 4) {
                Toast.makeText(HomepageActivity.this, "Task already exists", Toast.LENGTH_LONG).show();
            }
            else {
                Toast.makeText(HomepageActivity.this, result.toString(), Toast.LENGTH_LONG).show();
            }
        }
    }
}

And XML file:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="utanashati.testapp.HomepageActivity">

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Add a new task..."
        android:id="@+id/addTaskEditText"
        android:nestedScrollingEnabled="false"
        android:minLines="1"
        android:maxLines="1" />

    <Spinner
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/prioritySpinner"
        android:layout_alignRight="@+id/addTaskButton"
        android:layout_alignEnd="@+id/addTaskButton"
        android:layout_below="@+id/addTaskEditText" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Add task"
        android:id="@+id/addTaskButton"
        android:layout_below="@+id/prioritySpinner"
        android:layout_centerHorizontal="true" />

</RelativeLayout>

This question is related to java android android-asynctask nullpointerexception

The answer is


Got the same error, CHECK THIS : MINOR SILLY MISTAKE

check findviewbyid(R.id.yourID); If you have put the id correct or not.


That true,Mustafa....its working..its point to two layout

  1. setContentView(R.layout.your_layout)
  2. v23(your_layout).

You should take Button both activity layout...
solve this problem successfully


Placing setOnClickListener in onStart method solved the problem for me. Checkout "Android Lifecycle concept" for further clarification


Check out this solution. It worked for me..... Check the id of the button for which the error is raised...it may be the same in any one of the other page in your app. If yes, then change the id of them and then the app runs perfectly.

I was having two same button id's in two different XML codes....I changed the id. Now it runs perfectly!! Hope it works


Just define the button as lateinit var at top of your class:

 lateinit var buttonOk: Button

When you want to use a button in another layout you should define it in that layout. For example if you want to use button in layout which name is 'dialogview', you should write:

 buttonOk = dialogView.findViewById<Button>(R.id.buttonOk)

After this you can use setonclicklistener for the button and you won't have any error. You can see correct answer of this question: Android Kotlin findViewById must not be null


It seems the button you are invoking is not in the layout you are using in setContentView(R.layout.your_layout) Check it.


 mAddTaskButton.setOnClickListener(new View.OnClickListener()

you have a click listner but you haven't initialized the mAddTaskButton with your layout binding


i had the same problem and it seems like i didn't initiate the button used with click listener, in other words id didn't te


Make sure that while using : Button "varName" =findViewById("btID"); you put in the right "btID". I accidentally put in the id of a button from another similar activity and it showed the same error. Hope it helps.


mAddTaskButton is null because you never initialize it with:

mAddTaskButton = (Button) findViewById(R.id.addTaskButton);

before you call mAddTaskButton.setOnClickListener().


Check whether you have matching IDs in both Java and XML


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 android-asynctask

Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference Android check null or empty string in Android java.net.UnknownHostException: Unable to resolve host "<url>": No address associated with hostname and End of input at character 0 of java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState Android basics: running code in the UI thread How to get the result of OnPostExecute() to main activity because AsyncTask is a separate class? Android. Fragment getActivity() sometimes returns null android asynctask sending callbacks to ui AsyncTask Android example Return a value from AsyncTask in Android

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