onInfoWindowClick doesn't do anything - java

When I click my onInfoWindowClick nothing is happening? I cant really find my issue.
Here is some of my functions. The Alert works very well if i just post it in onResume(), so i must me the onInfoWindowClick.
public class map extends Fragment implements
OnMapReadyCallback,
GoogleMap.OnInfoWindowClickListener {
private static final String TAG = "map";
private boolean mLocationPermissionGranted = false; //Used to ask permission to locations on the device
private MapView mMapView;
private FirebaseFirestore mDb;
private FusedLocationProviderClient mfusedLocationClient;
private UserLocation mUserLocation;
private ArrayList<UserLocation> mUserLocations = new ArrayList<>();
private GoogleMap mGoogleMap;
private LatLngBounds mMapBoundary;
private UserLocation mUserPosition;
private ClusterManager mClusterManager;
private MyClusterManagerRendere mClusterManagerRendere;
private ArrayList<ClusterMarker> mClusterMarkers = new ArrayList<>();
private Handler mHandler = new Handler();
private Runnable mRunnable;
private static final int LOCATION_UPDATE_INTERVAL = 3000; // 3 sek
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.test, container, false);
mMapView = (MapView) view.findViewById(R.id.user_list_map);
mfusedLocationClient = LocationServices.getFusedLocationProviderClient(getActivity());
mDb = FirebaseFirestore.getInstance();
initGoogleMaps(savedInstanceState);
if(getArguments() != null){
mUserLocations = getArguments().getParcelableArrayList(getString(R.string.user_location));
setUserPosition();
}
return view;
}
private void getUserDetails(){
//Merging location, timestamp and user information together
if(mUserLocation == null){
mUserLocation = new UserLocation();
FirebaseUser usercheck = FirebaseAuth.getInstance().getCurrentUser();
if (usercheck != null) {
String user = usercheck.getUid();
String email = usercheck.getEmail();
String username = usercheck.getDisplayName();
int avatar = R.drawable.pbstd;
if(user != null) {
mUserLocation.setUser(user);
mUserLocation.setEmail(email);
mUserLocation.setUsername(username);
mUserLocation.setAvatar(avatar);
getLastKnownLocation();
}
}
}else{
getLastKnownLocation();
}
}
private void getLastKnownLocation(){
Log.d(TAG, "getLastKnownLocation: called.");
if(ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_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();
GeoPoint geoPoint = new GeoPoint(location.getLatitude(), location.getLongitude());
Log.d(TAG, "onComplete: Latitude: " + location.getLatitude());
Log.d(TAG, "onComplete: Longitude: " + location.getLongitude());
mUserLocation.setGeo_Point(geoPoint);
mUserLocation.setTimestamp(null);
saveUserLocation();
}
}
});
}
private void saveUserLocation(){
if(mUserLocation != null) {
DocumentReference locationRef = mDb.
collection(getString(R.string.user_location))
.document(FirebaseAuth.getInstance().getUid());
locationRef.set(mUserLocation).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
Log.d(TAG, "SaveUserLocation: \ninserted user location into database."+
"Latitude: " + mUserLocation.getGeo_Point().getLatitude()+
"Longitude: " + mUserLocation.getGeo_Point().getLongitude());
}
}
});
}
}
private void addMapMarkers(){
if(mGoogleMap != null){
if(mClusterManager == null){
mClusterManager = new ClusterManager<ClusterMarker>(getActivity().getApplicationContext(), mGoogleMap);
}
if (mClusterManagerRendere == null){
mClusterManagerRendere = new MyClusterManagerRendere(
getActivity(),
mGoogleMap,
mClusterManager
);
mClusterManager.setRenderer(mClusterManagerRendere);
}
for (UserLocation userLocation: mUserLocations){
try{
String snippet = "";
if (userLocation.getUser().equals(FirebaseAuth.getInstance().getUid())){
snippet = "This is you";
}else{
snippet = "Determine route to " + userLocation.getUsername() + "?";
}
int avatar = R.drawable.pbstd;
try{
avatar = userLocation.getAvatar();
}catch (NumberFormatException e){
Toast.makeText(getActivity(), "Error Cluster 1", Toast.LENGTH_SHORT).show();
}
ClusterMarker newClusterMarker =new ClusterMarker(
new LatLng(userLocation.getGeo_Point().getLatitude(), userLocation.getGeo_Point().getLongitude()),
userLocation.getUsername(),
snippet,
avatar,
userLocation.getUser());
mClusterManager.addItem(newClusterMarker);
mClusterMarkers.add(newClusterMarker);
}catch (NullPointerException e){
Toast.makeText(getActivity(), "Error Cluster 2", Toast.LENGTH_SHORT).show();
}
}
mClusterManager.cluster();
setCameraView();
}
}
private void setCameraView(){
//Map view window: 0.2 * 0.2 = 0.04
double bottomBoundary = mUserPosition.getGeo_Point().getLatitude() - .1;
double leftBoundary = mUserPosition.getGeo_Point().getLongitude() - .1;
double topBoundary = mUserPosition.getGeo_Point().getLatitude() + .1;
double rightBoundary = mUserPosition.getGeo_Point().getLongitude() + .1;
mMapBoundary = new LatLngBounds(
new LatLng(bottomBoundary, leftBoundary),
new LatLng(topBoundary, rightBoundary)
);
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngBounds(mMapBoundary, 0));
}
private void setUserPosition(){
for (UserLocation userLocation : mUserLocations){
if (userLocation.getUser().equals(FirebaseAuth.getInstance().getUid())){
mUserPosition = userLocation;
Log.d(TAG, "setUserPosition: "+userLocation);
}
}
}
private void initGoogleMaps(Bundle savedInstanceState){
// MapView requires that the Bundle you pass contain _ONLY_ MapView SDK
// objects or sub-Bundles.
Bundle mapViewBundle = null;
if (savedInstanceState != null) {
mapViewBundle = savedInstanceState.getBundle(MAPVIEW_BUNDLE_KEY);
}
mMapView.onCreate(mapViewBundle);
mMapView.getMapAsync(this);
}
private boolean checkMapServices(){
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if(isServiceApproved() && user != null){
if(isMapsEnabled()){
return true;
}
}
return false;
}
//Prompt a dialog
private void buildAlertMessageNoLocation(){
final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage("This application requires Location, do you want to enable it?");
builder.setCancelable(false);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent enableLocationIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivityForResult(enableLocationIntent, PERMISSIONS_REQUEST_ENABLE_LOCATION);
}
});
}
//Determines whether or not the current application has enabled Location.
public boolean isMapsEnabled(){
final LocationManager manager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
if( !manager.isProviderEnabled( LocationManager.GPS_PROVIDER)){
buildAlertMessageNoLocation();
return false;
}
return true;
}
//Request location permission, so that we can get the location of the device.
private void getLocationPermission(){
if(ContextCompat.checkSelfPermission(getActivity().getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mLocationPermissionGranted = true;
//getChatRooms();
getUserDetails();
} else{
//this wil prompt the user a dialog pop-up asking them if its okay to use location permission
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSIONS_REQUEST_ACCES_FINE_LOCATION);
}
}
private void startUserLocationsRunnable(){
Log.d(TAG, "startUserLocationsRunnable: starting runnable for retrieving updated locations.");
mHandler.postDelayed(mRunnable = new Runnable() {
#Override
public void run() {
retrieveUserLocations();
//Call every 3 sec, in the background
mHandler.postDelayed(mRunnable, LOCATION_UPDATE_INTERVAL);
}
}, LOCATION_UPDATE_INTERVAL);
}
private void stopLocationUpdates(){
mHandler.removeCallbacks(mRunnable);
}
private void retrieveUserLocations(){
Log.d(TAG, "retrieveUserLocations: retrieving location of all users in the chatroom.");
//Loop through every ClusterMarker (custom marker in Maps)
try{
for(final ClusterMarker clusterMarker: mClusterMarkers){
DocumentReference userLocationRef = FirebaseFirestore.getInstance()
.collection(getString(R.string.user_location))
.document(clusterMarker.getUser());
userLocationRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if(task.isSuccessful()){
final UserLocation updatedUserLocation = task.getResult().toObject(UserLocation.class);
// update the location
for (int i = 0; i < mClusterMarkers.size(); i++) {
try {
if (mClusterMarkers.get(i).getUser().equals(updatedUserLocation.getUser())) {
LatLng updatedLatLng = new LatLng(
updatedUserLocation.getGeo_Point().getLatitude(),
updatedUserLocation.getGeo_Point().getLongitude()
);
mClusterMarkers.get(i).setPosition(updatedLatLng);
mClusterManagerRendere.setUpdateMarker(mClusterMarkers.get(i));
}
} catch (NullPointerException e) {
Log.e(TAG, "retrieveUserLocations: NullPointerException: " + e.getMessage());
}
}
}
}
});
}
}catch (IllegalStateException e){
Log.e(TAG, "retrieveUserLocations: Fragment was destroyed during Firestore query. Ending query." + e.getMessage() );
}
}
//This function determines whether or not the device is able to use google services
public boolean isServiceApproved(){
Log.d(TAG, "isServiceApproved: checking google services version ");
int available = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(getActivity());
if(available == ConnectionResult.SUCCESS){
//User can access the map
Log.d(TAG, "isServiceApproved: Google Play Services is okay");
return true;
}
else if(GoogleApiAvailability.getInstance().isUserResolvableError(available)){
Log.d(TAG, "isServiceApproved: an error occured");
Dialog dialog = GoogleApiAvailability.getInstance().getErrorDialog(getActivity(), available, ERROR_DIALOG_REQUEST);
dialog.show();
} else {
Toast.makeText(getActivity(), "Map requests cannot be accessed", Toast.LENGTH_SHORT).show();
}
return false;
}
//This function will run after the user either denied or accepted the permission for Fine location
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode){
case PERMISSIONS_REQUEST_ACCES_FINE_LOCATION: {
// if result is cancelled, the result arrays are empty
if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
mLocationPermissionGranted = true;
}
}
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.d(TAG, "onActivityResult: called");
switch (requestCode) {
case PERMISSIONS_REQUEST_ENABLE_LOCATION: {
if (mLocationPermissionGranted) {
//getChatRooms();
getUserDetails();
} else {
getLocationPermission();
}
}
}
}
#Override
public void onResume() {
super.onResume();
if(checkMapServices()){
if(mLocationPermissionGranted){
//getChatRooms();
getUserDetails();
} else{
getLocationPermission();
}
}
mMapView.onResume();
startUserLocationsRunnable();
}
#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);
}
#Override
public void onMapReady(GoogleMap map) {
map.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
if(ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED){
return;
}
//Enable/disable blue dot
map.setMyLocationEnabled(true);
mGoogleMap = map;
addMapMarkers();
map.setOnInfoWindowClickListener(this);
}
#Override
public void onInfoWindowClick(Marker marker) {
final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(marker.getSnippet())
.setCancelable(true)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(#SuppressWarnings("unused") final DialogInterface dialog, #SuppressWarnings("unused") final int id) {
dialog.dismiss();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, #SuppressWarnings("unused") final int id) {
dialog.cancel();
}
});
final AlertDialog alert = builder.create();
alert.show();
}
}

Related

didn't show geofense circle in another device,circle show only in one device

In this app i will genrate geofense circle for current user , if one device have at latlong A,B then this will genrate geofense circle at A,B center and other device is at latlong C,D then this will genrate geofense circle at C,D in another device, In this app one device have only one geofense circle which genrate at device current location
But in this app circle show in only one device
Here is my mapactivity
public class MapsActivity extends FragmentActivity implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener,
OnMapReadyCallback,
ResultCallback<Status> {
private static final String TAG = "MapsActivity";
private Integer j=0;
private Marker mark;
private LatLng location,l1;
private GoogleMap map;
private Toolbar mTopToolbar;
private List<String> ids = new ArrayList<>();
private FirebaseAuth mAuth;
private Double current_lat, current_long, current_geoloc, lat, lon, geoloc;
private String current_name,current_names, name, currentuserid;
private BitmapDescriptor vnrPoint, banPoint;
private LocationRequest locationRequest;
private final int UPDATE_INTERVAL = 6000;
private final int FASTEST_INTERVAL = 3000;
private User users,user,n;
private Marker geoFenceMarker;
private Circle circle,circle2;
private List<MarkerOptions> markerList;
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private CollectionReference myCollection = db.collection("users");
private GeoFire geoFire = new GeoFire(myCollection);
private GoogleApiClient googleApiClient;
private Location lastLocation;
private TextView textLat, textLong;
private MapFragment mapFragment;
private String idd;
private SeekBar volumeControl = null;
private PendingIntent geoFencePendingIntent;
private static final float GEOFENCE_RADIUS = 100.0f; // in meter
private final int REQ_PERMISSION = 999;
private final int GEOFENCE_REQ_CODE = 0;
private final String KEY_GEOFENCE_LAT = "GEOFENCE LATITUDE";
private final String KEY_GEOFENCE_LON = "GEOFENCE LONGITUDE";
private static final String NOTIFICATION_MSG = "NOTIFICATION MSG";
// Create a Intent send by the notification
public static Intent makeNotificationIntent(Context context, String msg) {
Intent intent = new Intent( context, MapsActivity.class );
intent.putExtra( NOTIFICATION_MSG, msg );
return intent;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
volumeControl = (SeekBar) findViewById(R.id.verticalseekbar);
volumeControl.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
int progressChanged = 0;
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
progressChanged = progress;
}
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
public void onStopTrackingTouch(SeekBar seekBar) {
Toast.makeText(getApplicationContext(), "seek bar progress:" + progressChanged,
Toast.LENGTH_SHORT).show();
}
});
textLat = (TextView) findViewById(R.id.lat);
textLong = (TextView) findViewById(R.id.lon);
mAuth = FirebaseAuth.getInstance();
getdata();
mTopToolbar = findViewById(R.id.my_toolbar);
setActionBar(mTopToolbar);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
createGoogleApi();
}
#Override
protected void onStart() {
super.onStart();
// Call GoogleApiClient connection when starting the Activity
googleApiClient.connect();
}
#Override
protected void onStop() {
super.onStop();
// Disconnect GoogleApiClient when stopping Activity
googleApiClient.disconnect();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.option_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
if (item.getItemId() == R.id.main_logout_option) {
mAuth.signOut();
LoginManager.getInstance().logOut();
gotologinactivity();
}
if (item.getItemId() == R.id.clear) {
clearGeofence();
return true;
}
if (item.getItemId() == R.id.geofence) {
startGeofence();
return true;
}
if (item.getItemId() == R.id.Refresh) {
finish();
startActivity(getIntent());
return true;
}
return true;
}
private void createGoogleApi()
{
Log.d(TAG, "createGoogleApi()");
if ( googleApiClient == null ) {
googleApiClient = new GoogleApiClient.Builder( this )
.addConnectionCallbacks(this)
.addOnConnectionFailedListener( this )
.addApi( LocationServices.API )
.build();
}
}
// Check for permission to access Location
private boolean checkPermission() {
Log.d(TAG, "checkPermission()");
// Ask for permission if it wasn't granted yet
return (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED );
}
// Asks for permission
private void askPermission() {
Log.d(TAG, "askPermission()");
ActivityCompat.requestPermissions(
this,
new String[] { Manifest.permission.ACCESS_FINE_LOCATION },
REQ_PERMISSION
);
}
// Verify user's response of the permission requested
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
Log.d(TAG, "onRequestPermissionsResult()");
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch ( requestCode ) {
case REQ_PERMISSION: {
if ( grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED ){
// Permission granted
getLastKnownLocation();
} else {
// Permission denied
permissionsDenied();
}
break;
}
}
}
// App cannot work without the permissions
private void permissionsDenied() {
Log.w(TAG, "permissionsDenied()");
// TODO close app and warn user
}
#Override
public void onMapReady(GoogleMap googleMap) {
map = googleMap;
}
// Start location Updates
private void startLocationUpdates(){
Log.i(TAG, "startLocationUpdates()");
locationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(UPDATE_INTERVAL)
.setFastestInterval(FASTEST_INTERVAL)
.setSmallestDisplacement(30);
//movement in meter
if ( checkPermission() )
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
}
#Override
public void onLocationChanged(Location location) {
Log.d(TAG, "onLocationChanged ["+location+"]");
lastLocation = location;
clearGeofence();
startGeofence();
writeActualLocation(location);
}
#Override
public void onConnected(#Nullable Bundle bundle) {
Log.i(TAG, "onConnected()");
getLastKnownLocation();
recoverGeofenceMarker();
}
// GoogleApiClient.ConnectionCallbacks suspended
#Override
public void onConnectionSuspended(int i) {
Log.w(TAG, "onConnectionSuspended()");
}
// GoogleApiClient.OnConnectionFailedListener fail
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Log.w(TAG, "onConnectionFailed()");
}
// Get last known location
private void getLastKnownLocation() {
Log.d(TAG, "getLastKnownLocation()");
if ( checkPermission() ) {
lastLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
if ( lastLocation != null ) {
Log.i(TAG, "LasKnown location. " +
"Long: " + lastLocation.getLongitude() +
" | Lat: " + lastLocation.getLatitude());
writeLastLocation();
startLocationUpdates();
} else {
Log.w(TAG, "No location retrieved yet");
startLocationUpdates();
}
}
else askPermission();
}
private void writeActualLocation(Location location) {
textLat.setText( "Lat: " + location.getLatitude() );
textLong.setText( "Long: " + location.getLongitude() );
geoloc = (location.getLatitude() + 90) * 180 + location.getLongitude();
markerLocation(new LatLng(location.getLatitude(), location.getLongitude()));
markerForGeofence(new LatLng(location.getLatitude(), location.getLongitude()));
HashMap<String, Object> profileMap = new HashMap<>();
profileMap.put("latitude",location.getLatitude());
profileMap.put("longtitude", location.getLongitude());
profileMap.put("geoFireLocation", geoloc);
idd = mAuth.getCurrentUser().getUid();
db.collection("users").document(idd)
.update(profileMap)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid)
{
Log.d(TAG,"save");
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d(TAG,"not save");
}
});
}
private void writeLastLocation() {
writeActualLocation(lastLocation);
}
private Marker locationMarker;
private void markerLocation(LatLng latLng) {
Log.i(TAG, "markerLocation("+latLng+")");
String title = latLng.latitude + ", " + latLng.longitude;
MarkerOptions markerOptions = new MarkerOptions()
.position(latLng)
.title(title);
if ( map!=null ) {
if ( locationMarker != null )
locationMarker.remove();
locationMarker = map.addMarker(markerOptions);
float zoom = 14f;
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, zoom);
//map.animateCamera(cameraUpdate);
}
}
private void markerForGeofence(LatLng latLng) {
Log.i(TAG, "markerForGeofence("+latLng+")");
String title = latLng.latitude + ", " + latLng.longitude;
// Define marker options
MarkerOptions markerOptions = new MarkerOptions()
.position(latLng)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE))
.title(title);
Log.e("marker",name+""+latLng.toString());
if ( map!=null ) {
// Remove last geoFenceMarker
if (geoFenceMarker != null)
geoFenceMarker.remove();
geoFenceMarker = map.addMarker(markerOptions);
Log.e("geomarker",title+""+geoFenceMarker);
}
}
// Start Geofence creation process
private void startGeofence() {
Log.i(TAG, "startGeofence()");
if( geoFenceMarker != null ) {
a( );
} else {
Log.e(TAG, "Geofence marker is null");
}
}
private void a()
{
for (int i=0;i<j;i++)
{
Geofence geofence = createGeofence( geoFenceMarker.getPosition(), GEOFENCE_RADIUS,ids.get(i));
GeofencingRequest geofenceRequest = createGeofenceRequest( geofence );
addGeofence( geofenceRequest );
}
}
private Geofence createGeofence( LatLng latLng, float radius,String id) {
Log.d(TAG, "createGeofence");
return new Geofence.Builder()
.setRequestId(id)
.setCircularRegion( latLng.latitude,latLng.longitude, radius)
.setTransitionTypes( Geofence.GEOFENCE_TRANSITION_ENTER
| Geofence.GEOFENCE_TRANSITION_EXIT )
.setExpirationDuration(Geofence.NEVER_EXPIRE)
.setNotificationResponsiveness(1000)
.build();
}
// Create a Geofence Request
private GeofencingRequest createGeofenceRequest( Geofence geofence ) {
Log.d(TAG, "createGeofenceRequest");
return new GeofencingRequest.Builder()
.setInitialTrigger( GeofencingRequest.INITIAL_TRIGGER_ENTER | GeofencingRequest.INITIAL_TRIGGER_EXIT )
.addGeofence( geofence )
.build();
}
private PendingIntent createGeofencePendingIntent() {
Log.d(TAG, "createGeofencePendingIntent");
if ( geoFencePendingIntent != null )
return geoFencePendingIntent;
Intent intent = new Intent( this, GeofenseTrasitionService.class);
return PendingIntent.getService(
this, GEOFENCE_REQ_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT );
}
// Add the created GeofenceRequest to the device's monitoring list
private void addGeofence(GeofencingRequest request) {
Log.d(TAG, "addGeofence");
if (checkPermission())
LocationServices.GeofencingApi.addGeofences(
googleApiClient,
request,
createGeofencePendingIntent()
).setResultCallback(this);
}
#Override
public void onResult(#NonNull Status status) {
Log.i(TAG, "onResult: " + status);
if ( status.isSuccess() ) {
saveGeofence();
drawGeofence();
} else {
// inform about fail
}
}
private Circle geoFenceLimits;
private void drawGeofence() {
Log.e("circle", "draw");
if ( circle2 != null )
circle2.remove();
// LatLng last = new LatLng(22.28,73.19);
circle2 = map.addCircle(new CircleOptions()
.center(geoFenceMarker.getPosition())
.radius(GEOFENCE_RADIUS)
.strokeColor(Color.argb(50, 70,70,70))
.fillColor(Color.argb(100, 150,150,150))
.strokeWidth(5.0f));
// map.moveCamera(CameraUpdateFactory.newLatLng(geoFenceMarker.getPosition()));
}
// Saving GeoFence marker with prefs mng
private void saveGeofence() {
Log.d(TAG, "saveGeofence()");
SharedPreferences sharedPref = getPreferences( Context.MODE_PRIVATE );
SharedPreferences.Editor editor = sharedPref.edit();
editor.putLong( KEY_GEOFENCE_LAT, Double.doubleToRawLongBits( geoFenceMarker.getPosition().latitude ));
editor.putLong( KEY_GEOFENCE_LON, Double.doubleToRawLongBits( geoFenceMarker.getPosition().longitude ));
editor.apply();
}
// Recovering last Geofence marker
private void recoverGeofenceMarker() {
Log.d(TAG, "recoverGeofenceMarker");
SharedPreferences sharedPref = getPreferences( Context.MODE_PRIVATE );
if ( sharedPref.contains( KEY_GEOFENCE_LAT ) && sharedPref.contains( KEY_GEOFENCE_LON )) {
double lat = Double.longBitsToDouble( sharedPref.getLong( KEY_GEOFENCE_LAT, -1 ));
double lon = Double.longBitsToDouble( sharedPref.getLong( KEY_GEOFENCE_LON, -1 ));
LatLng latLng = new LatLng( lat, lon );
markerForGeofence(latLng);
drawGeofence();
}
}
// Clear Geofence
private void clearGeofence() {
Log.d(TAG, "clearGeofence()");
LocationServices.GeofencingApi.removeGeofences(
googleApiClient,
createGeofencePendingIntent()
).setResultCallback(new ResultCallback<Status>() {
#Override
public void onResult(#NonNull Status status) {
if ( status.isSuccess() ) {
// remove drawing
removeGeofenceDraw();
}
}
});
}
private void removeGeofenceDraw() {
Log.d(TAG, "removeGeofenceDraw()");
if ( geoFenceMarker != null)
geoFenceMarker.remove();
if ( circle2 != null )
circle2.remove();
}
private void getdata() {
currentuserid = FirebaseAuth.getInstance().getCurrentUser().getUid();
db.collection("users").document(currentuserid).addSnapshotListener(new EventListener<DocumentSnapshot>() {
#Override
public void onEvent(#Nullable DocumentSnapshot documentSnapshot, #Nullable FirebaseFirestoreException e) {
if(documentSnapshot.exists())
{
current_name = documentSnapshot.getString("name");
current_lat = documentSnapshot.getDouble("latitude");
Log.e("lat",current_lat.toString());
current_long = documentSnapshot.getDouble("longtitude");
Log.e("lat",current_long.toString());
location = new LatLng(current_lat, current_long);
if(circle!=null){
circle.remove();
}
try {
circle = map.addCircle(new CircleOptions()
.center(location)
.radius(3000)
.strokeColor(Color.BLUE)
.fillColor(0x220000FF)
.strokeWidth(5.0f)
);
}
catch (Exception e1)
{
Log.e("ex",e1.getMessage());
}
// map.addMarker(new MarkerOptions().position(location).title(current_name));
// map.moveCamera(CameraUpdateFactory.newLatLng(location));
Log.d(TAG,"data"+current_lat+" "+current_long+" "+current_name);
j=0;
getalluser();
}
}
});
}
private void getalluser()
{
QueryLocation queryLocation = QueryLocation.fromDegrees(current_lat, current_long);
Distance searchDistance = new Distance(3, DistanceUnit.KILOMETERS);
geoFire.query()
.whereNearTo(queryLocation, searchDistance)
.build()
.addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#Nullable QuerySnapshot queryDocumentSnapshots, #Nullable FirebaseFirestoreException e) {
if(mark != null)
{
mark.remove();
}
for(final QueryDocumentSnapshot documentSnapshot : queryDocumentSnapshots)
{
user = documentSnapshot.toObject(User.class);
current_names = user.getName();
LatLng all = new LatLng(user.getLatitude(),user.getLongtitude());
showmark(all,current_names,documentSnapshot.getId());
}
}
});
}
private void showmark(LatLng all, String current_n,String id)
{
if(!id.equals(currentuserid))
{
j++;
ids.add(id);
Log.d(TAG, "location"+" "+id+" "+currentuserid+" "+ all + " " + current_n);
vnrPoint = BitmapDescriptorFactory.fromResource(R.drawable.marker_a);
mark = map.addMarker(new MarkerOptions().position(all).icon(vnrPoint).title(current_n));
// map.moveCamera(CameraUpdateFactory.newLatLng(all));
//getnotification();
}
}
private void gotologinactivity() {
Intent intent = new Intent(MapsActivity.this, LoginActivity.class);
startActivity(intent);
finish();
}
}
I don't have any error but geofense circle is not genrate in another device that is the problem it show circle only in one device

I don' know please help... Unable to start activity ComponentInfo{...}: java.lang.NullPointerException [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I am a Korean university student.
I use a translator.
Please excuse me for not being soft.
Failed to resolve issue while writing code, asking questions
Please help me.
The code below is quite simple and the only goal is to navigate from MainActivity.java to Mian2Activity.java However, I've been looking for a solution to this on a lot of tutorial and I really don't get what I'm doing wrong...
this is Main2Activity Code
public class Main2Activity extends AppCompatActivity
implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
private GoogleApiClient mGoogleApiClient = null;
private GoogleMap mGoogleMap = null;
private Marker currentMarker = null;
private static final String TAG = "googlemap_example";
private static final int GPS_ENABLE_REQUEST_CODE = 2001;
private static final int PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 2002;
private static final int UPDATE_INTERVAL_MS = 1000; // 1초
private static final int FASTEST_UPDATE_INTERVAL_MS = 500; // 0.5초
private AppCompatActivity mActivity;
boolean askPermissionOnceAgain = false;
boolean mRequestingLocationUpdates = false;
Location mCurrentLocatiion;
boolean mMoveMapByUser = true;
boolean mMoveMapByAPI = true;
LatLng currentPosition;
LocationRequest locationRequest = new LocationRequest()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(UPDATE_INTERVAL_MS)
.setFastestInterval(FASTEST_UPDATE_INTERVAL_MS);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate");
mActivity = this;
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
MapFragment mapFragment = (MapFragment) getFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onResume() {
super.onResume();
if (mGoogleApiClient.isConnected()) {
Log.d(TAG, "onResume : call startLocationUpdates");
if (!mRequestingLocationUpdates) startLocationUpdates();
}
//앱 정보에서 퍼미션을 허가했는지를 다시 검사해봐야 한다.
if (askPermissionOnceAgain) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
askPermissionOnceAgain = false;
checkPermissions();
}
}
}
private void startLocationUpdates() {
if (!checkLocationServicesStatus()) {
Log.d(TAG, "startLocationUpdates : call showDialogForLocationServiceSetting");
showDialogForLocationServiceSetting();
}else {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
Log.d(TAG, "startLocationUpdates : 퍼미션 안가지고 있음");
return;
}
Log.d(TAG, "startLocationUpdates : call FusedLocationApi.requestLocationUpdates");
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, locationRequest, this);
mRequestingLocationUpdates = true;
mGoogleMap.setMyLocationEnabled(true);
}
}
private void stopLocationUpdates() {
Log.d(TAG,"stopLocationUpdates : LocationServices.FusedLocationApi.removeLocationUpdates");
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
mRequestingLocationUpdates = false;
}
#Override
public void onMapReady(GoogleMap googleMap) {
Log.d(TAG, "onMapReady :");
mGoogleMap = googleMap;
//런타임 퍼미션 요청 대화상자나 GPS 활성 요청 대화상자 보이기전에
//지도의 초기위치를 서울로 이동
setDefaultLocation();
//mGoogleMap.getUiSettings().setZoomControlsEnabled(false);
mGoogleMap.getUiSettings().setMyLocationButtonEnabled(true);
mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
mGoogleMap.setOnMyLocationButtonClickListener(new GoogleMap.OnMyLocationButtonClickListener(){
#Override
public boolean onMyLocationButtonClick() {
Log.d( TAG, "onMyLocationButtonClick : 위치에 따른 카메라 이동 활성화");
mMoveMapByAPI = true;
return true;
}
});
mGoogleMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng latLng) {
Log.d( TAG, "onMapClick :");
}
});
mGoogleMap.setOnCameraMoveStartedListener(new GoogleMap.OnCameraMoveStartedListener() {
#Override
public void onCameraMoveStarted(int i) {
if (mMoveMapByUser == true && mRequestingLocationUpdates){
Log.d(TAG, "onCameraMove : 위치에 따른 카메라 이동 비활성화");
mMoveMapByAPI = false;
}
mMoveMapByUser = true;
}
});
mGoogleMap.setOnCameraMoveListener(new GoogleMap.OnCameraMoveListener() {
#Override
public void onCameraMove() {
}
});
}
#Override
public void onLocationChanged(Location location) {
currentPosition
= new LatLng( location.getLatitude(), location.getLongitude());
Log.d(TAG, "onLocationChanged : ");
String markerTitle = getCurrentAddress(currentPosition);
String markerSnippet = "위도:" + String.valueOf(location.getLatitude())
+ " 경도:" + String.valueOf(location.getLongitude());
//현재 위치에 마커 생성하고 이동
setCurrentLocation(location, markerTitle, markerSnippet);
mCurrentLocatiion = location;
}
#Override
protected void onStart() {
if(mGoogleApiClient != null && mGoogleApiClient.isConnected() == false){
Log.d(TAG, "onStart: mGoogleApiClient connect");
mGoogleApiClient.connect();
}
super.onStart();
}
#Override
protected void onStop() {
if (mRequestingLocationUpdates) {
Log.d(TAG, "onStop : call stopLocationUpdates");
stopLocationUpdates();
}
if ( mGoogleApiClient.isConnected()) {
Log.d(TAG, "onStop : mGoogleApiClient disconnect");
mGoogleApiClient.disconnect();
}
super.onStop();
}
#Override
public void onConnected(Bundle connectionHint) {
if ( mRequestingLocationUpdates == false ) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
int hasFineLocationPermission = ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION);
if (hasFineLocationPermission == PackageManager.PERMISSION_DENIED) {
ActivityCompat.requestPermissions(mActivity,
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
} else {
Log.d(TAG, "onConnected : 퍼미션 가지고 있음");
Log.d(TAG, "onConnected : call startLocationUpdates");
startLocationUpdates();
mGoogleMap.setMyLocationEnabled(true);
}
}else{
Log.d(TAG, "onConnected : call startLocationUpdates");
startLocationUpdates();
mGoogleMap.setMyLocationEnabled(true);
}
}
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.d(TAG, "onConnectionFailed");
setDefaultLocation();
}
#Override
public void onConnectionSuspended(int cause) {
Log.d(TAG, "onConnectionSuspended");
if (cause == CAUSE_NETWORK_LOST)
Log.e(TAG, "onConnectionSuspended(): Google Play services " +
"connection lost. Cause: network lost.");
else if (cause == CAUSE_SERVICE_DISCONNECTED)
Log.e(TAG, "onConnectionSuspended(): Google Play services " +
"connection lost. Cause: service disconnected");
}
public String getCurrentAddress(LatLng latlng) {
//지오코더... GPS를 주소로 변환
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses;
try {
addresses = geocoder.getFromLocation(
latlng.latitude,
latlng.longitude,
1);
} catch (IOException ioException) {
//네트워크 문제
Toast.makeText(this, "지오코더 서비스 사용불가", Toast.LENGTH_LONG).show();
return "지오코더 서비스 사용불가";
} catch (IllegalArgumentException illegalArgumentException) {
Toast.makeText(this, "잘못된 GPS 좌표", Toast.LENGTH_LONG).show();
return "잘못된 GPS 좌표";
}
if (addresses == null || addresses.size() == 0) {
Toast.makeText(this, "주소 미발견", Toast.LENGTH_LONG).show();
return "주소 미발견";
} else {
Address address = addresses.get(0);
return address.getAddressLine(0).toString();
}
}
public boolean checkLocationServicesStatus() {
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
|| locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
public void setCurrentLocation(Location location, String markerTitle, String markerSnippet) {
mMoveMapByUser = false;
if (currentMarker != null) currentMarker.remove();
LatLng currentLatLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(currentLatLng);
markerOptions.title(markerTitle);
markerOptions.snippet(markerSnippet);
markerOptions.draggable(true);
//구글맵의 디폴트 현재 위치는 파란색 동그라미로 표시
//마커를 원하는 이미지로 변경하여 현재 위치 표시하도록 수정 fix - 2017. 11.27
markerOptions.icon(BitmapDescriptorFactory.fromResource(R.mipmap.ic_launcher));
currentMarker = mGoogleMap.addMarker(markerOptions);
if ( mMoveMapByAPI ) {
Log.d( TAG, "setCurrentLocation : mGoogleMap moveCamera "
+ location.getLatitude() + " " + location.getLongitude() ) ;
// CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(currentLatLng, 15);
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLng(currentLatLng);
mGoogleMap.moveCamera(cameraUpdate);
}
}
public void setDefaultLocation() {
mMoveMapByUser = false;
//디폴트 위치, Seoul
LatLng DEFAULT_LOCATION = new LatLng(37.56, 126.97);
String markerTitle = "위치정보 가져올 수 없음";
String markerSnippet = "위치 퍼미션과 GPS 활성 요부 확인하세요";
if (currentMarker != null) currentMarker.remove();
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(DEFAULT_LOCATION);
markerOptions.title(markerTitle);
markerOptions.snippet(markerSnippet);
markerOptions.draggable(true);
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
currentMarker = mGoogleMap.addMarker(markerOptions);
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(DEFAULT_LOCATION, 15);
mGoogleMap.moveCamera(cameraUpdate);
}
//여기부터는 런타임 퍼미션 처리을 위한 메소드들
#TargetApi(Build.VERSION_CODES.M)
private void checkPermissions() {
boolean fineLocationRationale = ActivityCompat
.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION);
int hasFineLocationPermission = ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION);
if (hasFineLocationPermission == PackageManager
.PERMISSION_DENIED && fineLocationRationale)
showDialogForPermission("앱을 실행하려면 퍼미션을 허가하셔야합니다.");
else if (hasFineLocationPermission
== PackageManager.PERMISSION_DENIED && !fineLocationRationale) {
showDialogForPermissionSetting("퍼미션 거부 + Don't ask again(다시 묻지 않음) " +
"체크 박스를 설정한 경우로 설정에서 퍼미션 허가해야합니다.");
} else if (hasFineLocationPermission == PackageManager.PERMISSION_GRANTED) {
Log.d(TAG, "checkPermissions : 퍼미션 가지고 있음");
if ( mGoogleApiClient.isConnected() == false) {
Log.d(TAG, "checkPermissions : 퍼미션 가지고 있음");
mGoogleApiClient.connect();
}
}
}
#Override
public void onRequestPermissionsResult(int permsRequestCode,
#NonNull String[] permissions,
#NonNull int[] grantResults) {
if (permsRequestCode
== PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION && grantResults.length > 0) {
boolean permissionAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
if (permissionAccepted) {
if ( mGoogleApiClient.isConnected() == false) {
Log.d(TAG, "onRequestPermissionsResult : mGoogleApiClient connect");
mGoogleApiClient.connect();
}
} else {
checkPermissions();
}
}
}
#TargetApi(Build.VERSION_CODES.M)
private void showDialogForPermission(String msg) {
AlertDialog.Builder builder = new AlertDialog.Builder(Main2Activity.this);
builder.setTitle("알림");
builder.setMessage(msg);
builder.setCancelable(false);
builder.setPositiveButton("예", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
ActivityCompat.requestPermissions(mActivity,
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
}
});
builder.setNegativeButton("아니오", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
});
builder.create().show();
}
private void showDialogForPermissionSetting(String msg) {
AlertDialog.Builder builder = new AlertDialog.Builder(Main2Activity.this);
builder.setTitle("알림");
builder.setMessage(msg);
builder.setCancelable(true);
builder.setPositiveButton("예", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
askPermissionOnceAgain = true;
Intent myAppSettings = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
Uri.parse("package:" + mActivity.getPackageName()));
myAppSettings.addCategory(Intent.CATEGORY_DEFAULT);
myAppSettings.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mActivity.startActivity(myAppSettings);
}
});
builder.setNegativeButton("아니오", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
});
builder.create().show();
}
//여기부터는 GPS 활성화를 위한 메소드들
private void showDialogForLocationServiceSetting() {
AlertDialog.Builder builder = new AlertDialog.Builder(Main2Activity.this);
builder.setTitle("위치 서비스 비활성화");
builder.setMessage("앱을 사용하기 위해서는 위치 서비스가 필요합니다.\n"
+ "위치 설정을 수정하실래요?");
builder.setCancelable(true);
builder.setPositiveButton("설정", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
Intent callGPSSettingIntent
= new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivityForResult(callGPSSettingIntent, GPS_ENABLE_REQUEST_CODE);
}
});
builder.setNegativeButton("취소", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
builder.create().show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case GPS_ENABLE_REQUEST_CODE:
//사용자가 GPS 활성 시켰는지 검사
if (checkLocationServicesStatus()) {
if (checkLocationServicesStatus()) {
Log.d(TAG, "onActivityResult : 퍼미션 가지고 있음");
if ( mGoogleApiClient.isConnected() == false ) {
Log.d( TAG, "onActivityResult : mGoogleApiClient connect ");
mGoogleApiClient.connect();
}
return;
}
}
break;
}
}
}
and this MainActivity Code
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button bttest1 = (Button)findViewById(R.id.bttest1);
bttest1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(),Main2Activity.class);
startActivity(intent);
}
});
}
}
Unable to start activity ComponentInfo{...}: java.lang.NullPointerException
An error occurs here.(Main2Activity)
mapFragment.getMapAsync(this);
What is the reason for the error?
Help me, please.
In your Main2Activity onCreate, you use setContentView(R.layout.activity_main);
It seems to be layout from MainActivity, not Main2Activity. You should make something like R.layout.activity_main2 for your second activity.
Then, your code
MapFragment mapFragment = (MapFragment) getFragmentManager()
.findFragmentById(R.id.map);
probably won't find view with ID R.id.map, because that view isn't part of first MainActivity layout.

Broadcasting data not passed

I'm trying to make an app that tracks device's location using a service and display that location on Google Map. But I feel like the code in service is not executed at all. When I try to retrieve and assign latitude and longitude to a LatLng object I cannot because they are null.
Here is the main activity:
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private static final String TAG = "MapActivity";
private static final String FINE_LOCATION = Manifest.permission.ACCESS_FINE_LOCATION;
private static final String COURSE_LOCATION = Manifest.permission.ACCESS_COARSE_LOCATION;
private static final int LOCATION_PERMISSION_REQUEST_CODE = 1000;
private static final int ERROR_DIALOG_REQUEST = 1001;
private static final float DEFAULT_ZOOM = 15f;
//vars
private Boolean mLocationPermissionsGranted = false;
private GoogleMap mMap;
private FusedLocationProviderClient mFusedLocationProviderClient;
private BroadcastReceiver mBroadcastReceiver;
private LatLng currentLocation;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
if (isServicesOK()) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
}
getLocationPermission();
startMyService();
}
#Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: resumed from service");
if (mBroadcastReceiver == null) {
Log.d(TAG, "onResume: broadcastReceiver == null");
mBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "onReceive: receiving current location");
currentLocation = new LatLng((double) intent.getExtras().get("latitude"),
(double) intent.getExtras().get("longitude"));
}
};
}
Log.d(TAG, "onResume:"+ currentLocation.toString());
registerReceiver(mBroadcastReceiver, new IntentFilter("location"));
}
#Override
protected void onDestroy() {
super.onDestroy();
Intent intent = new Intent(this.getApplicationContext(), MyService.class);
stopService(intent);
if(mBroadcastReceiver != null){
unregisterReceiver(mBroadcastReceiver);
}
}
private void startMyService() {
Log.d(TAG, "startMyService: starting to track devices location");
Intent intent = new Intent(this.getApplicationContext(), MyService.class);
startService(intent);
}
#Override
public void onMapReady(GoogleMap googleMap) {
Toast.makeText(this, "Map is Ready", Toast.LENGTH_SHORT).show();
Log.d(TAG, "onMapReady: map is ready");
mMap = googleMap;
if (currentLocation != null) {
moveCamera(currentLocation, 15f);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// auto-generated permission check
return;
}
mMap.setMyLocationEnabled(true);
}
}
private void moveCamera(LatLng latLng, float zoom){
Log.d(TAG, "moveCamera: moving the camera to: lat: " + latLng.latitude + ", lng: " + latLng.longitude );
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoom));
}
private void initMap(){
Log.d(TAG, "initMap: initializing map");
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(MapsActivity.this);
}
private void getLocationPermission(){
Log.d(TAG, "getLocationPermission: getting location permissions");
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(),
COURSE_LOCATION) == PackageManager.PERMISSION_GRANTED){
mLocationPermissionsGranted = true;
initMap();
}else{
ActivityCompat.requestPermissions(this,
permissions,
LOCATION_PERMISSION_REQUEST_CODE);
}
}else{
ActivityCompat.requestPermissions(this,
permissions,
LOCATION_PERMISSION_REQUEST_CODE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
Log.d(TAG, "onRequestPermissionsResult: called.");
mLocationPermissionsGranted = false;
switch(requestCode){
case LOCATION_PERMISSION_REQUEST_CODE:{
if(grantResults.length > 0){
for(int i = 0; i < grantResults.length; i++){
if(grantResults[i] != PackageManager.PERMISSION_GRANTED){
mLocationPermissionsGranted = false;
Log.d(TAG, "onRequestPermissionsResult: permission failed");
return;
}
}
Log.d(TAG, "onRequestPermissionsResult: permission granted");
mLocationPermissionsGranted = true;
//initialize our map
initMap();
}
}
}
}
public boolean isServicesOK(){
Log.d(TAG, "isServicesOK: checking google services version");
int availvable = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(MapsActivity.this);
if(availvable == ConnectionResult.SUCCESS){
//everything is fine
Log.d(TAG, "isServicesOK: google play services is working");
return true;
}
else if(GoogleApiAvailability.getInstance().isUserResolvableError(availvable)) {
//an error occured but we can resolve it
Log.d(TAG, "isServicesOK: an error occured but we can fix it");
Dialog dialog = GoogleApiAvailability.getInstance().getErrorDialog(MapsActivity.this,availvable, ERROR_DIALOG_REQUEST); dialog.show();
}else{
Toast.makeText(this,"You can't make map request", Toast.LENGTH_SHORT).show();
}
return false;
}
}
The service class:
public class MyService extends Service {
private LocationListener listener;
private LocationManager locationManager;
private static final String TAG = "MyService";
private FusedLocationProviderClient mFusedLocationProviderClient;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#SuppressLint("MissingPermission")
#Override
public void onCreate() {
Log.d(TAG, "getDeviceLocation: getting the devices current location");
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
try{
final Task location = mFusedLocationProviderClient.getLastLocation();
location.addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if(task.isSuccessful()){
Log.d(TAG, "onComplete: found location!");
Location currentLocation = (Location) task.getResult();
Intent intent = new Intent("location");
intent.putExtra("latitude", currentLocation.getLatitude());
intent.putExtra("longitude", currentLocation.getLongitude());
sendBroadcast(intent);
}else{
Log.d(TAG, "onComplete: current location is null");
}
}
});
}catch (SecurityException e){
Log.e(TAG, "getDeviceLocation: SecurityException: " + e.getMessage() );
}
}
}
I know how to get the current location and update the map but without using a service. But I need to make it this way - with a service. And I can't figure out where my mistake is.

how to create service to update location in background

public class MainActivity extends AppCompatActivity {
private static String lat_long_time="";
private static final String TAG = MainActivity.class.getSimpleName();
private static final int PERMISSION_REQUEST_CODE = 1;
private static final int REQUEST_PERMISSIONS_REQUEST_CODE = 34;
private static final int REQUEST_CHECK_SETTINGS = 0x1;
private static final long UPDATE_INTERVAL_IN_MILLISECONDS = 5000;
private static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS =
UPDATE_INTERVAL_IN_MILLISECONDS / 2;
private final static String KEY_REQUESTING_LOCATION_UPDATES = "requesting-location-updates";
private final static String KEY_LOCATION = "location";
private final static String KEY_LAST_UPDATED_TIME_STRING = "last-updated-time-string";
private FusedLocationProviderClient mFusedLocationClient;
private SettingsClient mSettingsClient;
private LocationRequest mLocationRequest;
private LocationSettingsRequest mLocationSettingsRequest;
private LocationCallback mLocationCallback;
private Location mCurrentLocation;
private Button mStartUpdatesButton;
private TextView mLastUpdateTimeTextView;
private TextView mLatitudeTextView;
private TextView mLongitudeTextView;
private String mLatitudeLabel;
private String mLongitudeLabel;
private String mLastUpdateTimeLabel;
private Boolean mRequestingLocationUpdates;
private String mLastUpdateTime;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if(!checkPermissionForStorage()){
requestPermissionForStorage();
}
mStartUpdatesButton = (Button)
findViewById(R.id.start_updates_button);
findViewById(R.id.stop_updates_button);
mLatitudeTextView = (TextView) findViewById(R.id.latitude_text);
mLongitudeTextView = (TextView) findViewById(R.id.longitude_text);
mLastUpdateTimeTextView = (TextView)
findViewById(R.id.last_update_time_text);
mLatitudeLabel =
getResources().getString(R.string.latitude_label);
mLongitudeLabel =
getResources().getString(R.string.longitude_label);
mLastUpdateTimeLabel =
getResources().getString(R.string.last_update_time_label);
mRequestingLocationUpdates = false;
mLastUpdateTime = "";
updateValuesFromBundle(savedInstanceState);
mFusedLocationClient =
LocationServices.getFusedLocationProviderClient(this);
mSettingsClient = LocationServices.getSettingsClient(this);
LocationRequest, and
createLocationCallback();
createLocationRequest();
buildLocationSettingsRequest();
}
private void updateValuesFromBundle(Bundle savedInstanceState) {
if (savedInstanceState != null) {
if (savedInstanceState.keySet().contains(KEY_REQUESTING_LOCATION_UPDATES)) {
mRequestingLocationUpdates = savedInstanceState.getBoolean(
KEY_REQUESTING_LOCATION_UPDATES);
}
if (savedInstanceState.keySet().contains(KEY_LOCATION)) {
sure that mCurrentLocation
mCurrentLocation = savedInstanceState.getParcelable(KEY_LOCATION);
}
if (savedInstanceState.keySet().contains(KEY_LAST_UPDATED_TIME_STRING)) {
mLastUpdateTime = savedInstanceState.getString(KEY_LAST_UPDATED_TIME_STRING);
}
updateUI();
}
}
private void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
private void createLocationCallback() {
mLocationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
super.onLocationResult(locationResult);
mCurrentLocation = locationResult.getLastLocation();
mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
updateLocationUI();
}
};
}
private void buildLocationSettingsRequest() {
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
builder.addLocationRequest(mLocationRequest);
mLocationSettingsRequest = builder.build();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
startResolutionForResult().
case REQUEST_CHECK_SETTINGS:
switch (resultCode) {
case Activity.RESULT_OK:
Log.i(TAG, "User agreed to make required location settings changes.");
break;
case Activity.RESULT_CANCELED:
Log.i(TAG, "User chose not to make required location settings changes.");
mRequestingLocationUpdates = false;
updateUI();
break;
}
break;
}
}
public void startUpdatesButtonHandler(View view) {
if (!mRequestingLocationUpdates) {
mRequestingLocationUpdates = true;
setButtonsEnabledState();
startLocationUpdates();
}
}
private void startLocationUpdates() {
mSettingsClient.checkLocationSettings(mLocationSettingsRequest)
.addOnSuccessListener(this, new OnSuccessListener<LocationSettingsResponse>() {
#Override
public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
Log.i(TAG, "All location settings are satisfied.");
//noinspection MissingPermission
mFusedLocationClient.requestLocationUpdates(mLocationRequest,
mLocationCallback, Looper.myLooper());
updateUI();
}
})
.addOnFailureListener(this, new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
int statusCode = ((ApiException) e).getStatusCode();
switch (statusCode) {
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
Log.i(TAG, "Location settings are not satisfied. Attempting to upgrade " +
"location settings ");
try {
// Show the dialog by calling startResolutionForResult(), and check the
// result in onActivityResult().
ResolvableApiException rae = (ResolvableApiException) e;
rae.startResolutionForResult(MainActivity.this, REQUEST_CHECK_SETTINGS);
} catch (IntentSender.SendIntentException sie) {
Log.i(TAG, "PendingIntent unable to execute request.");
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
String errorMessage = "Location settings are inadequate, and cannot be " +
"fixed here. Fix in Settings.";
Log.e(TAG, errorMessage);
Toast.makeText(MainActivity.this, errorMessage, Toast.LENGTH_LONG).show();
mRequestingLocationUpdates = false;
}
updateUI();
}
});
}
private void updateUI() {
setButtonsEnabledState();
updateLocationUI();
}
private void setButtonsEnabledState() {
if (mRequestingLocationUpdates) {
mStartUpdatesButton.setEnabled(false);
//mStopUpdatesButton.setEnabled(true);
} else {
mStartUpdatesButton.setEnabled(true);
//mStopUpdatesButton.setEnabled(false);
}
}
private void updateLocationUI() {
if (mCurrentLocation != null) {
mLatitudeTextView.setText(String.format(Locale.ENGLISH, "%s: %f", mLatitudeLabel,
mCurrentLocation.getLatitude()));
mLongitudeTextView.setText(String.format(Locale.ENGLISH, "%s: %f", mLongitudeLabel,
mCurrentLocation.getLongitude()));
mLastUpdateTimeTextView.setText(String.format(Locale.ENGLISH, "%s: %s",
mLastUpdateTimeLabel, mLastUpdateTime));
Toast.makeText(MainActivity.this, "latitude="+mCurrentLocation.getLatitude()
+" longitude="+mCurrentLocation.getLongitude()+
" last update="+mLastUpdateTime, LENGTH_SHORT).show();
lat_long_time=mCurrentLocation.getLatitude()+" "+mCurrentLocation.getLongitude();
Map<String, String> source = readFromSdMap("GettingLocation/sources.dat");
source.put(mLastUpdateTime, lat_long_time);
saveToSDMap(source, "GettingLocation/sources.dat");
Toast.makeText(MainActivity.this,lat_long_time,Toast.LENGTH_SHORT).show();
}
}
#Override
public void onResume() {
super.onResume();
if (mRequestingLocationUpdates && checkPermissions()) {
startLocationUpdates();
} else if (!checkPermissions()) {
requestPermissions();
}
updateUI();
}
#Override
protected void onPause() {
super.onPause();
}
#Override
public void onStop(){
super.onStop();
}
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putBoolean(KEY_REQUESTING_LOCATION_UPDATES, mRequestingLocationUpdates);
savedInstanceState.putParcelable(KEY_LOCATION, mCurrentLocation);
savedInstanceState.putString(KEY_LAST_UPDATED_TIME_STRING, mLastUpdateTime);
super.onSaveInstanceState(savedInstanceState);
}
private void showSnackbar(final int mainTextStringId, final int actionStringId,
View.OnClickListener listener) {
Snackbar.make(
findViewById(android.R.id.content),
getString(mainTextStringId),
Snackbar.LENGTH_INDEFINITE)
.setAction(getString(actionStringId), listener).show();
}
private boolean checkPermissions() {
int permissionState = ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION);
return permissionState == PackageManager.PERMISSION_GRANTED;
}
private boolean checkPermissionForStorage() {
int result = ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (result == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
return false;
}
}
private void requestPermissionForStorage() {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
}
private void requestPermissions() {
boolean shouldProvideRationale =
ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION);
if (shouldProvideRationale) {
Log.i(TAG, "Displaying permission rationale to provide additional context.");
showSnackbar(R.string.permission_rationale,
android.R.string.ok, new View.OnClickListener() {
#Override
public void onClick(View view) {
// Request permission
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_PERMISSIONS_REQUEST_CODE);
}
});
} else {
Log.i(TAG, "Requesting permission");
// Request permission. It's possible this can be auto answered if device policy
// sets the permission in a given state or the user denied the permission
// previously and checked "Never ask again".
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_PERMISSIONS_REQUEST_CODE);
}
}
public static boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
return true;
}
return false;
}
void saveToSDMap(Map<String, String> source, String dest) {
if (isExternalStorageWritable()) {
File path = Environment.getExternalStorageDirectory();
try {
File dir = new File(valueOf(path) + "/GettingLocation");
if (!dir.exists()) {
dir.mkdir();
}
FileOutputStream fos =
new FileOutputStream(
new File(path, dest)
);
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(source);
os.close();
} catch (Exception ex) {
ex.printStackTrace();
System.out.println(ex.getMessage());
}
}
}
public static Map<String, String> readFromSdMap(String dest) {
Map<String, String> source = new HashMap<String, String>();
if (isExternalStorageWritable()) {
File path = Environment.getExternalStorageDirectory();
try {
File dir = new File(valueOf(path) + "/GettingLocation");
if (!dir.exists()) {
dir.mkdir();
}
FileInputStream fis =
new FileInputStream(
new File(path, dest)
);
ObjectInputStream is = new ObjectInputStream(fis);
source = (Map<String, String>) is.readObject();
is.close();
fis.close();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
return source;
} else {
return source;
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions,
#NonNull int[] grantResults) {
Log.i(TAG, "onRequestPermissionResult");
if (requestCode == REQUEST_PERMISSIONS_REQUEST_CODE) {
if (grantResults.length <= 0) {
// If user interaction was interrupted, the permission request is cancelled and you
// receive empty arrays.
Log.i(TAG, "User interaction was cancelled.");
} else if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (mRequestingLocationUpdates) {
Log.i(TAG, "Permission granted, updates requested, starting location updates");
startLocationUpdates();
}
} else {
showSnackbar(R.string.permission_denied_explanation,
R.string.settings, new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setAction(
Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package",
BuildConfig.APPLICATION_ID, null);
intent.setData(uri);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
});
}
}
}
}
/* Add your service in Manifest... */
/* Your Activity */
Gps_service gps = new Gps_service(this);
if (gps.canGetLocation()) {
double latitude = Application.gps.getLatitude();
double longitude = Application.gps.getLongitude();
LogHelper.v("latitude","latitude=="+latitude +" longitude=="+longitude);
getAddress(latitude, longitude);
}
*******If you need to fetch the Address use the following method*******
private void getAddress(double lat, double lon) {
String cityName = "";
String stateName = "";
String postalCode = "";
String countryName = "";
StringBuilder finalAddress = new StringBuilder();
try {
Geocoder geocoder = new Geocoder(ManagedActivity.this, Locale.getDefault());
List<Address> addresses = geocoder.getFromLocation(lat, lon, 1);
if (addresses != null) {
try {
cityName = addresses.get(0).getLocality();
stateName = addresses.get(0).getAdminArea();
countryName = addresses.get(0).getCountryName();
postalCode = addresses.get(0).getPostalCode();
if (addresses.get(0).getAddressLine(0) != null)
finalAddress.append(addresses.get(0).getAddressLine(0));
if (addresses.get(0).getAddressLine(1) != null)
finalAddress.append(addresses.get(0).getAddressLine(1));
if (addresses.get(0).getAddressLine(2) != null)
finalAddress.append(addresses.get(0).getAddressLine(2));
if (addresses.get(0).getAddressLine(3) != null)
finalAddress.append(addresses.get(0).getAddressLine(3));
mDataStorage.saveAddress(this, String.valueOf(finalAddress));
} catch (Exception e)
{
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
/* Service class */
public class Gps_service extends Service implements LocationListener,
ActivityCompat.OnRequestPermissionsResultCallback {
private Context mContext;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 20; // 20 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 5000; // 5 seconds
// Declaring a Location Manager
protected LocationManager locationManager;
public Gps_service(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
// First get location from Network Provider
if (isNetworkEnabled) {
if (Build.VERSION.SDK_INT >= 23) {
if (ActivityCompat.checkSelfPermission((Activity) mContext,
Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission((Activity) mContext,
Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions((Activity) mContext,
new String[]{
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION,}, 1);
} else {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
}
} else {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
}
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
LogHelper.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
return latitude;
}
/**
* Function to get longitude
*/
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
public boolean canGetLocation() {
return this.canGetLocation;
}
#Override
public void onLocationChanged(Location location) {
this.location = location;
LogHelper.v("Location changed", "Location changed==" + location);
latitude = location.getLatitude();
longitude = location.getLongitude();
}
You can use fused location service to detect the location in background. check out my answer here
https://stackoverflow.com/a/43155046/3789993 .
For Detailed information check this link http://www.vogella.com/tutorials/AndroidLocationAPI/article.html
and don't forget to add runtime permission

Android GPS works at first but later returns null values

This is a simple GPS logger. The latitude and longitude values get logged into an SQLite database every 10 seconds.
This works when my app is run for the first time, but when the app is run again the location values are null and my table never gets updated with the values.
public class GPSService extends Service {
public static final String TAG = GPSService.class.getSimpleName();
private static final int ONGOING_NOTIFICATION_ID = 1000;
public static final String GPS_WAKE_LOCK = "GPSWakeLock";
public static final int GPS_TIME_THRESHOLD = 10000; // 10 sec
public static final int GPS_DISTANCE_THRESHOLD = 10; // 10 meters
public static EventBus bus = EventBus.getDefault();
private LocationManager lm;
private LocationManager locationManager2;
private LocationListener locationListener;
private Location location = null;
private Timer timer;
private DumpTask dumpTask = null;
private DatabaseHelper myDb = null;
private static boolean active = false;
private PowerManager.WakeLock wakeLock = null;
public static Double Latitude;
public static Double Longitude;
public static int TotalNoOfStations;
public float[] result = new float[2];
public int k;
public static Boolean SwitchOffAlarmService=false;
#Override
public void onCreate() {
super.onCreate();
bus.register(this);
timer = new Timer();
myDb = DatabaseHelper.getInstance(this);
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager2 = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationListener = new MyLocationListener();
Log.d(TAG, "onCreate ");
k=0;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onDestroy() {
Log.d(TAG, "destroyed");
bus.unregister(this);
timer.cancel();
stopService(new Intent(this,GPSService.class));
super.onDestroy();
}
#SuppressWarnings("unused")
public void onEvent(GPSLoggerCommand e) {
if (e.command == GPSLoggerCommand.START && !active) {
Log.d(TAG, "start gps logger");
getRouteDetails();
MainActivity.LocationServiceStarted=true;
getLatLonFromDB();
try {
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, GPS_TIME_THRESHOLD, GPS_DISTANCE_THRESHOLD, locationListener);
}catch (SecurityException ex){
Log.e(TAG, "onEvent " + ex.toString());
}
dumpTask = new DumpTask();
timer.schedule(dumpTask, GPS_TIME_THRESHOLD, GPS_TIME_THRESHOLD);
active = true;
} else if (e.command == GPSLoggerCommand.STOP && active) {
Log.d(TAG, "stop gps logger");
dumpTask.cancel();
try {
lm.removeUpdates(locationListener);
}catch(SecurityException ex){
Log.e(TAG, "onEvent " + ex);
}
bus.post(new StatusReply("total rows " + myDb.getRowsCount()));
stopForeground(true);
active = false;
locationManager2.sendExtraCommand(LocationManager.GPS_PROVIDER,"delete_aiding_data",null);
Bundle bundle = new Bundle();
locationManager2.sendExtraCommand("gps","force_xtra_injection",bundle);
locationManager2.sendExtraCommand("gps","fource_time_injection",bundle);
stopService(new Intent(this,GPSService.class));
} else if (e.command == GPSLoggerCommand.STATUS) {
Log.d(TAG, "onEvent send message " + active);
bus.post(new GPSLoggerStatus(active));
}
}
public class MyLocationListener implements LocationListener {
public void onLocationChanged(Location loc) {
if (loc != null) {
Log.d(TAG, "onLocationChanged " + loc.getLatitude() + ":" + loc.getLongitude());
location = loc;
}
}
public void onProviderDisabled(String provider) {
Log.d(TAG, "onProviderDisabled");
Toast.makeText(GPSService.this, "Service Canceled due to GPS being Disabled!!", Toast.LENGTH_SHORT).show();
GPSLoggerCommand c;
c = new GPSLoggerCommand(GPSLoggerCommand.STOP);
bus.post(c);
MainActivity.GPServiceStarted=false;
MainActivity.LocationServiceStarted=false;
}
public void onProviderEnabled(String provider) {
Log.d(TAG, "onProviderEnabled");
}
public void onStatusChanged(String provider, int status, Bundle extras) {
String showStatus = null;
if (status == LocationProvider.AVAILABLE)
showStatus = "Available";
if (status == LocationProvider.TEMPORARILY_UNAVAILABLE)
showStatus = "Temporarily Unavailable";
if (status == LocationProvider.OUT_OF_SERVICE)
showStatus = "Out of Service";
Log.d(TAG, "onStatusChanged " + showStatus);
}
}
public class DumpTask extends TimerTask {
#Override
public void run() {
Log.d(TAG, "dump to base");
if (location != null) {
// write to database
}
}
}
public static void StopServiceFunction()
{
GPSLoggerCommand c;
c = new GPSLoggerCommand(GPSLoggerCommand.STOP);
bus.post(c);
MainActivity.GPServiceStarted=false;
MainActivity.LocationServiceStarted=false;
active = false;
}
}
implement GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener
in your activity and past below code in override methods
#Override
public void onConnected(#Nullable Bundle bundle) {
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;
}
Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (location == null) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, (com.google.android.gms.location.LocationListener) this);
} else {
mCurrentLatitude = location.getLatitude();
mCurrentLongitude = location.getLongitude();
Toast.makeText(this, mCurrentLongitude + " * ********"+mCurrentLatitude, Toast.LENGTH_LONG).show();
}
}

Categories

Resources