Reputation: 15
I tried to get a latitude and longitude and the address of the current location. When I tried in the emulator it worked..but when I tried to use my smartphone it was not working. I have added the location permissions in the manifest. Please help me with a solution. The emulator I have used is Pixel 4a API 30. I can't find where I have gone wrong.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView_location = findViewById(R.id.text_location);
button_location = findViewById(R.id.button_location);
//Runtime permissions
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(MainActivity.this,new String[]{
Manifest.permission.ACCESS_FINE_LOCATION
},100);
}
button_location.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//create method
getLocation();
}
});
}
@SuppressLint("MissingPermission")
private void getLocation() {
try {
locationManager = (LocationManager) getApplicationContext().getSystemService(LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,5000,5,MainActivity.this);
}catch (Exception e){
e.printStackTrace();
}
}
@Override
public void onLocationChanged(Location location) {
Toast.makeText(this, ""+location.getLatitude()+","+location.getLongitude(), Toast.LENGTH_SHORT).show();
try {
Geocoder geocoder = new Geocoder(MainActivity.this, Locale.getDefault());
List<Address> addresses = geocoder.getFromLocation(location.getLatitude(),location.getLongitude(),1);
String address = addresses.get(0).getAddressLine(0);
textView_location.setText(address);
}catch (Exception e){
e.printStackTrace();
}
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
}
Upvotes: 1
Views: 55