简体   繁体   中英

Null Pointer exception to a button in a Dialog -- Android -- JAVA

This has been asked a million times, but I cannot get my code to work:

public class MainActivity extends AppCompatActivity {

//private static final String LOG_TAG = "SongList";
Dialog mDialog;
Button button;
static final String LOG_TAG = "SONG_APP";

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

    // Setup Floating Action Button that is used by user to open EditorActivity
    FloatingActionButton fab = findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            mDialog = new Dialog (MainActivity.this);
            button = mDialog.findViewById(R.id.button);
            
            mDialog.setContentView(R.layout.fab_search_popup);
            mDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

            try {
                button.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Log.e(LOG_TAG,"Button is clicked");
                        mDialog.dismiss();
                    }
                });
                mDialog.show();

            } catch (NullPointerException e) {
                Log.e(LOG_TAG, "Null Pointer Exception");
                }
        }
    });

}

}

And the Layout file for the Dialog is:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="300dp"
    android:layout_height="400dp"
    android:layout_gravity="center"
    android:padding="12dp">

    <Button
        android:id="@+id/button"
        android:layout_width="100dp"
        android:layout_height="50dp"
        android:layout_centerInParent="true"
        android:background="@color/teal_200"
        android:gravity="center"
        android:text="Button" />

</RelativeLayout>

I still get a Null value for button at the below line and don't know why:

button = mDialog.findViewById(R.id.button);

I have stripped down my code to the bone but cannot figure out why it is null. Please Help

You're inflating the dialog layout AFTER you get the reference to your button. It returns null because your dialog object, before inflation, has no button view with id "button"

You should change the order to this

mDialog.setContentView(R.layout.fab_search_popup);
button = mDialog.findViewById(R.id.button);

Let me know if that helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM