The error I get is as follows
Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
Please tell me where I'm going wrong
Activity onCreate function
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 function
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 function
private void configureButton() {
mbutton.setOnClickListener(new View.OnClickListener(){
public void onClick(View view) {
locationmanager.requestLocationUpdates("gps", 5000, 5, locationlistener);
}
});
}
I took reference from here
setContentView(R.layout.activity_menuact);
Above line should come immediately after super.onCreate(savedInstanceState);
And after that do findViewById
.
You are finding views before setting a view so all views will be null only.