单击按钮获取位置时出错

Getting error on button click to fetch location

我得到的错误如下

尝试在空对象引用上调用虚方法'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)'

请告诉我哪里错了

Activity onCreate 函数

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    mbutton=(Button)findViewById(R.id.partymb);
    textview=(TextView)findViewById(R.id.tv);
    setContentView(R.layout.activity_menuact);
    locationmanager = (LocationManager) getSystemService(LOCATION_SERVICE);
    locationlistener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            textview.append("\n "+location.getLongitude() +" "+location.getLatitude());
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {

        }

        @Override
        public void onProviderEnabled(String provider) {

        }

        @Override
        public void onProviderDisabled(String provider) {
            Intent intent=new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            startActivity(intent);
        }
    };
    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(new String[]{
                    Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.INTERNET
            },10);
            return;
        }
    } else {
        configureButton();
    }
}

onRequestPermissionResult 函数

public void onRequestPermissionResult(int requestCode, String[] permission, int[] grantResults) {
  switch (requestCode){
      case 10:
          if(grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
              configureButton();
          return;
  }
}

配置按钮功能

private void configureButton() {
    mbutton.setOnClickListener(new View.OnClickListener(){
        public void onClick(View view) {
            locationmanager.requestLocationUpdates("gps", 5000, 5, locationlistener);
        }
    });

}

我参考了here

setContentView(R.layout.activity_menuact);

上一行应该紧跟在 super.onCreate(savedInstanceState);

之后

然后findViewById.

您在设置视图之前查找视图,因此所有视图都将仅为空。

您在

之前设置视图和 ID
setContentView(R.layout.activity_menuact);

你应该像下面这样设置

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


setContentView(R.layout.activity_menuact);
  mbutton=(Button)findViewById(R.id.partymb);
    textview=(TextView)findViewById(R.id.tv);
 }