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.
you are setting view and id before
setContentView(R.layout.activity_menuact);
you should set like below
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);
}
Related
So I've tried to get the users location and wanted it to popup as a Toast() or in the Logs but nothing happens.
I've added <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> to the manifest and this is my class:
public class MainActivity extends AppCompatActivity {
private LocationManager locationManager;
private LocationListener locationListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Get the users location
locationManager = (LocationManager)
this.getSystemService(Context.LOCATION_SERVICE);
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
Log.i("LOCATION", location.toString());
Toast.makeText(MainActivity.this, location.toString(),
Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle
extras) {
Log.i("STATUS", String.valueOf(status));
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
// Ask users permission to get location
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},1);
} else {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locationListener);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 1) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locationListener);
}
}
}
}
}
The app asks for permission the first time and after I accept it doesn't show any signs of getting a location from the OnStatusChanges() method. I've tried to get lastKnownLocation()and it works but that's all...
Any idea what's missing?
Thanks!
I am new to android. I am creating a android service which retrieves the current location and send it as a message to a particular number. I have almost achieved it, but when I use SMSManager to send message of the retrieved location value the app crashes(I have commented the code in the attachment). I have achieved up-to the step of retrieving the current location and display it on EditText. I have included all the permissions.Kindly help me to fix the issue of sending message of the received intent value. I have included the code of MainActivity and BroadcastService
int count=1;
#Override
protected void onResume() {
super.onResume();
if(broadcastReceiver == null){
broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
textView.setText("\n" +intent.getExtras().get("coordinates"));
String loc = textView.getText().toString();
/*
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage("7448958358", null, loc, null, null);
*/
}
};
}
registerReceiver(broadcastReceiver,new IntentFilter("location_update"));
}
#Override
protected void onDestroy() {
super.onDestroy();
if(broadcastReceiver != null){
unregisterReceiver(broadcastReceiver);
}
}
private void sendSMS(String phoneNumber, String message) {
Toast.makeText(this, "sending", Toast.LENGTH_SHORT).show();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_start = (Button) findViewById(R.id.button);
btn_stop = (Button) findViewById(R.id.button2);
textView = (TextView) findViewById(R.id.textView);
if(!runtime_permissions())
{
enable_buttons();
}
}
private void enable_buttons() {
btn_start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i =new Intent(getApplicationContext(),BroadcastService.class);
startService(i);
}
});
btn_stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i =new Intent(getApplicationContext(),BroadcastService.class);
stopService(i);
}
});
}
private boolean runtime_permissions() {
if(Build.VERSION.SDK_INT >= 23 && ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ContextCompat.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.SEND_SMS,Manifest.permission.RECEIVE_SMS},100);
return true;
}
return false;
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(requestCode == 100){
if( grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED){
enable_buttons();
}else {
runtime_permissions();
}
}
}
BroadcastService.java
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#SuppressLint("MissingPermission")
#Override
public void onCreate() {
Toast.makeText(this, "Services has been started", Toast.LENGTH_SHORT).show();
listener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
Intent i = new Intent("location_update");
i.putExtra("coordinates",location.getLongitude()+" "+location.getLatitude());
sendBroadcast(i);
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
}
};
locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
//noinspection MissingPermission
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,3000,0,listener);
}
#Override
public void onDestroy() {
super.onDestroy();
if(locationManager != null){
//noinspection MissingPermission
locationManager.removeUpdates(listener);
}
}
My crash log says
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.prakaash.broadcastservice, PID: 27810
java.lang.RuntimeException: Error receiving broadcast Intent { act=location_update flg=0x10 (has extras) } in com.example.prakaash.broadcastservice.MainActivity$1#9f66542
at android.app.LoadedApk$ReceiverDispatcher$Args.lambda$-android_app_LoadedApk$ReceiverDispatcher$Args_51117(LoadedApk.java:1300)
at android.app.-$Lambda$FilBqgnXJrN9Mgyks1XHeAxzSTk.$m$0(Unknown Source:4)
at android.app.-$Lambda$FilBqgnXJrN9Mgyks1XHeAxzSTk.run(Unknown Source:0)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:172)
at android.app.ActivityThread.main(ActivityThread.java:6637)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Caused by: java.lang.SecurityException: Neither user 10119 nor current process has android.permission.READ_PHONE_STATE.
at android.os.Parcel.readException(Parcel.java:1942)
at android.os.Parcel.readException(Parcel.java:1888)
at com.android.internal.telephony.ISms$Stub$Proxy.sendTextForSubscriber(ISms.java:867)
at android.telephony.SmsManager.sendTextMessageInternal(SmsManager.java:330)
at android.telephony.SmsManager.sendTextMessage(SmsManager.java:313)
at com.example.prakaash.broadcastservice.MainActivity$1.onReceive(MainActivity.java:42)
at android.app.LoadedApk$ReceiverDispatcher$Args.lambda$-android_app_LoadedApk$ReceiverDispatcher$Args_51117(LoadedApk.java:1290)
at android.app.-$Lambda$FilBqgnXJrN9Mgyks1XHeAxzSTk.$m$0(Unknown Source:4)
at android.app.-$Lambda$FilBqgnXJrN9Mgyks1XHeAxzSTk.run(Unknown Source:0)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:172)
at android.app.ActivityThread.main(ActivityThread.java:6637)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Application terminated.
This issue doesn't happen for all the manufacturers. The official document doesnt specify the need for requesting this permission. Some manufacturers have issues in implementation of sendTextMessage due to which READ_PHONE_STATE permission is required.
To fix the issue only workaround is to add this permission to your Manifest and requestPermissions.
Used this code on previous app and all seems ok - but today im getting a
call requires permission which may be rejected by user
I have added
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
to manifest and have read several threads on the subject, but still having issues. Could you guys helps out.
public class MainActivity extends AppCompatActivity implements LocationListener
{
private LocationManager locationManager;
public static String locationlong;
public static String locationlati;
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tv = (TextView)findViewById(R.id.pig);
TextView cow = (TextView)findViewById(R.id.cow);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 1, this);
}
}
Add the permission check in your activity:
in your code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tv = (TextView) findViewById(R.id.pig);
TextView cow = (TextView) findViewById(R.id.cow);
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 0);
}
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (checkLocationPermission()) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 1, this);
}
}
public boolean checkLocationPermission() {
String permission = "android.permission.ACCESS_FINE_LOCATION";
int res = this.checkCallingOrSelfPermission(permission);
return (res == PackageManager.PERMISSION_GRANTED);
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case 0: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(getApplicationContext(), "Permission granted", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Permission denied", Toast.LENGTH_SHORT).show();
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
Basically since android 6 you need to ask certain permissions on runtime , so the user may reject them.
Use checkSelfPermission(..) to ask for it and override onRequestPermissionsResult to see the answer.
Here's a link with the full example:
https://developer.android.com/training/permissions/requesting.html
I am trying to send users location via sms. I can get the users location but it takes lot time while the smsmanager sends the message with null value of location can somebody see my code or guide me what is wrong here. thanks!
public class MainActivity extends AppCompatActivity {
public Button button;
private LocationManager locationManager;
private LocationListener listener;
private String gpslonla;
private TextView t;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
getlocation();
sendlocationsms();
}
private void sendlocationsms() {
String phoneNumber = "903399000";
//Location location = new Location("dummyprovider");
SmsManager smsManager = SmsManager.getDefault();
StringBuffer smsBody = new StringBuffer();
smsBody.append("http://maps.google.com?q="+gpslonla);
//smsBody.append(location.getLatitude());
//smsBody.append(",");
//smsBody.append(location.getLongitude());
smsManager.sendTextMessage(phoneNumber, null, smsBody.toString(), null, null);
int gravity = Gravity.CENTER; // the position of toast
int xOffset = 0; // horizontal offset from current gravity
int yOffset = 0; // vertical offset from current gravity
Toast toast = Toast.makeText(getApplicationContext(), "Your message has been sent ", Toast.LENGTH_SHORT);
toast.setMargin(50, 50);
toast.setGravity(gravity, xOffset, yOffset);
toast.show();
}
});
}
private void getlocation() {
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
listener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
gpslonla=location.getLongitude() + "," + location.getLatitude();
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(i);
}
};
configure_button();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case 10:
configure_button();
break;
default:
break;
}
}
void configure_button() {
// first check for permissions
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.INTERNET}
, 10);
}
return;
}
// this code won't execute IF permissions are not allowed, because in the line above there is return statement.
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//noinspection MissingPermission
locationManager.requestLocationUpdates("gps", 5000, 0, listener);
}
});
}
}
You must call the sendlocationsms() method when the location is received. Change your onClick method with:
EDITED:
Declare a boolean variable with initial value to false:
boolean needsToSendSms = false;
Then:
#Override
public void onClick(View view) {
needsToSendSms = true;
getlocation();
}
And call it when the location changes with
#Override
public void onLocationChanged(Location location) {
gpslonla=location.getLongitude() + "," + location.getLatitude();
if(needsToSendSms) {
sendlocationsms();
needsToSendSms = false;
}
}
Adding the boolean variable makes to only send one sms per click.
I hope this helps.
I've got problem. I need only one information about location. I want to click on my button, get location and stop GPS. But in my case it gives me informations about location every 5 seconds. It'S possible to make it work, how i want it? Because i want to save data about start of road in sqlite database. So i need only one information about location. Like my first idea, or the most simple thing i can do, was making the time interval larger than five seconds, something like 5 000 000 seconds. But it's not the best solution i think. :)
this is my code
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent dbmanager = new Intent(MainActivity.this, AndroidDatabaseManager.class);
startActivity(dbmanager);
}
});
locLIST = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
gps1.append("\n " + location.getLatitude() + " " + location.getLongitude());
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
Intent intent1 = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent1);
}
};
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();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode){
case 10:
if (grantResults.length>0&&grantResults[0]== PackageManager.PERMISSION_GRANTED)
configureButton();
return;
}
}
private void configureButton() {
buttonGPS.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
locman.requestLocationUpdates("gps", 0, 0, locLIST);
}
});
}