如何解决此问题-NPE?

时间:2019-12-07 18:38:46

标签: java android nullpointerexception

我在手机上打开应用程序时遇到问题,该应用程序将关闭,并且来自Android Studio中的调试消息。      原因:java.lang.NullPointerException:尝试调用虚拟方法'void     android.widget.Button.setOnClickListener(android.view.View $ OnClickListener)'在一个空对象上     参考          at com.example.alartdialogs.MainActivity.onCreate(MainActivity.java:22)

package com.example.alartdialogs;

import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

private AlertDialog.Builder alert;
private Button button;

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

    button = (Button) findViewById(R.id.bottom);
    button.setOnClickListener(new View.OnClickListener() { //Line 22
        @Override
        public void onClick(View v) {
            alert = new AlertDialog.Builder(MainActivity.this);

          //  alert.setTitle(R.string.title);
            alert.setTitle(getResources().getString(R.string.title));
            alert.setMessage(getResources().getString(R.string.message));
            alert.setCancelable(false);
            alert.setPositiveButton(getResources().getString(R.string.yes),
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            MainActivity.this.finish();
                        }
                    });

            alert.setNegativeButton(getResources().getString(R.string.no),
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                        }
                    });
            AlertDialog dialog = alert.create();
            dialog.show();
        }
    });
}
}

0 个答案:

没有答案