My MainActivity looks like this:-
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, OnMapReadyCallback, LocationListener {
public static GoogleMap mMap;
public boolean flag = false;
public static boolean markerAlready = false;
public static PlaceAutocompleteFragment placeAutoComplete;
private LocationManager mLocationManager = null;
private String provider = null;
Circle c;
private Marker mCurrentPosition = null;
Marker marker;
public static Location location;
CircleOptions mOptions;
public static Location l;
FancyButton button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.btnGuide);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(MainActivity.this, "Opens guides's details!", Toast.LENGTH_SHORT).show();
}
});
int perm = ContextCompat.checkSelfPermission(
MainActivity.this,
Manifest.permission.ACCESS_COARSE_LOCATION);
if (perm == PackageManager.PERMISSION_GRANTED) {
start();
final LocationManager manager = (LocationManager) getSystemService( Context.LOCATION_SERVICE );
if ( !manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) {
buildAlertMessageNoGps();
}
} else {
ActivityCompat.requestPermissions(
MainActivity.this,
new String[] {Manifest.permission.ACCESS_COARSE_LOCATION},
44
);
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
#NonNull String[] permissions,
#NonNull int[] grantResults) {
if (requestCode == 44) { //write request
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
start();
}
}
else if (Build.VERSION.SDK_INT >= 23 && !shouldShowRequestPermissionRationale(permissions[0])) {
Toast.makeText(MainActivity.this, "Go to Settings and Grant the permission to use this feature.", Toast.LENGTH_SHORT).show();
}
}
public void start()
{
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingSearchView searchView = findViewById(R.id.floating_search_view);
searchView.setSearchHint("");
placeAutoComplete = (PlaceAutocompleteFragment) getFragmentManager().findFragmentById(R.id.place_autocomplete);
Fragment a = getFragmentManager().findFragmentById(R.id.place_autocomplete);
a.setUserVisibleHint(false);
placeAutoComplete.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
if (marker != null)
marker.remove();
flag = true;
Log.d("Maps", "Place selected: " + place.getLatLng());
marker = mMap.addMarker(new MarkerOptions().position(place.getLatLng()).title(place.getName().toString()).zIndex(800));
mMap.moveCamera(CameraUpdateFactory.newLatLng(place.getLatLng()));
mMap.animateCamera(CameraUpdateFactory.zoomIn());
mMap.animateCamera(CameraUpdateFactory.zoomTo(13), 2000, null);
}
#Override
public void onError(Status status) {
Log.d("Maps", "An error occurred: " + status);
}
});
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
flag = false;
mMap.clear();
locateCurrentPosition();
placeAutoComplete.setText(null);
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
//region NavDrawer Activity
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
if(id == R.id.emergency){
List<String> HelpLineNumbers = new ArrayList<>();
HelpLineNumbers.add("Women's Helpline");
HelpLineNumbers.add("Police");
HelpLineNumbers.add("Hospital");
HelpLineNumbers.add("Fire Department");
HelpLineNumbers.add("Ambulance");
HelpLineNumbers.add("Men's Helpline");
final CharSequence[] helpLine = HelpLineNumbers.toArray(new String[HelpLineNumbers.size()]);
AlertDialog.Builder mBuilder = new AlertDialog.Builder(MainActivity.this);
mBuilder.setTitle("Helpline Numbers");
mBuilder.setItems(helpLine, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
String selectedText = helpLine[i].toString();
}
});
AlertDialog alertDialogObject = mBuilder.create();
alertDialogObject.show();
}
List<String> HelpLineNumbers = new ArrayList<>();
HelpLineNumbers.add("Women's Helpline");
HelpLineNumbers.add("Police");
HelpLineNumbers.add("Hospital");
HelpLineNumbers.add("Fire Department");
HelpLineNumbers.add("Ambulance");
HelpLineNumbers.add("Men's Helpline");
final CharSequence[] helpLine = HelpLineNumbers.toArray(new String[HelpLineNumbers.size()]);
AlertDialog.Builder mBuilder = new AlertDialog.Builder(MainActivity.this);
mBuilder.setTitle("Helpline Numbers");
mBuilder.setItems(helpLine, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
String selectedText = helpLine[i].toString();
}
});
AlertDialog alertDialogObject = mBuilder.create();
//Show the dialog
alertDialogObject.show();
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.myProfile) {
// Handle the camera action
} else if (id == R.id.myTrips) {
} else if (id == R.id.fir) {
} else if (id == R.id.logout) {
} else if (id == R.id.contactus) {
} else if (id == R.id.feedback) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private void setupBottomNavigationView()
{
Log.d("BottomNv", "setupBottomNavigationView: setting up botNavView");
BottomNavigationViewEx bottomNavigationViewEx = findViewById(R.id.bnve);
BottomNavigationViewHelper.setupBottomNavigationView(bottomNavigationViewEx);
BottomNavigationViewHelper.enableNavigation(this,bottomNavigationViewEx);
}
//endregion
//region Maps Methods
public void onMapReady(GoogleMap googleMap) {
LocationManager lm = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
boolean gps_enabled = false;
boolean network_enabled = false;
try {
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch(Exception ex) {
Log.e("Error", "onMapReady: ");
}
try {
network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch(Exception ex) {
Log.e("Error", "onMapReady: " );
}
if(!gps_enabled && !network_enabled)
{
buildAlertMessageNoGps();
}
mMap = googleMap;
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
if (isProviderAvailable() && (provider != null))
{
locateCurrentPosition();
}
setupBottomNavigationView();
}
public void locateCurrentPosition()
{
int status = getPackageManager().checkPermission(Manifest.permission.ACCESS_COARSE_LOCATION,
getPackageName());
if (status == PackageManager.PERMISSION_GRANTED) {
location = mLocationManager.getLastKnownLocation(provider);
updateWithNewLocation(location);
// mLocationManager.addGpsStatusListener(this);
long minTime = 5000;// ms
float minDist = 5.0f;// meter
mLocationManager.requestLocationUpdates(provider, minTime, minDist, this);
l=location;
if(l != null)
placeAutoComplete.setBoundsBias(new LatLngBounds(new LatLng(l.getLatitude(),l.getLongitude()),new LatLng(l.getLatitude()+2,l.getLongitude()+2)));
}
}
private void updateWithNewLocation(Location location) {
if (location != null && provider != null) {
double lng = location.getLongitude();
double lat = location.getLatitude();
if(!flag)
addBoundaryToCurrentPosition(lat, lng);
CameraPosition camPosition = new CameraPosition.Builder()
.target(new LatLng(lat, lng)).zoom(12f).build();
if (mMap != null && !flag)
mMap.animateCamera(CameraUpdateFactory
.newCameraPosition(camPosition));
} else {
Log.d("Location error", "Something went wrong");
}
}
//*****************************************************************//
private void addBoundaryToCurrentPosition(double lat, double lang) {
Geocoder myLocation = new Geocoder(getApplicationContext(), Locale.getDefault());
String addressStr = "";
try {
List<Address> myList = myLocation.getFromLocation(lat,lang, 1);
Address address;
address = (Address) myList.get(0);
Log.d("LOCC", address.getAddressLine(0));
addressStr += address.getAddressLine(0) ;
} catch (IOException e) {
e.printStackTrace();
}
MarkerOptions mMarkerOptions = new MarkerOptions();
mMarkerOptions.position(new LatLng(lat, lang));
mMarkerOptions.icon(BitmapDescriptorFactory
.fromResource(R.drawable.ic_location));
mMarkerOptions.anchor(0.5f, 0.5f);
if( mOptions == null)
{
mOptions = new CircleOptions()
.center(new LatLng(lat, lang)).radius(5000)
.strokeColor(0x110000FF).strokeWidth(1).fillColor(0x110000FF);
c = mMap.addCircle(mOptions);
}
else {
c.remove();
mOptions = new CircleOptions()
.center(new LatLng(lat, lang)).radius(5000)
.strokeColor(0x110000FF).strokeWidth(1).fillColor(0x110000FF);
c = mMap.addCircle(mOptions);
}
if (mCurrentPosition != null)
mCurrentPosition.remove();
mCurrentPosition = mMap.addMarker(mMarkerOptions);
mCurrentPosition.setTitle(addressStr);
}
private boolean isProviderAvailable() {
mLocationManager = (LocationManager) getSystemService(
Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
provider = mLocationManager.getBestProvider(criteria, true);
if (mLocationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
provider = LocationManager.NETWORK_PROVIDER;
return true;
}
if (mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
provider = LocationManager.GPS_PROVIDER;
return true;
}
if (provider != null) {
return true;
}
return false;
}
#Override
public void onLocationChanged(Location location) {
updateWithNewLocation(location);
}
#Override
public void onProviderDisabled(String provider) {
updateWithNewLocation(null);
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
switch (status) {
case LocationProvider.OUT_OF_SERVICE:
break;
case LocationProvider.TEMPORARILY_UNAVAILABLE:
break;
case LocationProvider.AVAILABLE:
break;
}
}
public void buildAlertMessageNoGps()
{
new MaterialDialog.Builder(this)
.title("Location")
.content("Enable Location")
.positiveText("Enable GPS!")
.negativeText("No, Thanks!")
.cancelable(false)
.positiveColor(Color.rgb(232,42,42))
.negativeColor(Color.rgb(232,42,42))
.onPositive(new MaterialDialog.SingleButtonCallback() {
#Override
public void onClick(#NonNull MaterialDialog dialog, #NonNull DialogAction which) {
Intent myIntent = new Intent( Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(myIntent);
}
})
.onNegative(new MaterialDialog.SingleButtonCallback() {
#Override
public void onClick(#NonNull MaterialDialog dialog, #NonNull DialogAction which) {
Toast.makeText(MainActivity.this, "Location Access Required!!", Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
})
.show();
}
//endregion
}
As you can see in the method addBoundaryToCurrentPosition(), below that "//******//" (it's a part of MainActivity), I've set a marker at current location towards the end of the method which is supposed to refresh after every 5000ms.
Moreover I have a bottomNavigationView which is supposed to show nearby places. It's code is as below:-
public class BottomNavigationViewHelper {
private static final String TAG = "BottomNavigationViewHel";
static Menu menu;
static MenuItem menuItem;
public static Location l;
public static void setupBottomNavigationView(BottomNavigationViewEx bottomNavigationViewEx)
{
Log.d(TAG, "setupBottomNavigationView: setting up BottomNavView");
bottomNavigationViewEx.enableAnimation(true);
bottomNavigationViewEx.enableItemShiftingMode(false);
bottomNavigationViewEx.enableShiftingMode(false);
bottomNavigationViewEx.setTextVisibility(true);
menu = bottomNavigationViewEx.getMenu();
}
public static void enableNavigation(final Context context, BottomNavigationViewEx view)
{
view.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.ic_hospital:
menuItem = menu.getItem(0);
menuItem.setChecked(true);
String Hospital = "hospital";
Log.d("onClick", "Button is Clicked");
MainActivity.mMap.clear();
locate(MainActivity.location);
MainActivity.markerAlready = false;
MainActivity.placeAutoComplete.setText("Hospitals near me");
String urlhospital = getUrl(MainActivity.l.getLatitude(), MainActivity.l.getLongitude(), Hospital);
Object[] DataTransferhospital = new Object[2];
DataTransferhospital[0] = MainActivity.mMap;
DataTransferhospital[1] = urlhospital;
Log.d("onClick", urlhospital);
GetNearbyPlacesData getNearbyPlacesDatahospital = new GetNearbyPlacesData();
getNearbyPlacesDatahospital.execute(DataTransferhospital);
break;
case R.id.ic_police:
menuItem = menu.getItem(1);
menuItem.setChecked(true);
String Police = "police";
Log.d("onClick", "Button is Clicked");
MainActivity.mMap.clear();
locate(MainActivity.location);
MainActivity.markerAlready = false;
MainActivity.placeAutoComplete.setText("Police Stations near me");
String urlpolice = getUrl(MainActivity.l.getLatitude(), MainActivity.l.getLongitude(), Police);
Object[] DataTransferpolice = new Object[2];
DataTransferpolice[0] = MainActivity.mMap;
DataTransferpolice[1] = urlpolice;
Log.d("onClick", urlpolice);
GetNearbyPlacesData getNearbyPlacesDatapolice = new GetNearbyPlacesData();
getNearbyPlacesDatapolice.execute(DataTransferpolice);
break;
case R.id.ic_food:
menuItem = menu.getItem(2);
menuItem.setChecked(true);
String Restaurant = "restaurant";
Log.d("onClick", "Button is Clicked");
MainActivity.mMap.clear();
MainActivity.markerAlready = false;
MainActivity.placeAutoComplete.setText("Restaurants near me");
locate(MainActivity.location);
String urlrestaurant = getUrl(MainActivity.l.getLatitude(), MainActivity.l.getLongitude(), Restaurant);
Object[] DataTransferrestaurant = new Object[2];
DataTransferrestaurant[0] = MainActivity.mMap;
DataTransferrestaurant[1] = urlrestaurant;
Log.d("onClick", urlrestaurant);
GetNearbyPlacesData getNearbyPlacesDatarestaurant = new GetNearbyPlacesData();
getNearbyPlacesDatarestaurant.execute(DataTransferrestaurant);
break;
}
return false;
}
});
}
private static String getUrl(double latitude, double longitude, String nearbyPlace) {
StringBuilder googlePlacesUrl = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
googlePlacesUrl.append("location=" + latitude + "," + longitude);
googlePlacesUrl.append("&radius=" + 10000);
googlePlacesUrl.append("&type=" + nearbyPlace);
googlePlacesUrl.append("&sensor=true");
googlePlacesUrl.append("&key=" + "AIzaSyATuUiZUkEc_UgHuqsBJa1oqaODI-3mLs0");
Log.d("getUrl", googlePlacesUrl.toString());
return (googlePlacesUrl.toString());
}
public static void locate(Location location) {
if (location != null) {
double lng = location.getLongitude();
double lat = location.getLatitude();
CameraPosition camPosition = new CameraPosition.Builder()
.target(new LatLng(lat, lng)).zoom(12f).build();
if (MainActivity.mMap != null) {
MainActivity.mMap.animateCamera(CameraUpdateFactory
.newCameraPosition(camPosition));
} else {
Log.d("Location error", "Something went wrong");
}
final MarkerOptions mMarkerOptions = new MarkerOptions();
mMarkerOptions.position(new LatLng(lat, lng));
mMarkerOptions.icon(BitmapDescriptorFactory
.fromResource(R.drawable.ic_location));
final Marker m = MainActivity.mMap.addMarker(mMarkerOptions);
CircleOptions mOptions;
final Circle c;
mOptions = new CircleOptions()
.center(new LatLng(lat, lng)).radius(5000)
.strokeColor(0x110000FF).strokeWidth(1).fillColor(0x110000FF);
c = MainActivity.mMap.addCircle(mOptions);
}
}
}
In this I've created a method locate() , towards the end, which is called in switch cases. It fetches current location from MainActivity and sets marker after clearing the map.
The problem that I face is that when I click one of the buttons in BottomNavView, at first only one marker for current location is visible (that by BottomNav) but after some random time, marker by MainActivity also starts showing up. Hence two markers for current location show up.
I've tried creating a handler to remove marker by bottomNav after 5000ms but marker of MainActivity starts showing after random amount of time.
How do I prevent two markers from showing up simultaneously while at the same time ensuring that at least on of the markers is visible at all times??
First, you need to change your Marker variable name to more a readable name because it makes you confuse:
private Marker mCurrentPosition = null;
Marker marker;
What current position means? is it location or marker? What is marker? I think the better name for the above code is following:
private Marker mMarkerCurrentPosition = null;
private Marker mMarkerSelectedPlace;
Second, you adding a marker with BottomNavigationViewHelper.locate without removing the previous marker:
public static void locate(Location location) {
...
final Marker m = MainActivity.mMap.addMarker(mMarkerOptions);
...
}
Furthermore, you should change your code so you can't access the MainActivity variable outside the class by modifying the method parameters to something like this:
public static void locate(GoogleMap map, Location location) {
}
Last, don't use GoogleMap.clear() to clear your markers. Instead, try to always removing all the markers added to the GoogleMap one by one. You can achieve it by always adding the item to a list. Then, you can remove each item by iterating the lists. For example:
List<Marker> markers;
// add 3 marker
markers.add(mMap.addMarker(mMarkerOptions));
markers.add(mMap.addMarker(mMarkerOptions));
markers.add(mMap.addMarker(mMarkerOptions));
// remove markers
for (Iterator<Marker> it = markers.listIterator(); it.hasNext(); ) {
Marker marker = iter.next();
// remove the marker from map
marker.remove();
// remove marker from list
iter.remove();
}
Related
so, after a year or two i started this project again... by the time it was outdated it worked fine... but since android x came out i wanted to upgrade my application and got stuck on a error i find it funny...
quick brief, i have button that makes me online / offline.. on pressing the button the map should zoom at my curr. location and add a marker.. but here comes the error :
Logcat:
Process: com.app.mk.transport, PID: 22142
java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.android.gms.maps.model.Marker com.google.android.gms.maps.GoogleMap.addMarker(com.google.android.gms.maps.model.MarkerOptions)' on a null object reference
at com.app.mk.transport.DriverHome$16$1$1.onComplete(DriverHome.java:1110)
at com.firebase.geofire.GeoFire$2.onComplete(GeoFire.java:178)
at com.google.firebase.database.core.Repo$6.run(com.google.firebase:firebase-database##19.2.0:404)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
DriverHome.java ( Not The whole code ):
private void setUpAutocomplete() {
AutocompleteSupportFragment autocompleteFragment = new AutocompleteSupportFragment();
// final AutocompleteSupportFragment autocompleteFragment;
// autocompleteFragment = (AutocompleteSupportFragment) getSupportFragmentManager().findFragmentById(R.id.autocomplete_fragment);
autocompleteFragment.setCountry("MK");
if (!Places.isInitialized()) {
Places.initialize(getApplicationContext(), getResources().getString(R.string.google_open_api));
}
autocompleteFragment.setPlaceFields(Arrays.asList(Place.Field.ADDRESS));
autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(#NonNull Place place) {
if (location_switch.isChecked()) {
destination = place.getAddress();
destination = destination.replace(" ", "+");
if (destination.contains("+(FYROM)")) {
destination = destination.replace("+(FYROM)", "");
}
mMap.clear();
getDirection();
}
}
#Override
public void onError(#NonNull Status status) {
Toast.makeText(DriverHome.this, "" + status.toString(), Toast.LENGTH_SHORT).show();
Log.i("MITKASIN", "An error occurred: " + status);
}
});
}
#Override
public void onBackPressed() {
DrawerLayout drawer = findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.driver_home, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_trip_history) {
// Handle the camera action
} else if (id == R.id.nav_way_bill) {
} else if (id == R.id.nav_help) {
} else if (id == R.id.nav_settings) {
} else if (id == R.id.nav_update_Info) {
showDialogUpdateInfo();
} else if (id == R.id.nav_sign_out) {
signOut();
}
DrawerLayout drawer = findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private void showDialogUpdateInfo() {
final AlertDialog.Builder alertDialog = new AlertDialog.Builder(DriverHome.this);
alertDialog.setTitle("Update Information");
alertDialog.setMessage("Please fill in the informations");
LayoutInflater inflater = this.getLayoutInflater();
View dialog_change_pwd = inflater.inflate(R.layout.layout_update_information, null);
final TextInputEditText edt_Name = dialog_change_pwd.findViewById(R.id.edtName);
final TextInputEditText edt_Phone = dialog_change_pwd.findViewById(R.id.edtPhone);
final ImageView image_upload = (ImageView) dialog_change_pwd.findViewById(R.id.image_upload);
image_upload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
chooseImage();
}
});
alertDialog.setView(dialog_change_pwd);
alertDialog.setPositiveButton("UPDATE", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
final android.app.AlertDialog waitingDialog = new SpotsDialog.Builder()
.setContext(DriverHome.this)
.setTheme(R.style.Orange)
.setMessage(R.string.waitingDialog_title)
.setCancelable(false)
.build();
waitingDialog.show();
AccountKit.getCurrentAccount(new AccountKitCallback<Account>() {
#Override
public void onSuccess(Account account) {
String name = edt_Name.getText().toString();
String phone = edt_Phone.getText().toString();
Map<String, Object> updateInfo = new HashMap<>();
if (!TextUtils.isEmpty(name))
updateInfo.put("name", name);
if (!TextUtils.isEmpty(phone))
updateInfo.put("phone", phone);
DatabaseReference driverInformations = FirebaseDatabase.getInstance().getReference(Common.user_driver_tbl);
driverInformations.child(account.getId())
.updateChildren(updateInfo)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
waitingDialog.dismiss();
if (task.isSuccessful()) {
Toast.makeText(DriverHome.this, "Information updated!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(DriverHome.this, "Information update Failed!", Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
public void onError(AccountKitError accountKitError) {
}
});
}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
private void chooseImage() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), Common.PICK_IMAGE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == Common.PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri saveUri = data.getData();
if (saveUri != null) {
final ProgressDialog mDialog = new ProgressDialog(this);
mDialog.setMessage("Uploading...");
mDialog.show();
String imageName = UUID.randomUUID().toString();
final StorageReference imageFolder = storageReference.child("images/" + imageName);
imageFolder.putFile(saveUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
mDialog.dismiss();
Toast.makeText(DriverHome.this, "Uploaded !", Toast.LENGTH_SHORT).show();
imageFolder.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(final Uri uri) {
AccountKit.getCurrentAccount(new AccountKitCallback<Account>() {
#Override
public void onSuccess(Account account) {
Map<String, Object> avatarUpdate = new HashMap<>();
avatarUpdate.put("avatarUrl", uri.toString());
DatabaseReference driverInformations = FirebaseDatabase.getInstance().getReference(Common.user_driver_tbl);
driverInformations.child(account.getId())
.updateChildren(avatarUpdate)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(DriverHome.this, "Uploaded!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(DriverHome.this, "Upload error !", Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
public void onError(AccountKitError accountKitError) {
}
});
}
});
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0 * taskSnapshot.getBytesTransferred() / taskSnapshot.getTotalByteCount());
mDialog.setMessage("Upliaded " + progress + "%");
}
});
}
}
}
private void signOut() {
AlertDialog.Builder builder;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
builder = new AlertDialog.Builder(this, android.R.style.Theme_Material_Dialog_Alert);
else
builder = new AlertDialog.Builder(this);
builder.setMessage("Do you want to logout?")
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// Paper.init(this);
AccountKit.logOut();
Intent intent = new Intent(DriverHome.this, MainActivity.class);
startActivity(intent);
finish();
}
})
.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.show();
}
private float getBearing(LatLng startPosition, LatLng endPosition) {
double lat = Math.abs(startPosition.latitude - endPosition.latitude);
double lng = Math.abs(startPosition.longitude - endPosition.longitude);
if (startPosition.latitude < endPosition.latitude && startPosition.longitude < endPosition.longitude)
return (float) (Math.toDegrees(Math.atan(lng / lat)));
else if (startPosition.latitude >= endPosition.latitude && startPosition.longitude < endPosition.longitude)
return (float) ((90 - Math.toDegrees(Math.atan(lng / lat))) + 90);
else if (startPosition.latitude >= endPosition.latitude && startPosition.longitude >= endPosition.longitude)
return (float) (Math.toDegrees(Math.atan(lng / lat)) + 180);
else if (startPosition.latitude < endPosition.latitude && startPosition.longitude >= endPosition.longitude)
return (float) ((90 - Math.toDegrees(Math.atan(lng / lat))) + 270);
return -1;
}
private void updateFirebaseToken() {
AccountKit.getCurrentAccount(new AccountKitCallback<Account>() {
#Override
public void onSuccess(Account account) {
FirebaseDatabase db = FirebaseDatabase.getInstance();
DatabaseReference tokens = db.getReference(Common.token_tbl);
Token token = new Token(FirebaseInstanceId.getInstance().getToken());
tokens.child(account.getId())
.setValue(token);
}
#Override
public void onError(AccountKitError accountKitError) {
}
});
}
private void getDirection() {
currentPosition = new LatLng(Common.mLastLocation.getLatitude(), Common.mLastLocation.getLongitude());
String requestApi = null;
try {
requestApi = "https://maps.googleapis.com/maps/api/directions/json?" +
"mode=driving&" +
"transit_routing_reference=less_driving&" +
"origin=" + currentPosition.latitude + "," + currentPosition.longitude + "&" +
"destination=" + destination + "&" +
"key=" + getResources().getString(R.string.google_direction_api);
Log.i("MITKASIN", requestApi);
mServices.getPath(requestApi)
.enqueue(new Callback<String>() {
#Override
public void onResponse(Call<String> call, Response<String> response) {
try {
JSONObject jsonObject = new JSONObject(response.body());
JSONArray jsonArray = jsonObject.getJSONArray("routes");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject route = jsonArray.getJSONObject(i);
JSONObject poly = route.getJSONObject("overview_polyline");
String polyline = poly.getString("points");
polyLineList = decodePoly(polyline);
}
if (!polyLineList.isEmpty()) {
LatLngBounds.Builder builder = new LatLngBounds.Builder();
for (LatLng latLng : polyLineList)
builder.include(latLng);
LatLngBounds bounds = builder.build();
CameraUpdate mCameraUpdate = CameraUpdateFactory.newLatLngBounds(bounds, 1);
mMap.animateCamera(mCameraUpdate);
// mMap.getUiSettings().setAllGesturesEnabled(true);
}
polylineOptiuons = new PolylineOptions();
polylineOptiuons.color(Color.GRAY);
polylineOptiuons.width(5);
polylineOptiuons.startCap(new SquareCap());
polylineOptiuons.endCap(new SquareCap());
polylineOptiuons.jointType(JointType.ROUND);
polylineOptiuons.addAll(polyLineList);
greyPolyline = mMap.addPolyline(polylineOptiuons);
blackPolylineOptions = new PolylineOptions();
blackPolylineOptions.color(Color.BLACK);
blackPolylineOptions.width(7);
blackPolylineOptions.startCap(new SquareCap());
blackPolylineOptions.endCap(new SquareCap());
blackPolylineOptions.jointType(JointType.ROUND);
blackPolyline = mMap.addPolyline(blackPolylineOptions);
if (!polyLineList.isEmpty()) {
mMap.addMarker(new MarkerOptions()
.position(polyLineList.get(polyLineList.size() - 1))
.title("Pickup Location"));
}
//Animation
ValueAnimator polyLineAnimator = ValueAnimator.ofInt(0, 100);
polyLineAnimator.setDuration(2000);
polyLineAnimator.setInterpolator(new LinearInterpolator());
polyLineAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
List<LatLng> points = greyPolyline.getPoints();
int percentValue = (int) valueAnimator.getAnimatedValue();
int size = points.size();
int newPoints = (int) (size * (percentValue / 100.0f));
List<LatLng> p = points.subList(0, newPoints);
blackPolyline.setPoints(p);
}
});
polyLineAnimator.start();
carMarker = mMap.addMarker(new MarkerOptions()
.position(currentPosition)
.flat(true)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.car)));
handler = new Handler();
index = -1;
next = 1;
handler.postDelayed(drawPathRunnable, 2000);
// mMap.getUiSettings().setScrollGesturesEnabled(true);
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Call<String> call, Throwable t) {
Toast.makeText(DriverHome.this, "" + t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
} catch (Exception e) {
e.printStackTrace();
}
// mMap.getUiSettings().setScrollGesturesEnabled(true);
}
private List decodePoly(String encoded) {
List poly = new ArrayList();
int index = 0, len = encoded.length();
int lat = 0, lng = 0;
while (index < len) {
int b, shift = 0, result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lat += dlat;
shift = 0;
result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lng += dlng;
LatLng p = new LatLng((((double) lat / 1E5)),
(((double) lng / 1E5)));
poly.add(p);
}
return poly;
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case MY_PEMISSION_REQUEST_CODE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
buildLocationCallback();
buildLocationRequest();
if (location_switch.isChecked())
displayLocation();
}
}
}
private void setUpLocation() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
//Request runtime permission
ActivityCompat.requestPermissions(this, new String[]{
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION
}, MY_PEMISSION_REQUEST_CODE);
} else {
buildLocationRequest();
buildLocationCallback();
if (location_switch.isChecked())
displayLocation();
}
}
private void buildLocationCallback() {
locationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
for (Location location : locationResult.getLocations()) {
Common.mLastLocation = location;
}
displayLocation();
}
};
}
private void buildLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(UPDATE_INTERVAL);
mLocationRequest.setFastestInterval(FATEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setSmallestDisplacement(DISPLACEMENT);
}
private void displayLocation() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
fusedLocationProviderClient.getLastLocation()
.addOnSuccessListener(new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
Common.mLastLocation = location;
if (Common.mLastLocation != null) {
if (location_switch.isChecked()) {
final double latitude = Common.mLastLocation.getLatitude();
final double longitude = Common.mLastLocation.getLongitude();
//Update to Firebase
AccountKit.getCurrentAccount(new AccountKitCallback<Account>() {
#Override
public void onSuccess(Account account) {
geoFire.setLocation(account.getId(), new GeoLocation(latitude, longitude), new GeoFire.CompletionListener() {
#Override
public void onComplete(String key, DatabaseError error) {
if (mCurrent != null) {
mCurrent.remove();
}
mCurrent = mMap.addMarker(new MarkerOptions()
.position(new LatLng(latitude, longitude))
.title("Your Location"));
// Move camera to this position when set to online!
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude, longitude), 14.5f));
// Draw animation rotate marker
// rotateMarker(mCurrent, 360, mMap);
}
});
}
#Override
public void onError(AccountKitError accountKitError) {
}
});
}
} else {
Log.d("ERROR", "Cannot get your location");
}
}
});
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mMap.setTrafficEnabled(false);
mMap.setIndoorEnabled(false);
mMap.setBuildingsEnabled(false);
mMap.getUiSettings().setZoomControlsEnabled(false);
try {
// Customise the styling of the base map using a JSON object defined
// in a raw resource file.
boolean success = googleMap.setMapStyle(
MapStyleOptions.loadRawResourceStyle(
this, R.raw.style_json));
if (!success) {
Log.e("Mitkasin", "Style parsing failed.");
}
} catch (Resources.NotFoundException e) {
Log.e("Mitkasin", "Can't find style. Error: ", e);
}
if (ActivityCompat.checkSelfPermission(DriverHome.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(DriverHome.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
buildLocationRequest();
buildLocationCallback();
fusedLocationProviderClient.requestLocationUpdates(mLocationRequest, locationCallback, Looper.myLooper());
}
}
excuse me for the nasty code tho :D
and sorry if its a dumb question but idk what im missing here ...
You need to call your displayLocation and getDirection methods only after the map has been initialized (i.e. mMap = googleMap). Check out related Null Pointer Exception and getMapAsync Error
E.g.:
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mMap.setTrafficEnabled(false);
mMap.setIndoorEnabled(false);
mMap.setBuildingsEnabled(false);
mMap.getUiSettings().setZoomControlsEnabled(false);
try {
// Customise the styling of the base map using a JSON object defined
// in a raw resource file.
boolean success = googleMap.setMapStyle(
MapStyleOptions.loadRawResourceStyle(
this, R.raw.style_json));
if (!success) {
Log.e("Mitkasin", "Style parsing failed.");
}
} catch (Resources.NotFoundException e) {
Log.e("Mitkasin", "Can't find style. Error: ", e);
}
displayLocation();
getDirection();
}
Hope this helps!
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
i have write an android program to show google map and show the current location.
Here is a part of the code , please see:
public class MapActivity extends FragmentActivity implements OnMapReadyCallback,LocationListener {
public static GoogleMap googleMap;
private Geocoder geoCoder;
private ArrayAdapter<String> adapter;
private List<Address> addressSearchList;
private static final int MY_PERMISSION_ACCESS_COARSE_LOCATION = 11;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_map);
Log.d("Test","success0");
geoCoder = new Geocoder(MapActivity.this, Locale.getDefault());
TextView textView = (TextView) findViewById(R.id.textTitle);
textView.setText(getString(R.string.TITLE_REPORT));
ListView list = (ListView) findViewById(R.id.listView1);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
list.setAdapter(adapter);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String addressName = adapter.getItem(position);
adapter.clear();
adapter.notifyDataSetChanged();
ListView list = (ListView) findViewById(R.id.listView1);
list.setVisibility(View.GONE);
if ((addressSearchList == null) || (position >= addressSearchList.size()))
return;
Address address = addressSearchList.get(position);
googleMap.clear();
LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());
Marker marker = googleMap.addMarker(new MarkerOptions()
.position(latLng)
.title(addressName)
.snippet(getString(R.string.CONFIRM))
);
marker.showInfoWindow();
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
}
});
ImageView imageView = (ImageView) findViewById(R.id.btnCancelSearch);
imageView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
EditText editText = (EditText) findViewById(R.id.editText1);
editText.setText("");
editText.clearFocus();
adapter.clear();
adapter.notifyDataSetChanged();
ListView list = (ListView) findViewById(R.id.listView1);
list.setVisibility(View.GONE);
try {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
} catch (Exception e) {
}
}
});
EditText editText = (EditText) findViewById(R.id.editText1);
editText.setOnEditorActionListener(new OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if ((actionId == EditorInfo.IME_ACTION_SEARCH) && (v.getText().length() > 0)) {
//Log.d("TEST", "onEditorAction");
try {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
} catch (Exception e) {
}
String locationName = v.getText().toString();
new SearchAddressTask(locationName).execute();
}
return false;
}
});
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (status != ConnectionResult.SUCCESS) {
//Log.d("TEST", "not success");
} else {
SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentByTag("mapClinic");
Log.d("Test","success1");
fm.getMapAsync(MapActivity.this);
Log.d("Test","success2");
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
///final GoogleMap googleMaps=googleMap;
// Your code heregoogleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
//Log.d("TEST", clinic.getLongitude() + ":" + clinic.getLatitude());
double latitude = 22.309994;
double longitude = 114.226036;
LatLng latLng = new LatLng(latitude, longitude);
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(10));
googleMap.getUiSettings().setRotateGesturesEnabled(false);
googleMap.getUiSettings().setCompassEnabled(false);
final GoogleMap googleMapF= googleMap;
googleMap.setOnMapClickListener(new OnMapClickListener() {
#Override
public void onMapClick(LatLng point) {
googleMapF.clear();
String address = "";
//Geocoder geoCoder = new Geocoder(MapActivity.this, Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocation(point.latitude, point.longitude, 1);
if (addresses.size() <= 0)
return;
//address = addresses.get(0).getAddressLine(1);
StringBuilder longAddress = new StringBuilder();
String temp;
int j = 0;
while ((temp = addresses.get(0).getAddressLine(j++)) != null) {
longAddress.append(temp);
}
address = longAddress.toString();
//EditText editText = (EditText) findViewById(R.id.textLocation);
//editText.setText(addresses.get(0).getFeatureName());
/*addresses = geoCoder.getFromLocationName("�Ի��{", 10);
if (addresses.size() <= 0) {
Log.d("TEST", "can't find");
}
else {
Log.d("TEST", addresses.toString());
Log.d("TEST", "find it");
}*/
} catch (IOException e) {
//e.printStackTrace();
}
Marker marker = googleMapF.addMarker(new MarkerOptions()
.position(point)
.title(address)
.snippet(getString(R.string.CONFIRM))
);
marker.showInfoWindow();
}
});
googleMap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
LatLng point = marker.getPosition();
Intent intent = new Intent();
intent.putExtra("LatLng", point);
setResult(RESULT_OK, intent);
finish();
}
});
if( ContextCompat.checkSelfPermission( this, android.Manifest.permission.ACCESS_COARSE_LOCATION ) != PackageManager.PERMISSION_GRANTED ) {
Log.d("Test","success3...1");
ActivityCompat.requestPermissions( this, new String[] { android.Manifest.permission.ACCESS_COARSE_LOCATION },
MY_PERMISSION_ACCESS_COARSE_LOCATION );
}
String provider = locationManager.getBestProvider(criteria, false);
if (provider == null){
Log.d("Test","success3");
return;
}
Log.d("Test","success3.1");
Location location = getLastKnownLocationS();
//Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
Log.d("Test", "success4");
if (location != null) {
Log.d("Test", "success5");
LatLng point = new LatLng(location.getLatitude(), location.getLongitude());
Log.d("Test", "success6");
googleMap.clear();
String address = "";
Geocoder geoCoder = new Geocoder(MapActivity.this, Locale.getDefault());
Log.d("Test", "success7");
try {
List<Address> addresses = geoCoder.getFromLocation(point.latitude, point.longitude, 1);
if (addresses.size() <= 0)
return;
//address = addresses.get(0).getAddressLine(1);
StringBuilder longAddress = new StringBuilder();
String temp;
int j = 0;
Log.d("Test", "success8");
while ((temp = addresses.get(0).getAddressLine(j++)) != null) {
longAddress.append(temp);
}
address = longAddress.toString();
Log.d("Test", "success9");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.d("Test", "success10");
Marker marker = googleMap.addMarker(new MarkerOptions()
.position(point)
.title(address)
.snippet(getString(R.string.CONFIRM))
);
Log.d("Test", "success11");
marker.showInfoWindow();
Log.d("Test", "success12.1");
onLocationChanged(location);
Log.d("Test", "success12.2");
}
locationManager.requestLocationUpdates(provider, 10000, 0, this);
Log.d("Test", "success13");
}
private Location getLastKnownLocationS() {
LocationManager mLocationManager = (LocationManager)getApplicationContext().getSystemService(LOCATION_SERVICE);
List<String> providers = mLocationManager.getProviders(true);
Location bestLocation = null;
if( ContextCompat.checkSelfPermission( this, android.Manifest.permission.ACCESS_COARSE_LOCATION ) != PackageManager.PERMISSION_GRANTED ) {
Log.d("Test","success3...2");
ActivityCompat.requestPermissions( this, new String[] { android.Manifest.permission.ACCESS_COARSE_LOCATION },
MY_PERMISSION_ACCESS_COARSE_LOCATION );
}
for (String provider : providers) {
Location l = mLocationManager.getLastKnownLocation(provider);
if (l == null) {
continue;
}
if (bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy()) {
// Found best last known location: %s", l);
bestLocation = l;
}
}
Log.d("Test","success_async");
return bestLocation;
}
Updated the error parts,please help ,thanks for reminds the error occur in onLocationChanged method, Thanks.
Updated the error parts,please help ,thanks for reminds the error occur in onLocationChanged method, Thanks
#Override
public void onLocationChanged(Location location) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
Log.d("Test","onLocationChange");
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
}
And debugger have below error:
10-26 08:47:12.493 26361-26361/com.afcd.redtidesystem E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.afcd.redtidesystem, PID: 26361
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.maps.GoogleMap.moveCamera(com.google.android.gms.maps.CameraUpdate)' on a null object reference
at com.afcd.redtidesystem.MapActivity.onLocationChanged(MapActivity.java:379)
at com.afcd.redtidesystem.MapActivity.onMapReady(MapActivity.java:329)
at com.google.android.gms.maps.zzaj.zza(Unknown Source)
at com.google.android.gms.maps.internal.zzaq.onTransact(Unknown Source)
at android.os.Binder.transact(Binder.java:499)
at gl.b(:com.google.android.gms.DynamiteModulesB#11518470:20)
at com.google.android.gms.maps.internal.bf.a(:com.google.android.gms.DynamiteModulesB#11518470:5)
at com.google.maps.api.android.lib6.impl.bc.run(:com.google.android.gms.DynamiteModulesB#11518470:5)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
1-Add these line to your onCreate() method if you are getting your map from map fragment
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
2- Uncomment your first line in onMapReady() method
i have changed your code ,try this one , if error comes in onLocationChangd()
#Override public void onLocationChanged(Location location)
{
if(Location!=null)
{
// You code here
}
}
try this
CameraUpdate center=
CameraUpdateFactory.newLatLng(new LatLng( 73.35687586412547,
-45.77172998180484));
CameraUpdate zoom=CameraUpdateFactory.zoomTo(10);
map.moveCamera(center);
map.animateCamera(zoom);
let me know if any query
i am using firebase realtime database to store two types of users for two apps, users A will use App A to update their info and such, and users B will use app B to search nearby users A that they need their services from. I have been successful in uploading user A info from app A, even with location using geofire, now what i need is to show a list of usera A inside app B that are nearby. please help with answers regarding best ways/practices and if this here isnt the best method then suggestions are welcome..... thanks
public class MainActivity extends AppCompatActivity implements LocationListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener,Home.OnFragmentInteractionListener
{
public static String userId;
public static final int MY_REQUEST_PERMISSION_LOCATION = 1;
private long UPDATE_INTERVAL = 10 * 1000; /* 10 secs */
private long FASTEST_INTERVAL = 2000; /* 2 sec */
private static final String TAG_HOME = "home";
private static final String TAG_MY_PREF = "my__preferences";
private static final String TAG_NOTIFICATIONS = "notifications";
private static final String TAG_SETTINGS = "settings";
public static String CURRENT_TAG = TAG_HOME;
private String [] activityTitles;
SharedPreferences sharedPreferences;
String name;
String imageURI;
private boolean shouldLoadHomeFragOnBackPress = true;
private Handler mHandler;
Toolbar toolbar;
DrawerLayout drawer;
NavigationView navigationView;
private View navHeader;
private static int navItemIndex = 0;
private ImageView imgProfile;
private TextView txtName, txtEmail;
private DatabaseReference mDatabase;
GoogleApiClient mGoogleApiClient;
private boolean isPermissionGranted = false;
private LocationRequest mLocationRequest;
public double lat, lng;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById (R.id.toolbar);
setSupportActionBar(toolbar);
mHandler = new Handler ();
mGoogleApiClient = new GoogleApiClient . Builder (this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).build();
activityTitles = getResources().getStringArray(R.array.nav_item_activity_titles);
drawer = (DrawerLayout) findViewById (R.id.drawer_layout);
navigationView = (NavigationView) findViewById (R.id.nav_view);
navHeader = navigationView.getHeaderView(0);
txtName = (TextView) navHeader . findViewById (R.id.username);
imgProfile = (ImageView) navHeader . findViewById (R.id.smallProfile);
setUpNavigationView();
if (savedInstanceState == null) {
navItemIndex = 0;
CURRENT_TAG = TAG_HOME;
loadHomeFragment();
}
sharedPreferences = getSharedPreferences(UserData, Context.MODE_PRIVATE);
name = sharedPreferences.getString(full_name, null);
imageURI = sharedPreferences.getString(imagesrc, null);
upload();
Glide.with(MainActivity.this).load(Uri.parse(imageURI)).into(imgProfile);
loadNavHeader();
}
public void loadNavHeader() {
txtName.setText(name);
}
private void loadHomeFragment() {
selectNavMenu();
// set toolbar title
setToolbarTitle();
// if user select the current navigation menu again, don't do anything
// just close the navigation drawer
if (getSupportFragmentManager().findFragmentByTag(CURRENT_TAG) != null) {
drawer.closeDrawers();
// show or hide the fab button
return;
}
Runnable mPendingRunnable = new Runnable() {
#Override
public void run() {
// update the main content by replacing fragments
Fragment fragment = getHomeFragment ();
FragmentTransaction fragmentTransaction = getSupportFragmentManager ().beginTransaction();
fragmentTransaction.setCustomAnimations(android.R.anim.fade_in,
android.R.anim.fade_out);
fragmentTransaction.replace(R.id.frame, fragment, CURRENT_TAG);
fragmentTransaction.commitAllowingStateLoss();
}
};
if (mPendingRunnable != null) {
mHandler.post(mPendingRunnable);
}
//Closing drawer on item click
drawer.closeDrawers();
// refresh toolbar menu
invalidateOptionsMenu();
}
private void upload() {
userId = sharedPreferences.getString("UID", null);
String username = sharedPreferences . getString (full_name, null);
String photoUri = sharedPreferences . getString (imagesrc, null);
mDatabase = FirebaseDatabase.getInstance().getReference("users/B");
mDatabase.child(userId).child("name").setValue(username);
mDatabase.child(userId).child("imageuri").setValue(photoUri);
}
#Override
public void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
#Override
public void onStop() {
super.onStop();
if (isPermissionGranted) {
mGoogleApiClient.disconnect();
}
}
public void onPause() {
if (isPermissionGranted)
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
super.onPause();
}
public void onResume() {
if (isPermissionGranted) {
if (mGoogleApiClient.isConnected())
startLocationUpdates();
}
super.onResume();
}
private Fragment getHomeFragment() {
switch(navItemIndex) {
case 0:
// home
Home home = new Home();
return home;
case 1:
//subjects
MYPref myPref = new MYPref();
return myPref;
case 2:
//
NotificationFragment notificationsFragment = new NotificationFragment();
return notificationsFragment;
case 3:
Settings settings = new Settings();
return settings;
default:
return new Home ();
}
}
private void setToolbarTitle() {
getSupportActionBar().setTitle(activityTitles[navItemIndex]);
}
private void selectNavMenu() {
navigationView.getMenu().getItem(navItemIndex).setChecked(true);
}
private void setUpNavigationView() {
//Setting Navigation View Item Selected Listener to handle the item click of the navigation menu
navigationView.setNavigationItemSelectedListener(new NavigationView . OnNavigationItemSelectedListener () {
// This method will trigger on item Click of navigation menu
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
//Check to see which item was being clicked and perform appropriate action
switch(menuItem.getItemId()) {
//Replacing the main content with ContentFragment Which is our Inbox View;
case R . id . nav_home :
navItemIndex = 0;
CURRENT_TAG = TAG_HOME;
break;
case R . id . nav_my_subjects :
navItemIndex = 1;
CURRENT_TAG = TAG_MY_PREF;
break;
case R . id . nav_notification :
navItemIndex = 2;
CURRENT_TAG = TAG_NOTIFICATIONS;
break;
case R . id . nav_settings :
navItemIndex = 3;
CURRENT_TAG = TAG_SETTINGS;
break;
case R . id . nav_logout :
LoginManager.getInstance().logOut();
FirebaseAuth.getInstance().signOut();
Intent i = new Intent(MainActivity.this, LoginActivity.class);
startActivity(i);
finish();
default:
navItemIndex = 0;
}
//Checking if the item is in checked state or not, if not make it in checked state
if (menuItem.isChecked()) {
menuItem.setChecked(false);
} else {
menuItem.setChecked(true);
}
menuItem.setChecked(true);
loadHomeFragment();
return true;
}
});
ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close) {
#Override
public void onDrawerClosed(View drawerView) {
// Code here will be triggered once the drawer closes as we dont want anything to happen so we leave this blank
super.onDrawerClosed(drawerView);
}
#Override
public void onDrawerOpened(View drawerView) {
// Code here will be triggered once the drawer open as we dont want anything to happen so we leave this blank
super.onDrawerOpened(drawerView);
}
};
//Setting the actionbarToggle to drawer layout
drawer.setDrawerListener(actionBarDrawerToggle);
//calling sync state is necessary or else your hamburger icon wont show up
actionBarDrawerToggle.syncState();
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawers();
return;
}
// This code loads home fragment when back key is pressed
// when user is in other fragment than home
if (shouldLoadHomeFragOnBackPress) {
// checking if user is on other navigation menu
// rather than home
if (navItemIndex != 0) {
navItemIndex = 0;
CURRENT_TAG = TAG_HOME;
loadHomeFragment();
return;
}
}
super.onBackPressed();
}
#Override
public void onConnected(#Nullable Bundle bundle) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String []{ Manifest.permission.ACCESS_COARSE_LOCATION }, MY_REQUEST_PERMISSION_LOCATION);
}
return;
}
Location mCurrentLocation = LocationServices . FusedLocationApi . getLastLocation (mGoogleApiClient);
// Note that this can be NULL if last location isn't already known.
if (mCurrentLocation != null) {
// Print current location if not null
Log.d("DEBUG", "current location: " + mCurrentLocation.toString());
mDatabase = FirebaseDatabase.getInstance().getReference("users/B");
GeoFire gf = new GeoFire(mDatabase.child(userId));
gf.setLocation("location", new GeoLocation (mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude()));
lat = mCurrentLocation.getLatitude();
lng = mCurrentLocation.getLongitude();
}
// Begin polling for new location updates.
startLocationUpdates();
}
#Override
public void onConnectionSuspended(int i) {
if (i == CAUSE_SERVICE_DISCONNECTED) {
Toast.makeText(this, "Disconnected. Please re-connect.", Toast.LENGTH_SHORT).show();
} else if (i == CAUSE_NETWORK_LOST) {
Toast.makeText(this, "Network lost. Please re-connect.", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public void onLocationChanged(Location location) {
String msg = "Updated Location: "+
Double.toString(location.getLatitude()) + "," +
Double.toString(location.getLongitude());
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
protected void startLocationUpdates() {
// Create the location request
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(UPDATE_INTERVAL)
.setFastestInterval(FASTEST_INTERVAL);
// Request location updates
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String []{ Manifest.permission.ACCESS_COARSE_LOCATION }, MY_REQUEST_PERMISSION_LOCATION);
}
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
return;
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch(requestCode) {
case MY_REQUEST_PERMISSION_LOCATION :
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
isPermissionGranted = true;
} else {
isPermissionGranted = false;
}
}
}
#Override
public void onFragmentInteraction() {
}
}
my firebase database
For anyone who will find this useful i managed to do it by placing the addValueEventListenermethod of firebase within the addQueryEventListener and pass the String key that is returned by the onKeyEnteredmethod as part of the path in my database reference,
something like this
temp2=FirebaseDatabase.getInstance().getReference("users/A");
GeoFire geofire=new GeoFire(temp2.child("A_location"));
GeoQuery geoQuery=geofire.queryAtLocation(new GeoLocation(lat,lng),10);
geoQuery.addGeoQueryEventListener(new GeoQueryEventListener() {
#Override
public void onKeyEntered(String key, GeoLocation location) {
temp2.child(key).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Person person1 = dataSnapshot.getValue(Person.class);
String name = person1.getName();
String imageUri = person1.getImageUri();
System.out.print(name + " " + imageUri);
Toast.makeText(getActivity(),name,Toast.LENGTH_LONG).show();
personList.add(new Person(name, imageUri));
RVAdapter adapter=new RVAdapter(getActivity(),personList);
rv.setAdapter(adapter);
}
My only question is now is this method efficient if there are alot of users?
I have a service to handle my websocket events however it stops listening when the UI is closed - however, I can still emit messages (eg. location data). How do I keep websockets running in the background so it will listen for events on boot or when the main UI thread is closed?
public class HomeActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
public static final String TAG = HomeActivity.class.getSimpleName();
public static final String PREFS_NAME = "MyPrefsFile";
String userName = "init";
String token = "init";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo wInfo = wifiManager.getConnectionInfo();
String macAddress = wInfo.getMacAddress();
TextView textView = (TextView) findViewById(R.id.txtMac);
textView.setText(macAddress);
startService(new Intent(getBaseContext(), wsService.class));
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
userName = settings.getString("username","does not exist");
token = settings.getString("token","does not exist");
textView = (TextView) findViewById(R.id.txtEmail);
textView.setText(userName);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Beacon");
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
} else if (id == R.id.nav_logout) {
Log.i(TAG, "<<<<---- LOGOUT ---->>> ");
Intent i = new Intent(getApplicationContext(), HomeActivity.class);
startActivity(i);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
This is the service being started from the activity above:
public class wsService extends Service implements OnPreparedListener {
public static final String PREFS_NAME = "MyPrefsFile";
double longitude = 0;
double latitude = 0;
long time = 0;
float speed = 0;
float accuracy = 0;
float bearing = 0;
boolean sound_stopped = true;
String userName = "init";
String token = "init";
public static final String TAG = wsService.class.getSimpleName();
private LocationRequest mLocationRequest;
MediaPlayer mp;
/** indicates how to behave if the service is killed */
int mStartMode;
/** interface for clients that bind */
IBinder mBinder;
/** indicates whether onRebind should be used */
boolean mAllowRebind;
private Socket mSocket;
{
try {
mSocket = IO.socket("http://192.168.0.2:5000");
} catch (URISyntaxException e) {}
}
/** Called when the service is being created. */
#Override
public void onCreate() {
Log.d(TAG, "-- Starting wsService --");
new LongOperation().execute("test");
mp = MediaPlayer.create(this, R.raw.led);
String locationProvider = LocationManager.NETWORK_PROVIDER;
mLocationRequest = LocationRequest.create() // Create the LocationRequest object
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(10 * 1000) // 10 seconds, in milliseconds
.setFastestInterval(1 * 1000); // 1 second, in milliseconds
// Acquire a reference to the system Location Manager
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(locationProvider, 0, 0, locationListener);
}
private class LongOperation extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
Log.d(TAG, "-- Starting BACKGROUND wsService --");
mSocket.connect();
mSocket.on("to_mobile", onCommand);
return "Executed";
}
#Override
protected void onPostExecute(String result) {
}
#Override
protected void onPreExecute() {}
#Override
protected void onProgressUpdate(Void... values) {}
}
//Listening new message event to receive message
private Emitter.Listener onCommand = new Emitter.Listener() {
#Override
public void call(final Object... args) {
JSONObject data = (JSONObject)args[0];
String command = null;
try {
command = data.getString("command");
} catch (JSONException e) {
e.printStackTrace();
}
Log.i(TAG, "<<<<---- RECEIVING COMMAND ----->>> " + command);
if (command.equals("ping_audio_start")) {
start_sound();
}
if (command.equals("ping_audio_stop")) {
stop_sound();
}
if (command.equals("ping_gps")) {
Log.i(TAG, "<<<<---- RESPONDING GPS REQUEST ----->>> ");
mSocket.emit("from_mobile", gps_string);
}
}
};
String gps_string = "HELLO FROM DROID";
private void handleNewLocation(Location location) {
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo wInfo = wifiManager.getConnectionInfo();
String macAddress = wInfo.getMacAddress();
longitude = location.getLongitude();
latitude = location.getLatitude();
time = location.getTime();
speed = location.getSpeed();
accuracy = location.getAccuracy();
bearing = location.getBearing();
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
userName = settings.getString("username","does not exist");
token = settings.getString("token","does not exist");
gps_string = "{ \"mac\":\"" + macAddress
+ "\", \"userName\":\"" + userName
+ "\", \"token\":\"" + token
+ "\", \"time\":\"" + time
+ "\", \"longitude\":\"" + longitude
+ "\", \"latitude\":\"" + latitude
+ "\", \"speed\":\"" + speed
+ "\", \"accuracy\":\"" + accuracy
+ "\", \"bearing\":\"" + bearing
+ "\"}";
mSocket.emit("from_mobile", gps_string);
Log.i(TAG, "<<<<---- SENDING GPS DATA ---->>> ");
}
// Define a listener that responds to location updates
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
handleNewLocation(location);
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
public void start_sound() {
Log.i(TAG, "<<<<---- START PING ----->>>");
mp.release();
mp = MediaPlayer.create(this, R.raw.led);
mp.setLooping(true);
mp.start();
mp.setVolume(1, 1);
sound_stopped = false;
}
public void stop_sound() {
Log.i(TAG, "<<<<---- STOP PING ----->>> ");
mp.stop();
sound_stopped = true;
}
public void onPrepared(MediaPlayer player) {
player.start();
}
/** The service is starting, due to a call to startService() */
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return mStartMode;
}
/** A client is binding to the service with bindService() */
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
/** Called when all clients have unbound with unbindService() */
#Override
public boolean onUnbind(Intent intent) {
return mAllowRebind;
}
/** Called when a client is binding to the service with bindService()*/
#Override
public void onRebind(Intent intent) {
}
/** Called when The service is no longer used and is being destroyed */
#Override
public void onDestroy() {
}
}
IntentService is running only for as long as the it needs to handle the Intent. i.e if there are no intents left to process, the service closes automatically.
Try a normal service instead.
I have an app that uses a Service. For some reason though, the service does not recognize the variables "placeArrayList", "latitudeArrayList", "longitudeArrayList", and "destination".
What can I do here?
MainActivity.java
public class MainActivity extends AppCompatActivity {
PlacePicker.IntentBuilder builder;
int PLACE_PICKER_REQUEST;
ListView placeListView;
ArrayList<String> placeArrayList;
ArrayList<String> latitudeArrayList;
ArrayList<String> longitudeArrayList;
ArrayAdapter<String> arrayAdapter;
SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
ArrayList<Double> latitudeList;
Integer counter;
LocationManager locationManager;
String provider;
double lat;
double lng;
Place place;
static Set<String> set;
static Set<String> set1;
static Set<String> set2;
Location location;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
placeListView = (ListView) findViewById(R.id.placeListView);
latitudeList = new ArrayList<>();
placeArrayList = new ArrayList<String>();
latitudeArrayList = new ArrayList<String>();
longitudeArrayList = new ArrayList<String>();
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
String provider = locationManager.getBestProvider(new Criteria(), false);
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;
}
final Location location = locationManager.getLastKnownLocation(provider);
final Location destination = new Location(provider);
destination.setLatitude(location.getLatitude());
destination.setLongitude(location.getLongitude());
Log.e("shit", String.valueOf(location.distanceTo(destination)));
ListView listView = (ListView) findViewById(R.id.placeListView);
SharedPreferences sharedPreferences = this.getSharedPreferences("bro", Context.MODE_PRIVATE);
set = sharedPreferences.getStringSet("names", null);
set1 = sharedPreferences.getStringSet("lats", null);
set2 = sharedPreferences.getStringSet("lngs", null);
placeArrayList.clear();
latitudeArrayList.clear();
longitudeArrayList.clear();
if (set != null) {
placeArrayList.addAll(set);
latitudeArrayList.addAll(set1);
longitudeArrayList.addAll(set2);
} else {
placeArrayList.add("Hold to delete");
set = new HashSet<String>();
set.addAll(placeArrayList);
sharedPreferences.edit().putStringSet("names", set).apply();
latitudeArrayList.add(String.valueOf("66.56083"));
set1 = new HashSet<String>();
set1.addAll(latitudeArrayList);
sharedPreferences.edit().putStringSet("lats", set1).apply();
longitudeArrayList.add(String.valueOf("39.3232"));
set2 = new HashSet<String>();
set2.addAll(longitudeArrayList);
sharedPreferences.edit().putStringSet("lngs", set2).apply();
}
arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, placeArrayList);
listView.setAdapter(arrayAdapter);
placeListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
new AlertDialog.Builder(MainActivity.this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Are you sure?")
.setMessage("Do you want to delete this place?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
placeArrayList.remove(position);
latitudeArrayList.remove(position);
SharedPreferences sharedPreferences = MainActivity.this.getSharedPreferences("bro", Context.MODE_PRIVATE);
if (set == null) {
set = new HashSet<String>();
set1 = new HashSet<String>();
set2 = new HashSet<String>();
} else {
set.clear();
set1.clear();
set2.clear();
}
set.addAll(placeArrayList);
set1.addAll(latitudeArrayList);
set2.addAll(longitudeArrayList);
sharedPreferences.edit().remove("names").apply();
sharedPreferences.edit().remove("lats").apply();
sharedPreferences.edit().remove("lngs").apply();
sharedPreferences.edit().putStringSet("names", set).apply();
sharedPreferences.edit().putStringSet("lats", set1).apply();
sharedPreferences.edit().putStringSet("lngs", set2).apply();
arrayAdapter.notifyDataSetChanged();
}
})
.setNegativeButton("No", null)
.show();
return false;
}
});
final android.os.Handler handler = new android.os.Handler();
Runnable run = new Runnable() {
#Override
public void run() {
if (location != null) {
lat = location.getLatitude();
lng = location.getLongitude();
if (placeArrayList.size() != 0) {
for (int i = 0; i < placeArrayList.size(); i++) {
Log.e("hello", String.valueOf(Float.parseFloat(latitudeArrayList.get(i))));
destination.setLatitude(Double.parseDouble(latitudeArrayList.get(i)));
destination.setLongitude(Double.parseDouble(longitudeArrayList.get(i)));
Log.e("distancemeters", String.valueOf(location.distanceTo(destination)));
if (location.distanceTo(destination)<100) {
AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
audioManager.setStreamVolume(AudioManager.STREAM_RING, AudioManager.RINGER_MODE_SILENT, AudioManager.FLAG_SHOW_UI);
} else {
}
}
}
}
handler.postDelayed(this, 10000);
}
};
handler.post(run);
arrayAdapter.notifyDataSetChanged();
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
PLACE_PICKER_REQUEST = 1;
builder = new PlacePicker.IntentBuilder();
pickPlace();
}
});
}
public void pickPlace() {
try {
startActivityForResult(builder.build(this), PLACE_PICKER_REQUEST);
} catch (GooglePlayServicesRepairableException e) {
e.printStackTrace();
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PLACE_PICKER_REQUEST) {
if (resultCode == RESULT_OK) {
place = PlacePicker.getPlace(data, this);
// String toastMsg = String.format("Place: %s", place.getName());
//Toast.makeText(this, toastMsg, Toast.LENGTH_LONG).show();
placeArrayList.add(String.valueOf(place.getName()));
latitudeArrayList.add(String.valueOf(place.getLatLng().latitude));
longitudeArrayList.add(String.valueOf(place.getLatLng().longitude));
arrayAdapter.notifyDataSetChanged();
startService(new Intent(getBaseContext(), myService.class));
SharedPreferences sharedPreferences = getSharedPreferences("bro", Context.MODE_PRIVATE);
if (set == null) {
set = new HashSet<String>();
set1 = new HashSet<String>();
set2 = new HashSet<String>();
} else {
set.clear();
set1.clear();
set2.clear();
}
arrayAdapter.notifyDataSetChanged();
set.addAll(placeArrayList);
set1.addAll(latitudeArrayList);
set2.addAll(longitudeArrayList);
sharedPreferences.edit().remove("names").apply();
sharedPreferences.edit().remove("lats").apply();
sharedPreferences.edit().remove("lngs").apply();
sharedPreferences.edit().putStringSet("names", set).apply();
sharedPreferences.edit().putStringSet("lats", set1).apply();
sharedPreferences.edit().putStringSet("lngs", set2).apply();
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
myService.java
public class myService extends Service implements LocationListener {
Double lat;
Double lng;
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Let it continue running until it is stopped.
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
}
#Override
public void onLocationChanged(Location location) {
if (location != null) {
lat = location.getLatitude();
lng = location.getLongitude();
if (placeArrayList.size() != 0) {
for (int i = 0; i < placeArrayList.size(); i++) {
Log.e("hello", String.valueOf(Float.parseFloat(latitudeArrayList.get(i))));
destination.setLatitude(Double.parseDouble(latitudeArrayList.get(i)));
destination.setLongitude(Double.parseDouble(longitudeArrayList.get(i)));
Log.e("distancemeters", String.valueOf(location.distanceTo(destination)));
if (location.distanceTo(destination)<100) {
AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
audioManager.setStreamVolume(AudioManager.STREAM_RING, AudioManager.RINGER_MODE_SILENT, AudioManager.FLAG_SHOW_UI);
} else {
}
}
}
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
Don't make variables as static. Because it can cause memory leaks. And it is not at all a good idea.
Better way is to write an Interface and implement it in MainActivity class.
This interface will have methods for assigning new values to variables.
And call the Interface methods from your service.
You can make the variables static.
And then refer them by prefixing the Activity name to them.
Since the Service is a separate class it makes sense that it wouldn't be able to have access to the fields of MainAcitivity, since they are out of scope to "myService".
When you want to share information between a calling Activity and the Service being called, you'll be able to pass data in a key-value store through the intent.
You can put key-values directly into an Intent:
Intent intent = new Intent(getBaseContext(), myService.class);
itent.putExtra(key, value);
You can build a Bundle and add it to the intent also. Bundle's have a few more methods that make it easier to put rich data into them.
Bundle bundle = new Bundle();
bundle.extras.putString(key, value);
intent.putExtras(mBundle);
View more about Bundle's via the docs: http://developer.android.com/reference/android/os/Bundle.html
If you're interesting in passing a lot of data that cannot be easily represented in key value pairs then you may want to organize your data into your own Parceable class which can also be passed through an Intent. View more on making your own Parceable via the docs: http://developer.android.com/reference/android/os/Parcelable.html
and via this answer
How to send an object from one Android Activity to another using Intents?