点击按钮获取错误以获取位置

时间:2017-04-12 09:35:35

标签: android android-gps

我得到的错误如下

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

请告诉我我哪里出错了

活动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;
  }
}

ConfigureButton函数

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

}

我参考了here

2 个答案:

答案 0 :(得分:3)

setContentView(R.layout.activity_menuact);

上面的行应该在super.onCreate(savedInstanceState);

之后立即出现

然后执行findViewById

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

答案 1 :(得分:0)

您正在设置

之前的视图和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);
 }