Broadcasting data not passed - java

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.

Related

onInfoWindowClick doesn't do anything

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();
}
}

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

Having problems with google maps on Fragments layout

I made an activity with google maps displayed, but I'd like to change it to Fragments, When I do that i get lots of errors.
I have problems with getMapAsync on the initmap method.
public class TAXIActivity extends Fragment implements OnMapReadyCallback {
private GoogleMap mMap;
private MapView mapView;
ArrayList LatitudeList = new ArrayList();
ArrayList LongitudeList = new ArrayList();
private FusedLocationProviderClient mFusedLocationProviderClient;
private Boolean mLocationPermissionsGranted = false;
private static final float DEFAULT_ZOOM = 15f;
private static final int LOCATION_PERMISSION_REQUEST_CODE = 1234;
private static final String FINE_LOCATION = Manifest.permission.ACCESS_FINE_LOCATION;
private static final String COURSE_LOCATION = Manifest.permission.ACCESS_COARSE_LOCATION;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.activity_taxi, container, false);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_taxi);
/*
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
*/
getLocationPermission();
//someMethod();
}
public void onViewCreated (View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
initMap();
}
#Override
public void onMapReady(GoogleMap googleMap) {
Toast.makeText(getContext(), "Map is Ready", Toast.LENGTH_SHORT).show();
Log.d("TAXIActivity", "onMapReady: map is ready");
mMap = googleMap;
someMethod();
if (mLocationPermissionsGranted) {
getDeviceLocation();
if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(),
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mMap.setMyLocationEnabled(true);
//mMap.getUiSettings().setMyLocationButtonEnabled(false);
}
//Log.d("TEST", "BBB");
//String LatMarkers = LatitudeList.toString();
//String LongMarkers = LongitudeList.toString();
//Log.d("TEST", "AAA");
/*
double latitude = Double.parseDouble(LatMarkers);
double longitude = Double.parseDouble(LongMarkers);
LatLng location = new LatLng(latitude, longitude);
//Log.d("TEST", "CCC");
mMap.addMarker(new MarkerOptions().position(location).title("Camera Location"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(location));
*/
//Log.d("TEST", "DDD");
}
OkHttpClient client = new OkHttpClient();
void someMethod() {
try {
String jsonData = new TAXIAPI(client).execute().get();
JSONObject object = new JSONObject(jsonData);
JSONArray RunningArray = object.getJSONArray("value");
for (int i = 0; i < RunningArray.length(); ++i) {
JSONObject objectInner = new JSONObject(RunningArray.getString(i));
String Latitude = objectInner.getString("Latitude");
String Longitude = objectInner.getString("Longitude");
double lat = Double.parseDouble(Latitude);
double lng = Double.parseDouble(Longitude);
LatLng location = new LatLng(lat, lng);
mMap.addMarker(new MarkerOptions().position(location).title("Taxi Location"));
//mMap.moveCamera(CameraUpdateFactory.newLatLng(location));//this will make camera focus on the last marker location
//LatitudeList.add(Latitude);
//LongitudeList.add(Longitude);
Log.d("APIActivity", " " + Latitude + " " + Longitude);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void getDeviceLocation() {
Log.d("TAXIActivity", "getDeviceLocation: getting the devices current location");
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(getContext());
try {
if (mLocationPermissionsGranted) {
final Task location = mFusedLocationProviderClient.getLastLocation();
location.addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if (task.isSuccessful()) {
Log.d("TAXIActivity", "onComplete: found location!");
Location currentLocation = (Location) task.getResult();
moveCamera(new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude()),
DEFAULT_ZOOM);
} else {
Log.d("TAXIActivity", "onComplete: current location is null");
Toast.makeText(getContext(), "unable to get current location", Toast.LENGTH_SHORT).show();
}
}
});
}
} catch (SecurityException e) {
Log.e("TAXIActivity", "getDeviceLocation: SecurityException: " + e.getMessage());
}
}
private void moveCamera(LatLng latLng, float zoom) {
Log.d("TAXIActivity", "moveCamera: moving the camera to: lat: " + latLng.latitude + ", lng: " + latLng.longitude);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoom));
}
private void initMap() {
Log.d("TAXIActivity", "initMap: initializing map");
SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(TAXIActivity.this);
}
private void getLocationPermission() {
Log.d("TAXIActivity", "getLocationPermission: getting location permissions");
String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION};
if (ContextCompat.checkSelfPermission(getActivity().getApplicationContext(),
FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(getActivity().getApplicationContext(),
COURSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mLocationPermissionsGranted = true;
initMap();
} else {
ActivityCompat.requestPermissions(getActivity(),
permissions,
LOCATION_PERMISSION_REQUEST_CODE);
}
} else {
ActivityCompat.requestPermissions(getActivity(),
permissions,
LOCATION_PERMISSION_REQUEST_CODE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
Log.d("TAXIActivity", "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("TAXIActivity", "onRequestPermissionsResult: permission failed");
return;
}
}
Log.d("TAXIActivity", "onRequestPermissionsResult: permission granted");
mLocationPermissionsGranted = true;
//initialize our map
initMap();
}
}
}
}
}
Error:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.maps.SupportMapFragment.getMapAsync(com.google.android.gms.maps.OnMapReadyCallback)' on a null object reference
at com.example.assignment1.TAXIActivity.initMap(TAXIActivity.java:199)
at com.example.assignment1.TAXIActivity.getLocationPermission(TAXIActivity.java:213)
at com.example.assignment1.TAXIActivity.onCreate(TAXIActivity.java:72)
You're getting google map fragment before your fragment view is created.
Right now you're doing, onCreate then getLocationPermission then initMap then .findFragmentById. Your google map fragment is not initialized at this point, that's why you're getting a null pointer exception when calling .getMapAsync.
Two solutions. Move you getLocationPermission to onViewCreated or remove initMap from getLocationPermission.
I'd do the second one, because Google Map doesn't need location permission.

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.

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