I'm trying to make a simple app to show my location coordinates. When I emulate the code ( nexus 6.0 , it works). However, when I use a real device via usb debugging (my htc 10), nothing appears when I press the button to show my coordinates. Any idea why? This is my code:
//Location
textView = (TextView) findViewById(R.id.textView);
button2 = (Button) findViewById(R.id.button2);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
listener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
textView.append("\n " + location.getLongitude() + " " + location.getLatitude());
System.out.println(location.getLongitude());
System.out.println(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.
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//noinspection MissingPermission
locationManager.requestLocationUpdates("gps", 5000, 0, listener);
}
});
}
I have this added in my manifest:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-feature android:name="android.hardware.location.gps" />
You should declare the button2 click listener in oncreate as there is return statement in configure_button() method.
Just declare it right after declaring ids.
textView = (TextView) findViewById(R.id.textView);
button2 = (Button) findViewById(R.id.button2);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//noinspection MissingPermission
locationManager.requestLocationUpdates("gps", 5000, 0, listener);
}
});
//rest of the code
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!
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
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);
}
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);
}
});
}