NullPointerException on Button.findViewById()

I followed a tutorial to create a dialog in Android Studio. My code shows no error in the Java file, but says "Unfortunately app has stopped working". I don’t know why.

My java File:

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {
    private static Button b1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        onButoonListener();
    }
    
    public void onButoonListener(){
        b1=(Button) b1.findViewById(R.id.button);
        b1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    AlertDialog.Builder ad = new          AlertDialog.Builder(MainActivity.this);
                    ad.setMessage("Do you want to   close").setCancelable(false).setPositiveButton("yes", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                finish();
                            }
                        }).setNegativeButton("no", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                            }
                        });
                    AlertDialog ad1= ad.create();
                    ad1.setTitle("Alert!!");
                    ad1.show();
                }
            });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

My Xml fie:

<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=".MainActivity">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Button"
        android:id="@+id/button"
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true"
        android:layout_marginTop="188dp" />

</RelativeLayout>

My Logcat:

 06-13 21:32:20.500  11336-11336/hilz.myapplication E/AndroidRuntime﹕ FATAL EXCEPTION: main
        Process: hilz.myapplication, PID: 11336
        java.lang.RuntimeException: Unable to start activity ComponentInfo{hilz.myapplication/hilz.myapplication.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.widget.Button.findViewById(int)' 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 'android.view.View android.widget.Button.findViewById(int)' on a null object reference
                at hilz.myapplication.MainActivity.onButoonListener(MainActivity.java:23)
                at hilz.myapplication.MainActivity.onCreate(MainActivity.java:20)
                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)

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

You are invoking the findViewById() method in the wrong way. It should be invoked on the Activity itself, not on the Button reference. Replace

b1=(Button) b1.findViewById(R.id.button);

with

b1=(Button) findViewById(R.id.button);

The b1 reference is null at that point, and is the reason for the NullPointerException.

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply