2017-04-12 66 views
-1

我得到的是如下按鈕獲取錯誤點擊獲取位置

嘗試在空調用虛擬方法無效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

回答

3
setContentView(R.layout.activity_menuact); 

,上面一行是後super.onCreate(savedInstanceState);

馬上過來後做findViewById

在設置視圖之前您正在查找視圖,因此所有視圖都將僅爲null。

0

您在設置之前

setContentView(R.layout.activity_menuact); 

視圖和id,你應該設置如下圖所示

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); 
}