I was trying to make google map application but when i try to build the app it gives me a weird error on some casting sentences please help
the error
the error 1
the androidstudio can not find R Class
This is the map activity where i am loading the map.............................................................................................................................
public class MapActivity extends AppCompatActivity implements OnMapReadyCallback {
public void onMapReady(GoogleMap googleMap) {
Toast.makeText(this, "Map is Ready", Toast.LENGTH_SHORT).show();
Log.d(TAG, "Map is Ready");
mMap = googleMap;
if (mLocationPermissionGranted)
{
getDeviceLocation();
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED)
{
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(false);
init();
}
}
private static final String TAG = "MapActivity";
private static final String FINE_LOCATION = Manifest.permission.ACCESS_FINE_LOCATION;
private static final String COARSE_LOCATION = Manifest.permission.ACCESS_COARSE_LOCATION;
private Boolean mLocationPermissionGranted = false;
private static final int LOCATON_PERMISSION_REQUEST_CODE = 1234;
private static final float DEFAULT_ZOOM= 15f;
private GoogleMap mMap;
private FusedLocationProviderClient mFusedLocationProviderClient;
private EditText mSearchText;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
mSearchText = (EditText) findViewById(R.id.input_search);
getLocationPermission();
/* MobileAds.initialize(this,"ca-app-pub-3940256099942544~3347511713");
mAdView = (AdView)findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().addTestDevice("7B0B6DDFA6EB4A71955387A3EA155884").build();
mAdView.loadAd(adRequest);*/
}
private void init()
{
Log.d(TAG,"initializing map");
mSearchText.setOnEditorActionListener(new TextView.OnEditorActionListener()
{
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event)
{
if(actionId== EditorInfo.IME_ACTION_SEARCH || actionId==EditorInfo.IME_ACTION_DONE
||actionId==KeyEvent.ACTION_DOWN || actionId== KeyEvent.KEYCODE_ENTER)
{
geoLocate();
}
return false;
}
});
}
private void geoLocate()
{
Log.d(TAG,"locating");
String searchString = mSearchText.getText().toString();
Geocoder geocoder = new Geocoder(MapActivity.this);
List<Address> list = new ArrayList<>();
try
{
list = geocoder.getFromLocationName(searchString,1);
}
catch(IOException e)
{
Log.e(TAG,"IOException"+ e.getMessage());
}
if(list.size()>0)
{
Address address = list.get(0);
Log.d(TAG,"found location" + address.toString());
// Toast.makeText(this,address.toString(),Toast.LENGTH_SHORT).show();
}
}
private void getDeviceLocation()
{
Log.d(TAG,"GetDeviceLocation");
mFusedLocationProviderClient= LocationServices.getFusedLocationProviderClient(this);
try
{
if(mLocationPermissionGranted)
{
Task location = mFusedLocationProviderClient.getLastLocation();
location.addOnCompleteListener(new OnCompleteListener()
{
#Override
public void onComplete(#NonNull Task task)
{
if(task.isSuccessful())
{
Log.d(TAG,"location found");
Location CurrentLocation = (Location) task.getResult();
moveCamera(new LatLng(CurrentLocation.getLatitude(),CurrentLocation.getLongitude()),DEFAULT_ZOOM);
}
else
{
Log.d(TAG,"location not found");
Toast.makeText(MapActivity.this,"unable to find location",Toast.LENGTH_SHORT).show();
}
}
});
}
}catch (SecurityException e)
{
Log.e(TAG,"security exception"+e.getMessage());
}
}
private void moveCamera(LatLng latlng,float zoom)
{
Log.d(TAG,"move camera to location lat:"+latlng.latitude + ",lng" + latlng.longitude);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latlng,zoom));
}
private void initMap()
{
Log.d(TAG,"initializing map");
SupportMapFragment mapFragment = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(MapActivity.this);
}
private void getLocationPermission()
{
Log.d(TAG,"Getting permission");
String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION};
if(ContextCompat.checkSelfPermission(this.getApplicationContext(),FINE_LOCATION)==PackageManager.PERMISSION_GRANTED)
{
if(ContextCompat.checkSelfPermission(this.getApplicationContext(),COARSE_LOCATION)==PackageManager.PERMISSION_GRANTED)
{
mLocationPermissionGranted = true;
initMap();
}
else
{
ActivityCompat.requestPermissions(this,permissions,LOCATON_PERMISSION_REQUEST_CODE);
}
}
else
{
ActivityCompat.requestPermissions(this,permissions,LOCATON_PERMISSION_REQUEST_CODE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults)
{
Log.d(TAG,"onRequestPermissionsResult:called");
// super.onRequestPermissionsResult(requestCode, permissions, grantResults);
mLocationPermissionGranted = false;
switch(requestCode)
{
case LOCATON_PERMISSION_REQUEST_CODE:
{
if(grantResults.length>0 )
{
for(int i = 0 ; i < grantResults.length;i++)
{
if(grantResults[i]!= PackageManager.PERMISSION_GRANTED)
{
mLocationPermissionGranted = false;
Log.d(TAG,"onRequestPermissionsResult:failed");
return;
}
}
Log.d(TAG,"onRequestPermissionsResult:granted");
mLocationPermissionGranted= true;
initMap();
}
}
}
}
}
In Android Studio
Go to Build -> Clean Project Project
It surely will work.If not restart Android Studio
Related
Getting location null. Disabled location then i opened my application, handled the permission, and intent to setting for location enable option. Re opened my application, it shows location null. Is there any way to get last know location if no other app have accessed the location before.
I have already defined ACCESS_FINE_LOCATION and ACCESS_COARSE_LOCATION
below is the code that I'm using
public class Map extends AppCompatActivity implements OnMapReadyCallback {
GoogleMap googleMap;
private static final int Request_code=101;
Location mLocation;
private MapView mMapView;
boolean mLocationPermissionGranted=false;
private FusedLocationProviderClient mFusedLocationClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
mFusedLocationClient= LocationServices.getFusedLocationProviderClient(this);
// initGoogleMap(savedInstanceState);
Bundle mapViewBundle = null;
if (savedInstanceState != null) {
mapViewBundle = savedInstanceState.getBundle(MAPVIEW_BUNDLE_KEY);
Log.d("bundle is not empty","true");
}else {
Log.d("bundle is empty","true");
}
mMapView = findViewById(R.id.service_center_map);
mMapView.onCreate(mapViewBundle);
//
mMapView.getMapAsync(this);
}
private void initGoogleMap(Bundle savedInstanceState){
}
public boolean isServicesOK(){
Log.d("map", "isServicesOK: checking google services version");
int available = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(this);
if(available == ConnectionResult.SUCCESS){
//everything is fine and the user can make map requests
Log.d("map", "isServicesOK: Google Play Services is working");
return true;
}
else if(GoogleApiAvailability.getInstance().isUserResolvableError(available)){
//an error occured but we can resolve it
Log.d("map", "isServicesOK: an error occured but we can fix it");
Dialog dialog = GoogleApiAvailability.getInstance().getErrorDialog(this, available, ERROR_DIALOG_REQUEST);
dialog.show();
}else{
Toast.makeText(this, "You can't make map requests", Toast.LENGTH_SHORT).show();
}
return false;
}
private void buildAlertMessageNoGps() {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("This application requires GPS to work properly, do you want to enable it?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(#SuppressWarnings("unused") final DialogInterface dialog, #SuppressWarnings("unused") final int id) {
Intent enableGpsIntent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivityForResult(enableGpsIntent, PERMISSION_REQUEST_ENABLE_GPS);
}
});
final AlertDialog alert = builder.create();
alert.show();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Bundle mapViewBundle = outState.getBundle(MAPVIEW_BUNDLE_KEY);
if (mapViewBundle == null) {
mapViewBundle = new Bundle();
outState.putBundle(MAPVIEW_BUNDLE_KEY, mapViewBundle);
}
mMapView.onSaveInstanceState(mapViewBundle);
}
private void getLocationPermission() {
/*
* Request location permission, so that we can get the location of the
* device. The result of the permission request is handled by a callback,
* onRequestPermissionsResult.
*/
if (ContextCompat.checkSelfPermission(this.getApplicationContext(),
android.Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
mLocationPermissionGranted = true;
getLastKnowLocation();
} else {
ActivityCompat.requestPermissions(this,
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
}
}
private void getLastKnowLocation(){
Log.d("location","last location");
if(ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION)!=PackageManager.PERMISSION_GRANTED){
return;
}
mFusedLocationClient.getLastLocation().addOnCompleteListener(new OnCompleteListener<Location>() {
#Override
public void onComplete(#NonNull Task<Location> task) {
if(task.isSuccessful()){
Location location=task.getResult();
Log.d("lat",String.valueOf(location.getLatitude()));
}else {
Log.d("Failed","");
}
}
});
}
public boolean isMapsEnabled(){
final LocationManager manager = (LocationManager) getSystemService( Context.LOCATION_SERVICE );
if ( !manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) {
buildAlertMessageNoGps();
Log.d("gps","permission false");
return false;
}
Log.d("gps","permission true");
return true;
}
private boolean checkMapServices(){
if(isServicesOK()){
if(isMapsEnabled()){
return true;
}
}
return false;
}
#Override
protected void onResume() {
super.onResume();
if (checkMapServices()) {
if (mLocationPermissionGranted) {
getLastKnowLocation();
} else {
getLocationPermission();
}
}
}
#Override
public void onStop() {
super.onStop();
mMapView.onStop();
}
#Override
public void onStart() {
super.onStart();
mMapView.onStart();
}
#Override
public void onMapReady(GoogleMap map) {
this.googleMap=map;
googleMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
if(ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_COARSE_LOCATION)
!=PackageManager.PERMISSION_GRANTED){
return;
}
LatLng bhaktapur=new LatLng(27.67352,85.3877);
LatLng Imadol=new LatLng(27.66193,85.34179);
googleMap.addMarker(new MarkerOptions().position(bhaktapur).title("GarageInc, Bhaktapur"));
googleMap.addMarker(new MarkerOptions().position(Imadol).title("GarageInc, Imadol"));
googleMap.setMyLocationEnabled(true);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.d("map", "onActivityResult: called.");
switch (requestCode) {
case PERMISSION_REQUEST_ENABLE_GPS: {
if(mLocationPermissionGranted){
getLastKnowLocation();
}
else{
getLocationPermission();
}
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
#NonNull String permissions[],
#NonNull int[] grantResults) {
mLocationPermissionGranted = false;
switch (requestCode) {
case PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
mLocationPermissionGranted = true;
}
}
}
}
#Override
public void onDestroy() {
mMapView.onDestroy();
super.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mMapView.onLowMemory();
}
}
I have implemented location using FusedLocationProviderClient. The problem in my app is that the permission dialog does not switch on the location in settings. I have to manually turn it on before I start getting updates.
I have checked and requested permission using ContextCompat and ActivityCompat classes but nothing happens until I manually press the button. Is this a bug with FusedLocationProviderClient or bad programming on my side? I have worked with location manager and Fused Location Provider APIs and never faced this before.
Here's my code:
public class HomeFragment extends BaseFragment implements OnMapReadyCallback {
private static final String TAG = HomeFragment.class.getSimpleName();
private Toolbar toolbar;
private TextView driverStatusTV;
public static MaterialAnimatedSwitch statusSwitch;
private FusedLocationProviderClient providerClient;
public static Location mLastLocation;
public static LocationRequest locationRequest;
public GoogleMap mGmap;
public static Marker currentMarker;
public static double latitude = 0f, longitude = 0f;
private static boolean isLocationGranted = false;
public static final int UPDATE_INTERVAL = 15000;
public static final int FASTEST_INTERVAL = 8000;
public static final int DISPLACEMENT = 10;
public static final int PLAY_SERVICES_REQ_CODE = 9009;
public static final int PLAY_SERVICES_RESOLUTION_REQ_CODE = 9090;
private SupportMapFragment mapFragment;
public HomeFragment() {
// Required empty public constructor
}
private void initViews(View view) {
toolbar = view.findViewById(R.id.toolbar);
driverStatusTV = view.findViewById(R.id.driverStatusTV);
statusSwitch = view.findViewById(R.id.statusSwitch);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, container, false);
initViews(view);
((AppCompatActivity) getActivity()).setSupportActionBar(toolbar);
checkPerms();
providerClient = LocationServices.getFusedLocationProviderClient(getActivity());
mapFragment = (SupportMapFragment) this.getChildFragmentManager().findFragmentById(R.id.mapFragment);
mapFragment.getMapAsync(this);
driverStatusTV.setText("OFFLINE");
statusSwitch.setOnCheckedChangeListener(new MaterialAnimatedSwitch.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(boolean b) {
if (b) {
Snackbar.make(getActivity().findViewById(android.R.id.content), "You are Now Online", Snackbar.LENGTH_LONG).show();
if (checkPerms()) {
startLocationListener();
driverStatusTV.setText("ONLINE");
}
} else {
Snackbar.make(getActivity().findViewById(android.R.id.content), "You are Now Offline", Snackbar.LENGTH_LONG).show();
mGmap.setIndoorEnabled(false);
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mGmap.setMyLocationEnabled(false);
stopLocationListener();
driverStatusTV.setText("OFFLINE");
if (currentMarker != null){
currentMarker.remove();
}
}
}
});
return view;
}
private void stopLocationListener() {
if (providerClient != null){
providerClient.removeLocationUpdates(locationCallback);
}
}
#Override
public void onPause() {
super.onPause();
stopLocationListener();
}
private void startLocationListener() {
locationRequest = LocationRequest.create();
locationRequest.setSmallestDisplacement(DISPLACEMENT);
locationRequest.setFastestInterval(FASTEST_INTERVAL);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(UPDATE_INTERVAL);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
builder.addLocationRequest(locationRequest);
LocationSettingsRequest settingsRequest = builder.build();
SettingsClient client = LocationServices.getSettingsClient(getActivity());
client.checkLocationSettings(settingsRequest);
displayLocation();
}
private boolean checkPerms() {
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
reqPerms();
isLocationGranted = false;
Log.d(TAG, "Permission Value:\t" + isLocationGranted);
} else {
isLocationGranted = true;
Log.d(TAG, "Permission Value:\t" + isLocationGranted);
}
return isLocationGranted;
}
private void reqPerms() {
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, AppConstants.LOC_PERM_CODE);
}
private void displayLocation() {
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
reqPerms();
} else {
if (statusSwitch.isChecked()) {
providerClient.requestLocationUpdates(locationRequest, locationCallback, Looper.myLooper());
mGmap.setIndoorEnabled(true);
mGmap.setMyLocationEnabled(true);
} else {
mGmap.setIndoorEnabled(false);
mGmap.setMyLocationEnabled(false);
}
}
}
private LocationCallback locationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
Location location = locationResult.getLastLocation();
mLastLocation = location;
if (currentMarker != null) {
currentMarker.remove();
}
latitude = mLastLocation.getLatitude();
Log.d(TAG, "Lat:\t" + latitude);
longitude = mLastLocation.getLongitude();
Log.d(TAG, "Long:\t" + longitude);
MarkerOptions options = new MarkerOptions();
options.position(new LatLng(latitude, longitude));
options.title("Driver");
//options.icon(BitmapDescriptorFactory.fromResource(R.drawable.car)); // throws error
currentMarker = mGmap.addMarker(options);
rotateMarker(currentMarker, 360, mGmap);
mGmap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude,longitude), 18.0f));
}
};
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case AppConstants.LOC_PERM_CODE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
isLocationGranted = true;
if (checkPlayServices() && statusSwitch.isChecked()) {
startLocationListener();
} else {
Snackbar.make(getActivity().findViewById(android.R.id.content), "Google Play Services Not Supported on Your Device", Snackbar.LENGTH_LONG).show();
}
}
break;
}
}
public boolean checkPlayServices() {
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity());
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
GooglePlayServicesUtil.getErrorDialog(resultCode, getActivity(), AppConstants.PLAY_SERVICES_RESOLUTION_REQUEST).show();
} else {
Snackbar.make(getActivity().findViewById(android.R.id.content), "Play Services NOT Supported on Your Device", Snackbar.LENGTH_LONG).show();
getActivity().finish();
getActivity().moveTaskToBack(true);
}
return false;
}
return true;
}
private void rotateMarker(final Marker currentMarker, final float i, GoogleMap mGmap) {
final Handler handler = new Handler();
final long start = SystemClock.uptimeMillis();
final float startRotation = currentMarker.getRotation();
final int duration = 1500;
final Interpolator interpolator = new LinearInterpolator();
handler.postDelayed(new Runnable() {
#Override
public void run() {
long elapsed = SystemClock.elapsedRealtime() - start;
float t = interpolator.getInterpolation(elapsed / duration);
float rot = t * i + (1 - t) * startRotation;
currentMarker.setRotation(-rot > 180 ? rot / 2 : rot);
if (t < 1.0) {
handler.postDelayed(this, 16);
}
}
}, duration);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mGmap = googleMap;
startLocationListener();
}
}
Alos, the set icon on marker throws this error com.google.maps.api.android.lib6.common.apiexception.b: Failed to decode image. The provided image must be a Bitmap.
Can anyone help me solve these two problems? Thank you
your onRequestPermissionsResult will never be called, you are requesting permissions from your activity and your activity's onRequestPermissionsResult would be getting invoked. If you want permission callback in your fragment just remove Activity when you request permssions
private void reqPerms() {
requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, AppConstants.LOC_PERM_CODE);
}
Your fragment has to be a supportFragment if you want to access this method
I am trying to get current location using FusedLocationAPI in my application. It works just fine in both android API>23 and <23. The issue is in case of GPS is not enabled, the app prompts the user to enable the GPS and after that the location returns null. But while restarting the app, it works just fine. In case of GPS not being turned OFF, the app just works fine. Is there any way that the app can wait for the GPS to be enabled before getting the location? below I am posting my code. Please have a look.
Inside onCreate():
manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
statusOfGPS = manager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!statusOfGPS) {
displayPromptForEnablingGPS(this);
}
Log.d("permipart", "before");
if(CheckingPermissionIsEnabledOrNot())
{
Toast.makeText(MainActivity.this, "All Permissions Granted Successfully", Toast.LENGTH_LONG).show();
}
else {
RequestMultiplePermission();
}
if(Build.VERSION.SDK_INT<= 23)
{
buildGoogleApiClient();
if (!mGoogleApiClient.isConnected()) {
mGoogleApiClient.connect();
}
}
Log.d("permipart", "out");
Other methods:
#Override
public void onLocationChanged(Location location) {
Log.d("onconnectedlocchange","called");
if (location != null) {
lat = location.getLatitude();
lon = location.getLongitude();
if (!String.valueOf(lat).equals("0.0"))
{
latitudeVal = location.getLatitude();
longitudeVal = location.getLongitude();
Log.e("Lat and Lng", String.valueOf(latitudeVal) + longitudeVal);
}
}
}
#Override
public void onConnected(#Nullable Bundle bundle) {
if(CheckingPermissionIsEnabledOrNot())
{
Toast.makeText(MainActivity.this, "All Permissions Granted Successfully", Toast.LENGTH_LONG).show();
}
// If, If permission is not enabled then else condition will execute.
else {
//Calling method to enable permission.
RequestMultiplePermission();
}
Log.d("onconnected","called");
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
// Update location every second
if (ActivityCompat.checkSelfPermission(this, ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
}
else
{
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (mLastLocation != null) {
lat = mLastLocation.getLatitude();
lon = mLastLocation.getLongitude();
if (!String.valueOf(lat).equals("0.0")){
latitudeVal = mLastLocation.getLatitude();
longitudeVal = mLastLocation.getLongitude();
Log.e("Lat and Lng", String.valueOf(latitudeVal)+ longitudeVal);
}
}
}
}
#Override
public void onConnectionSuspended(int i) {
}
synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
public void displayPromptForEnablingGPS(final Activity activity) {
final android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(activity);
final String action = Settings.ACTION_LOCATION_SOURCE_SETTINGS;
final String message = "Do you want open GPS setting?";
builder.setMessage(message)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface d, int id) {
activity.startActivity(new Intent(action));
d.dismiss();
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface d, int id) {
d.cancel();
}
});
builder.create().show();
}
String[] permissions = new String[]{ACCESS_FINE_LOCATION,
ACCESS_COARSE_LOCATION, READ_EXTERNAL_STORAGE, WRITE_EXTERNAL_STORAGE };
//Permission function starts from here
private void RequestMultiplePermission() {
// Creating String Array with Permissions.
Log.d("permipart", "RequestMultiplePermission");
ActivityCompat.requestPermissions(MainActivity.this, new String[]
{
READ_EXTERNAL_STORAGE,
WRITE_EXTERNAL_STORAGE,
ACCESS_FINE_LOCATION,
ACCESS_COARSE_LOCATION
}, RequestPermissionCode);
}
private boolean checkPermission() {
int result;
List<String> listPermissionsNeeded = new ArrayList<>();
for (String p:permissions) {
result = ContextCompat.checkSelfPermission(this,p);
if (result != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(p);
}
}
if (!listPermissionsNeeded.isEmpty()) {
ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]),10 );
Log.d("permissionissue","no");
return false;
}
Log.d("permissionissue","yes");
return true;
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
Log.d("permipart", "onRequestPermissionsResult");
switch (requestCode) {
case RequestPermissionCode:
if (grantResults.length > 0) {
boolean CameraPermission = grantResults[0] == PackageManager.PERMISSION_GRANTED;
boolean RecordAudioPermission = grantResults[1] == PackageManager.PERMISSION_GRANTED;
boolean SendSMSPermission = grantResults[2] == PackageManager.PERMISSION_GRANTED;
boolean GetAccountsPermission = grantResults[3] == PackageManager.PERMISSION_GRANTED;
if (CameraPermission && RecordAudioPermission && SendSMSPermission && GetAccountsPermission) {
Log.d("permipart", "done");
buildGoogleApiClient();
Toast.makeText(MainActivity.this, "Permission Granted", Toast.LENGTH_LONG).show();
if (!mGoogleApiClient.isConnected()) {
mGoogleApiClient.connect();
}
}
else {
Toast.makeText(MainActivity.this,"Permission Denied",Toast.LENGTH_LONG).show();
}
}
break;
}
}
/**
* Checking permission is enabled or not using function starts from here.
*
*/
public boolean CheckingPermissionIsEnabledOrNot() {
int FirstPermissionResult = ContextCompat.checkSelfPermission(getApplicationContext(), READ_EXTERNAL_STORAGE);
int SecondPermissionResult = ContextCompat.checkSelfPermission(getApplicationContext(), WRITE_EXTERNAL_STORAGE);
int ThirdPermissionResult = ContextCompat.checkSelfPermission(getApplicationContext(), ACCESS_FINE_LOCATION);
int ForthPermissionResult = ContextCompat.checkSelfPermission(getApplicationContext(), ACCESS_COARSE_LOCATION);
return FirstPermissionResult == PackageManager.PERMISSION_GRANTED &&
SecondPermissionResult == PackageManager.PERMISSION_GRANTED &&
ThirdPermissionResult == PackageManager.PERMISSION_GRANTED &&
ForthPermissionResult == PackageManager.PERMISSION_GRANTED ;
}
You need to recieve the broadcast of the GPS status something like this:
public class GpsLocationReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().matches("android.location.PROVIDERS_CHANGED")) {
// here you can get the location or start a service to get it.
// example
// Intent getLocationService = new Intent(context,YourService.class);
// context.startService(getLocationService);
}
}
}
update
according to comment below
use this in your code
manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if(manager.isProviderEnabled( LocationManager.GPS_PROVIDER)){
// it is enabled
}else{
// it is not
}
Use my code, it will ask the user to turn on GPS if it is turned off. It will never return you anything until GPS turned on.
Note: you have to get location permission before using it for marshmallow and above mobiles.
Try this:
#SuppressWarnings("MissingPermission")
public class LocationFinder implements LocationListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
public static final String TAG = "LocationFinder";
private static final String BROADCAST_GPS_REQ = "LocationFinder.GPS_REQ";
private static final String KEY_GPS_REQ = "key.gps.req";
private static final int GPS_REQUEST = 2301;
private Activity activity;
private FinderType finderType;
private GoogleApiClient googleApiClient;
private LocationRequest locationRequest;
private long updateInterval;
private long fastestInterval;
private GpsRequestListener gpsRequestListener;
private LocationUpdateListener locationUpdateListener;
public LocationFinder(Activity activity, FinderType finderType) {
this.activity = activity;
this.finderType = finderType;
}
private void connectGoogleApiClient() {
googleApiClient = new GoogleApiClient.Builder(activity)
.addApi(LocationServices.API).addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).build();
googleApiClient.connect();
}
private void createLocationRequest() {
locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(updateInterval);
locationRequest.setFastestInterval(fastestInterval);
}
private BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
int intExtra = intent.getIntExtra(KEY_GPS_REQ, 0);
switch (intExtra) {
case Activity.RESULT_OK:
try {
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, LocationFinder.this);
} catch (Exception e) {
e.printStackTrace();
}
gpsRequestListener.gpsTurnedOn();
break;
case Activity.RESULT_CANCELED:
gpsRequestListener.gpsNotTurnedOn();
}
}
};
public void gpsRequestCallback(GpsRequestListener gpsRequestListener) {
this.gpsRequestListener = gpsRequestListener;
LocalBroadcastManager.getInstance(activity).registerReceiver(receiver, new IntentFilter(BROADCAST_GPS_REQ));
}
public void config(long updateInterval, long fastestInterval) {
this.updateInterval = updateInterval;
this.fastestInterval = fastestInterval;
}
public void find(LocationUpdateListener listener) {
this.locationUpdateListener = listener;
createLocationRequest();
connectGoogleApiClient();
}
private void find() {
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(locationRequest);
builder.setAlwaysShow(true);
PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings(googleApiClient, builder.build());
result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
#Override
public void onResult(#NonNull LocationSettingsResult locationSettingsResult) {
Status status = locationSettingsResult.getStatus();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, LocationFinder.this);
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
try {
status.startResolutionForResult(activity, GPS_REQUEST);
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
Log.d(TAG, "No GPS Hardware");
break;
}
}
});
}
public void stopFinder() {
if (googleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this);
googleApiClient.disconnect();
}
try {
activity.unregisterReceiver(receiver);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onConnected(#Nullable Bundle bundle) {
Log.d(TAG, "GoogleApiClient: Connected");
find();
}
#Override
public void onConnectionSuspended(int i) {
Log.d(TAG, "GoogleApiClient: onConnectionSuspended");
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Log.d(TAG, "GoogleApiClient: onConnectionFailed");
}
#Override
public void onLocationChanged(Location location) {
if (finderType != FinderType.TRACK)
stopFinder();
locationUpdateListener.onLocationUpdate(new LatLng(location.getLatitude(), location.getLongitude()));
}
public void setGpsRequestListener(GpsRequestListener gpsRequestListener) {
this.gpsRequestListener = gpsRequestListener;
}
public static void onRequestResult(Activity activity, int requestCode, int resultCode) {
if (requestCode == GPS_REQUEST) {
Intent intent = new Intent(BROADCAST_GPS_REQ);
intent.putExtra(KEY_GPS_REQ, resultCode);
LocalBroadcastManager.getInstance(activity).sendBroadcast(intent);
}
}
public enum FinderType {
// It will update the current GPS location once.
GPS,
//It will update the user location continuously.
TRACK
}
public interface LocationUpdateListener {
void onLocationUpdate(LatLng latLng);
}
public interface GpsRequestListener {
void gpsTurnedOn();
void gpsNotTurnedOn();
}
}
To get location update initialize the class like this:
public class MyActivity extends AppCompatActivity implements
LocationFinder.GpsRequestListener,
LocationFinder.LocationUpdateListener {
private LocationFinder locationUpdater;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
locationUpdater = new LocationFinder(this, LocationFinder.FinderType.TRACK);
driverLocationUpdater.gpsRequestCallback(this);
driverLocationUpdater.config(5000, 5000);
driverLocationUpdater.find(this);
}
#Override
protected void onDestroy(){
super.onDestroy()
driverLocationUpdater.stopFinder();
}
#Override
public void onLocationUpdate(LatLng latLng) {
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
LocationFinder.onRequestResult(this, requestCode, resultCode);
}
}
I'm trying to get the current location icon on top of the map. However when i run the app the map looks;
The other case is when i wrote this line;
mGoogleMap.setMyLocationEnabled(true);
I could't get any 'Add Permission Check' warning like;
. So i wrote these permissions by hand.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
if (checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
}
I don't know its right way to do that or not. Here is my full code;
private Activity activity = this;
ActionBarDrawerToggle drawerToggle;
DrawerLayout drawerLayout;
RecyclerView recyclerMenu;
AdapterMenu obAdapter;
private Tracker mTracker;
GoogleMap mGoogleMap;
GoogleApiClient mGoogleApiClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_harita);
if (googleServicesAvailable()) {
initmap();
} else {
//No google maps layout
}
}
public boolean googleServicesAvailable() {
GoogleApiAvailability api = GoogleApiAvailability.getInstance();
int isAvailable = api.isGooglePlayServicesAvailable(this);
if (isAvailable == ConnectionResult.SUCCESS)
return true;
else if (api.isUserResolvableError(isAvailable)) {
Dialog dialog = api.getErrorDialog(this, isAvailable, 0);
dialog.show();
} else
Toast.makeText(this, "Can't connect to play services", Toast.LENGTH_LONG).show();
return false;
}
private void initmap() {
MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.fragment);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
if (checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
}
mGoogleMap.setMyLocationEnabled(true);
}
public void geoLocate(View view) throws IOException {
EditText searchtext = (EditText) findViewById(R.id.editAra);
String location = searchtext.getText().toString();
Geocoder geocoder = new Geocoder(this);
List<Address> list = geocoder.getFromLocationName(location, 1);
Address address = list.get(0);
String locality = address.getLocality();
Toast.makeText(this, locality, Toast.LENGTH_LONG).show();
double latitude = address.getLatitude();
double longitude = address.getLongitude();
goToLocationZoom(latitude, longitude, 15);
}
private void goToLocationZoom(double latitude, double longitude, float zoom) {
LatLng LatLang = new LatLng(latitude, longitude);
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(LatLang, zoom);
mGoogleMap.moveCamera(update);
}
}
If user has not granted for location permissions, you should request for it explicitly (Only required for Android M and above). Then you should override onRequestPermissionsResult and manage the results.
Here you have a working example for you are asking for:
public class MainActivity extends FragmentActivity implements OnMapReadyCallback {
private static final String[] LOCATION_PERMISSIONS = {
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION
};
private static final int LOCATION_PERMISSIONS_REQUEST_CODE = 1;
private GoogleMap mGoogleMap;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public void onMapReady(final GoogleMap googleMap) {
this.mGoogleMap = googleMap;
if (hasGrantedLocationPermissions()) {
showCurrentLocationMapControl();
} else {
requestForLocationPermissions();
}
}
#Override
public void onRequestPermissionsResult(final int requestCode, final #NonNull String[] permissions, final #NonNull int[] grantResults) {
if (requestCode == LOCATION_PERMISSIONS_REQUEST_CODE) {
if (grantResults.length == LOCATION_PERMISSIONS.length) {
for (final int grantResult : grantResults) {
if (PackageManager.PERMISSION_GRANTED != grantResult) {
return;
}
}
showCurrentLocationMapControl();
}
}
}
private boolean hasGrantedLocationPermissions() {
return ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED;
}
private void requestForLocationPermissions() {
ActivityCompat.requestPermissions(this, LOCATION_PERMISSIONS, LOCATION_PERMISSIONS_REQUEST_CODE);
}
private void showCurrentLocationMapControl() {
if (null != this.mGoogleMap) {
this.mGoogleMap.setMyLocationEnabled(true);
}
}
}
Do not forget to define needed permissions in manifest file:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
In my app I want to fetch Latitude, Longitude and current Location name and pass this value in the database. The app is running perfectly in Tab. But in case of other device getLastKnownLocation() returns null. For this reason I am facing nullpointerexception.
private Location getLastKnownLocation() {
locationmanager = (LocationManager) getApplicationContext().getSystemService(LOCATION_SERVICE);
List<String> providers = locationmanager.getProviders(true);
Location bestLocation = null;
for (String provider : providers) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return null;
}
Location l = locationmanager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
if (l == null) {
continue;
}
if (bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy()) {
// Found best last known location: %s", l);
bestLocation = l;
}
}
return bestLocation;
}
Please help me to solve this. I know this issue is asked before. But I have tried most of them. Still I am facing the nullpointerexception in the same place(while fetching lat long value).
10-13 15:54:12.825 16095-16095/com.example.ivdisplays.vehereapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.ivdisplays.vehereapp, PID: 16095
java.lang.NullPointerException
at com.example.ivdisplays.vehereapp.MainActivity$1.onClick(MainActivity.java:117)
at android.view.View.performClick(View.java:4463)
at android.view.View$PerformClick.run(View.java:18792)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5344)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:676)
at dalvik.system.NativeStart.main(Native Method)
public class MainActivity extends AppCompatActivity implements NetworkCallback,
LocationListener {
private EditText empIdTxt;
private EditText passwordTxt;
private TextView tv_lat;
private TextView tv_long;
private TextView tv_place;
private Button loginBtn;
private Button logoutBtn;
LocationManager locationmanager;
GPSTracker gps;
String cityName = "";
Context context;
static String loginDate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
empIdTxt = (EditText) findViewById(R.id.et_loginId);
passwordTxt = (EditText) findViewById(R.id.et_loginPass);
loginBtn = (Button) findViewById(R.id.bt_login);
logoutBtn= (Button) findViewById(R.id.bt_logout);
empIdTxt.addTextChangedListener(new MyTextWatcher(empIdTxt));
passwordTxt.addTextChangedListener(new MyTextWatcher(passwordTxt));
empIdTxt.setText("vinay");
passwordTxt.setText("qwerty");
context=MainActivity.this;
final Location location = getLastKnownLocation();
if (location != null) {
onLocationChanged(location);
} else {
Toast.makeText(getApplicationContext(), "location not found", Toast.LENGTH_LONG).show();
System.out.println("Output of Location is:" + getLastKnownLocation());
}
loginDate = AlertDialogManager.todayDate();
loginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!validateEmpID()) {
return;
}
if (!validatePassword()) {
return;
}
LoginApi api = new LoginApi(context, (NetworkCallback) context);
System.out.println("Output of LoginAPI:" +"username" +empIdTxt.getText().toString()
+"password"+passwordTxt.getText().toString()+"Lat"+location.getLatitude()+"Long"+location.getLongitude()
+"Date"+loginDate+"Locality"+new GPSTracker(MainActivity.this).getLocality(location));
api.processLogin(empIdTxt.getText().toString(), passwordTxt.getText().toString(),
location.getLatitude()+"",location.getLongitude()+"",loginDate,
new GPSTracker(MainActivity.this).getLocality(location),"123456");
loginBtn.setVisibility(View.GONE);
logoutBtn.setVisibility(View.VISIBLE);
}
});
logoutBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
LogoutApi api = new LogoutApi(context, (NetworkCallback) context);
System.out.println("Output of LogoutAPI:" +"userid " +AppDelegate.getInstance().uid
+"Lat"+location.getLatitude()+"Long"+location.getLongitude()
+"Date"+AlertDialogManager.todayDate()+"Locality"+new GPSTracker(MainActivity.this).getLocality(location));
api.processLogout(AppDelegate.getInstance().uid,
location.getLatitude()+"",location.getLongitude()+"",AlertDialogManager.todayDate(),
new GPSTracker(MainActivity.this).getLocality(location),"123456","");
logoutBtn.setVisibility(View.GONE);
loginBtn.setVisibility(View.VISIBLE);
}
});
}
private Location getLastKnownLocation() {
locationmanager = (LocationManager) getApplicationContext().getSystemService(LOCATION_SERVICE);
List<String> providers = locationmanager.getProviders(true);
Location bestLocation = null;
for (String provider : providers) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return null;
}
Location l = locationmanager.getLastKnownLocation(provider);
if (l == null) {
continue;
}
if (bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy()) {
// Found best last known location: %s", l);
bestLocation = l;
}
}
return bestLocation;
}
private void requestFocus(View view) {
if (view.requestFocus()) {
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}
}
private boolean validateEmpID() {
if (empIdTxt.getText().toString().trim().isEmpty()) {
empIdTxt.setError(ErrorUtil.USERNAME_ERROR);
requestFocus(empIdTxt);
return false;
}
return true;
}
private boolean validatePassword() {
if (passwordTxt.getText().toString().trim().isEmpty()) {
passwordTxt.setError(ErrorUtil.PASSWORD_ERROR);
requestFocus(passwordTxt);
return false;
}
return true;
}
private class MyTextWatcher implements TextWatcher {
private View view;
private MyTextWatcher(View view) {
this.view = view;
}
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
public void afterTextChanged(Editable editable) {
switch (view.getId()) {
case R.id.et_loginId:
validateEmpID();
break;
case R.id.et_loginPass:
validatePassword();
break;
}
}
}
#Override
public void updateScreen(String data, String tag) {
if (tag.compareTo(ApiUtil.TAG_LOGIN) == 0) {
try {
System.out.println("Login Response"+data);
JSONObject mainObj = new JSONObject(data);
AppDelegate ctrl = AppDelegate.getInstance();
if (!mainObj.isNull("user_id")) {
ctrl.uid = mainObj.getString("user_id");
}
if (!mainObj.isNull("error")) {
Toast.makeText(MainActivity.this,"Login Fails",Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this,"Login Success",Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
Toast.makeText(MainActivity.this,"Seems there is an issue please try again later",Toast.LENGTH_SHORT).show();
}
}
if (tag.compareTo(ApiUtil.TAG_LOGOUT) == 0) {
try {
System.out.println("Logout Response"+data);
JSONObject mainObj = new JSONObject(data);
AppDelegate ctrl = AppDelegate.getInstance();
if (!mainObj.isNull("message")) {
Toast.makeText(MainActivity.this,"Logout Success",Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this,"Logout Fails",Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
Toast.makeText(MainActivity.this,"Seems there is an issue please try again later",Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onLocationChanged(Location location) {
double latitude,longitude;
tv_lat = (TextView) findViewById(R.id.tv_lat);
tv_long = (TextView) findViewById(R.id.tv_long);
tv_place = (TextView) findViewById(R.id.tv_place);
latitude=location.getLatitude();
longitude=location.getLongitude();
tv_lat.setText("Latitude : "+latitude);
tv_long.setText("Longitude : "+ longitude);
// create class object
gps = new GPSTracker(MainActivity.this);
// check if GPS enabled
if (gps.canGetLocation()) {
Geocoder geocoder = new Geocoder(MainActivity.this, Locale.getDefault());
List<Address> addresses;
try {
addresses = geocoder.getFromLocation(latitude,
longitude, 1);
System.out.println("Output of Address" + addresses);
cityName = addresses.get(0).getAddressLine(0);
System.out.println("Cityname is" + cityName);
tv_place.setText("Place : "+cityName);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
gps.showSettingsAlert();
}
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
}
I think the problem is about checking permissions and && != operands. Handle it more carefully.
Try this:
private Location getLastKnownLocation() {
locationmanager = (LocationManager) getApplicationContext().getSystemService(LOCATION_SERVICE);
boolean permissionsActivated = canAll();
if (!permissionsActivated)
return null;
List<String> providers = locationmanager.getProviders(true);
Location bestLocation = null;
for (String provider : providers) {
Location l = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);// this may lead to 'null' value if not permissions
if (l == null) {
continue;
}
if (bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy()) {
// Found best last known location: %s", l);
bestLocation = l;
}
}
return bestLocation;
}
private boolean canAll() {
// TODO Auto-generated method stub
return (canAccessLocation() && canCoarseLocation());
}
private boolean canAccessLocation() {
return hasPermission(android.Manifest.permission.ACCESS_FINE_LOCATION);
}
private boolean canCoarseLocation() {
return hasPermission(android.Manifest.permission.ACCESS_COARSE_LOCATION);
}
#SuppressLint("NewApi")
private boolean hasPermission(String perm) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
return (PackageManager.PERMISSION_GRANTED == checkSelfPermission(perm));
} else {
return true;
}
}
Do not forget:
getLastKnownLocation may return a null value if the application has not detected any location.
You can use GoogleApiClient's fused location provider for fetching location. You need to add a dependency in your gradle file. i.e
compile 'com.google.android.gms:play-services-location:9.6.1'
Add fine_location permission needed in manifest
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
It is a Dangerous Permission you need to ask permission at runtime like this.
Code Snippet
public class DashboardActivity extends AppCompatActivity implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener,
ResultCallback<LocationSettingsResult> {
private GoogleApiClient googleApiClient;
private GoogleApiAvailability apiAvailability;
private static final long MIN_TIME_BW_UPDATES = 10000;
private static final long FAST_TIME_BW_UPDATES = 3000;
private final static int REQUEST_CHECK_SETTINGS = 100;
private static final long EXPIRATION_DURATION = 3600000;
protected LocationRequest mLocationRequest;
protected LocationSettingsRequest mLocationSettingsRequest;
private Location location;
private LatLng latLng = new LatLng(0, 0);
private double latitude;
private double longitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
init();
}
private void init() {
apiAvailability = GoogleApiAvailability.getInstance();
if (googleApiAvaibility()) {
buildGoogleApiClient();
displayLocation();
}
}
protected void createLocationRequest() {
mLocationRequest = LocationRequest.create();
mLocationRequest.setInterval(MIN_TIME_BW_UPDATES);
mLocationRequest.setFastestInterval(FAST_TIME_BW_UPDATES);
mLocationRequest.setSmallestDisplacement(10);
mLocationRequest.setExpirationDuration(EXPIRATION_DURATION);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
builder.addLocationRequest(mLocationRequest);
builder.setAlwaysShow(true);
mLocationSettingsRequest = builder.build();
}
protected synchronized void buildGoogleApiClient() {
googleApiClient = new GoogleApiClient.Builder(getApplicationContext())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
private boolean googleApiAvaibility() {
int resultCode = apiAvailability.isGooglePlayServicesAvailable(this);
switch (resultCode) {
case ConnectionResult.SUCCESS:
return true;
case ConnectionResult.API_UNAVAILABLE:
Dialog dialog = apiAvailability.getErrorDialog(this, ConnectionResult.API_UNAVAILABLE, 200,
new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
//finish();
}
});
dialog.show();
break;
case ConnectionResult.SERVICE_MISSING:
Dialog dialog1 = apiAvailability.getErrorDialog(this, ConnectionResult.SERVICE_MISSING, 201,
new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
//finish();
}
});
dialog1.show();
break;
}
return false;
}
#Override
public void onLocationChanged(Location location) {
latLng = new LatLng(location.getLatitude(), location.getLongitude());
//here you will get new latitude and longitude if location is changed
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQUEST_CHECK_SETTINGS:
switch (resultCode) {
case Activity.RESULT_OK:
displayLocation();
break;
case Activity.RESULT_CANCELED:
//finish();
Toast.makeText(getActivity(), "Please enable location. Otherwise you can not use this application", Toast.LENGTH_LONG).show();
break;
}
break;
default:
break;
}
}
#Override
public void onConnected(#Nullable Bundle bundle) {
createLocationRequest();
checkLocationSettings();
}
#Override
public void onConnectionSuspended(int i) {
googleApiClient.connect();
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
googleApiClient.connect();
}
#Override
public void onResult(#NonNull LocationSettingsResult result) {
Status status = result.getStatus();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
displayLocation();
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
try {
status.startResolutionForResult(this, REQUEST_CHECK_SETTINGS);
} catch (IntentSender.SendIntentException e) {
Log.e("Exception", e.toString());
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
//showDialog(this,"You have choose never for Location!");
break;
default:
break;
}
}
protected void checkLocationSettings() {
PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.
checkLocationSettings(googleApiClient, mLocationSettingsRequest);
result.setResultCallback(this);
}
private void displayLocation() {
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 250);
} else {
location = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
if (location != null) {
latLng = new LatLng(location.getLatitude(), location.getLongitude());
latitude = location.getLatitude();
longitude = location.getLongitude();
//print latitude longitude here
} else {
if (googleApiAvaibility()) {
buildGoogleApiClient();
googleApiClient.connect();
if (googleApiClient.isConnected()) {
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, mLocationRequest, this);
}
}
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (permissions[0].equals(Manifest.permission.ACCESS_FINE_LOCATION)) {
if (location != null) {
displayLocation();
} else {
//googleApiClient.connect();
if (googleApiAvaibility()) {
buildGoogleApiClient();
googleApiClient.connect();
}
}
}
}
}
}
You can also check this sample