When I tested it the first couple of times it was showing perfectly well, then I added some code and it just stopped. It still shows the Mapbox logo on the left bottom screen but it's not loading the map. Here's the code on the MapActivity:
public class MapActivity extends AppCompatActivity implements OnMapReadyCallback, LocationEngineListener, PermissionsListener {
private MapView mapView;
private Button startButton;
private MapboxMap map;
private PermissionsManager permissionsManager;
private LocationEngine locationEngine;
private Location originLocation;
private LocationLayerPlugin locationLayerPlugin;
private Locash customerLocash;
private Point destinationPosition;
private Point originPosition;
private Marker destinationMarker;
private NavigationMapRoute navigationMapRoute;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Mapbox.getInstance(this, getString(R.string.access_token));
setContentView(R.layout.activity_map);
mapView = findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(this);
startButton = findViewById(R.id.startButton);
Intent activityIntent = getIntent();
String locationJson = activityIntent.getStringExtra("location");
Gson gson = new Gson();
customerLocash = gson.fromJson(locationJson,Locash.class);
startButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Launch Navigation
NavigationLauncherOptions options = NavigationLauncherOptions.builder()
.origin(originPosition)
.destination(destinationPosition)
.shouldSimulateRoute(true)
.build();
NavigationLauncher.startNavigation(MapActivity.this, options);
}
});
}
#Override
public void onMapReady(MapboxMap mapboxMap) {
map = mapboxMap;
enableLocation();
LatLng point = new LatLng(customerLocash.getLongitude(),customerLocash.getLatitude());
destinationMarker = map.addMarker(new MarkerOptions().position(point));
destinationPosition = Point.fromLngLat(point.getLongitude(),point.getLatitude());
originPosition = Point.fromLngLat(originLocation.getLongitude(), originLocation.getLatitude());
getRoute(originPosition, destinationPosition);
startButton.setEnabled(true);
}
private void enableLocation() {
if (PermissionsManager.areLocationPermissionsGranted(this)){
initializeLocationEngine();
initializeLocationLayer();
} else {
permissionsManager = new PermissionsManager(this);
permissionsManager.requestLocationPermissions(this);
}
}
#SuppressWarnings("MissingPermission")
private void initializeLocationEngine() {
locationEngine = new LocationEngineProvider(this)
.obtainBestLocationEngineAvailable();
locationEngine.setPriority(LocationEnginePriority.HIGH_ACCURACY);
locationEngine.activate();
Location lastLocation = locationEngine.getLastLocation();
if (lastLocation != null){
originLocation = lastLocation;
setCameraPosition(lastLocation);
} else {
locationEngine.addLocationEngineListener(this);
}
}
#SuppressWarnings("MissingPermission")
private void initializeLocationLayer() {
locationLayerPlugin = new LocationLayerPlugin(mapView, map, locationEngine);
locationLayerPlugin.setLocationLayerEnabled(true);
locationLayerPlugin.setCameraMode(CameraMode.TRACKING);
locationLayerPlugin.setRenderMode(RenderMode.NORMAL);
}
private void setCameraPosition(Location location){
map.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(),
location.getLongitude()),13.0));
}
private void getRoute(Point origin, Point destination){
NavigationRoute.builder()
.accessToken(Mapbox.getAccessToken())
.origin(origin)
.destination(destination)
.build()
.getRoute(new Callback<DirectionsResponse>() {
#Override
public void onResponse(Call<DirectionsResponse> call, Response<DirectionsResponse> response) {
if (response.body() == null){
Toast.makeText(MapActivity.this, "No Routes Found", Toast.LENGTH_SHORT).show();
return;
} else if (response.body().routes().size() == 0){
Toast.makeText(MapActivity.this, "No Routes Found", Toast.LENGTH_SHORT).show();
return;
}
DirectionsRoute currentRoute = response.body().routes().get(0);
navigationMapRoute = new NavigationMapRoute(null, mapView,map);
navigationMapRoute.addRoute(currentRoute);
}
#Override
public void onFailure(Call<DirectionsResponse> call, Throwable t) {
Toast.makeText(MapActivity.this, "Error:" + t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
#SuppressWarnings("MissingPermission")
#Override
public void onConnected() {
locationEngine.requestLocationUpdates();
}
#Override
public void onLocationChanged(Location location) {
if (location != null){
originLocation = location;
setCameraPosition(location);
}
}
#Override
public void onExplanationNeeded(List<String> permissionsToExplain) {
Toast.makeText(this, "Location Required", Toast.LENGTH_SHORT).show();
}
#Override
public void onPermissionResult(boolean granted) {
if (granted){
enableLocation();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
permissionsManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
#Override
#SuppressWarnings("MissingPermission")
protected void onStart() {
super.onStart();
if (locationEngine != null){
locationEngine.requestLocationUpdates();
}
if (locationLayerPlugin != null){
locationLayerPlugin.onStart();
}
mapView.onStart();
}
#Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
#Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
#Override
protected void onStop() {
super.onStop();
if (locationEngine != null){
locationEngine.removeLocationUpdates();
}
if (locationLayerPlugin != null){
locationLayerPlugin.onStop();
}
mapView.onStop();
}
#Override
public void onSaveInstanceState(#NonNull Bundle outState, #NonNull PersistableBundle outPersistentState) {
super.onSaveInstanceState(outState, outPersistentState);
mapView.onSaveInstanceState(outState);
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
#Override
protected void onDestroy() {
super.onDestroy();
if (locationEngine != null){
locationEngine.deactivate();
}
mapView.onDestroy();
}
}
Oh and the Locash object is a class I use to store user location on firebase and the likes.
Looks like a problem I had. Not sure if this is the same, but in my case setting the textureView option to true solved it.
This is how I did it in code:
val resourceOptions = ResourceOptions.Builder()
.accessToken(context.getString(R.string.mapbox_access_token))
.build()
mapView = MapView(context, MapInitOptions(context, resourceOptions).apply { textureView = true })
I am not sure how to do it in XML.
Related
public class MainActivity extends AppCompatActivity implements
OnMapReadyCallback, PermissionsListener {
private static final int REQUEST_CODE_AUTOCOMPLETE = 1;
// variables for adding location layer
private MapView mapView;
private MapboxMap mapboxMap;
// variables for adding location layer
private PermissionsManager permissionsManager;
private LocationComponent locationComponent;
// variables for calculating and drawing a route
private DirectionsRoute currentRoute;
private static final String TAG = "DirectionsActivity";
private NavigationMapRoute navigationMapRoute;
// variables needed to initialize navigation
private Button button;
private CarmenFeature home;
private CarmenFeature work;
private String geojsonSourceLayerId = "geojsonSourceLayerId";
private String symbolIconId = "symbolIconId";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Mapbox access token is configured here. This needs to be called either in your application
// object or in the same activity which contains the mapview.
Mapbox.getInstance(this, getString(R.string.access_token));
// This contains the MapView in XML and needs to be called after the access token is configured.
setContentView(R.layout.activity_main);
mapView = findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(this);
}
#Override
public void onMapReady(#NonNull final MapboxMap mapboxMap) {
this.mapboxMap = mapboxMap;
mapboxMap.setStyle(Style.MAPBOX_STREETS, new Style.OnStyleLoaded() {
#Override
public void onStyleLoaded(#NonNull Style style) {
enableLocationComponent(style);
addDestinationIconSymbolLayer(style);
initSearchFab();
addUserLocations();
// Add the symbol layer icon to map for future use
style.addImage(symbolIconId, BitmapFactory.decodeResource(
MainActivity.this.getResources(), R.drawable.mapbox_marker_icon_default));
// Create an empty GeoJSON source using the empty feature collection
setUpSource(style);
// Set up a new symbol layer for displaying the searched location's feature coordinates
setupLayer(style);
}
});
}
//search
private void initSearchFab() {
findViewById(R.id.fab_location_search).setOnClickListener(new
View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new PlaceAutocomplete.IntentBuilder()
.accessToken(Mapbox.getAccessToken() != null ? Mapbox.getAccessToken() : getString(R.string.access_token))
.placeOptions(PlaceOptions.builder()
.backgroundColor(Color.parseColor("#EEEEEE"))
.limit(10)
.addInjectedFeature(home)
.addInjectedFeature(work)
.build(PlaceOptions.MODE_CARDS))
.build(MainActivity.this);
startActivityForResult(intent, REQUEST_CODE_AUTOCOMPLETE);
}
});
}
//home and work
private void addUserLocations() {
home = CarmenFeature.builder().text("Mapbox SF Office")
.geometry(Point.fromLngLat(-122.3964485, 37.7912561))
.placeName("50 Beale St, San Francisco, CA")
.id("mapbox-sf")
.properties(new JsonObject())
.build();
work = CarmenFeature.builder().text("Mapbox DC Office")
.placeName("740 15th Street NW, Washington DC")
.geometry(Point.fromLngLat(-77.0338348, 38.899750))
.id("mapbox-dc")
.properties(new JsonObject())
.build();
}
private void setUpSource(#NonNull Style loadedMapStyle) {
loadedMapStyle.addSource(new GeoJsonSource(geojsonSourceLayerId));
}
private void setupLayer(#NonNull Style loadedMapStyle) {
loadedMapStyle.addLayer(new SymbolLayer("SYMBOL_LAYER_ID", geojsonSourceLayerId).withProperties(
iconImage(symbolIconId),
iconOffset(new Float[] {0f, -8f})
));
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK && requestCode == REQUEST_CODE_AUTOCOMPLETE) {
// Retrieve selected location's CarmenFeature
CarmenFeature selectedCarmenFeature = PlaceAutocomplete.getPlace(data);
// Create a new FeatureCollection and add a new Feature to it using selectedCarmenFeature above.
// Then retrieve and update the source designated for showing a selected location's symbol layer icon
if (mapboxMap != null) {
Style style = mapboxMap.getStyle();
if (style != null) {
GeoJsonSource source = style.getSourceAs(geojsonSourceLayerId);
if (source != null) {
source.setGeoJson(FeatureCollection.fromFeatures(
new Feature[] {Feature.fromJson(selectedCarmenFeature.toJson())}));
}
// Move map camera to the selected location
mapboxMap.animateCamera(CameraUpdateFactory.newCameraPosition(
new CameraPosition.Builder()
.target(new LatLng(((Point) selectedCarmenFeature.geometry()).latitude(),
((Point) selectedCarmenFeature.geometry()).longitude()))
.zoom(14)
.build()), 4000);
}
}
}
}
//getRoute
private void getRoute(Point origin, Point destination)
{
NavigationRoute.builder(this)
.accessToken(Mapbox.getAccessToken())
.origin(origin)
.destination(destination)
.build()
.getRoute(new Callback<DirectionsResponse>()
{
//onResponse
#Override
public void onResponse(Call<DirectionsResponse> call, Response<DirectionsResponse> response)
{
// You can get the generic HTTP info about the response
Log.d(TAG, "Response code: " + response.code());
if (response.body() == null)
{
Log.e(TAG, "No routes found, make sure you set the right user and access token.");
return;
}
else if (response.body().routes().size() < 1)
{
Log.e(TAG, "No routes found");
return;
}
currentRoute = response.body().routes().get(0);
// Draw the route on the map
if (navigationMapRoute != null)
{
navigationMapRoute.removeRoute();
}
else
{
navigationMapRoute = new NavigationMapRoute(null, mapView, mapboxMap,
R.style.NavigationMapRoute);
}
navigationMapRoute.addRoute(currentRoute);
}//end of onResponse
//onFailure
#Override
public void onFailure(Call<DirectionsResponse> call, Throwable throwable)
{
Log.e(TAG, "Error: " + throwable.getMessage());
}//end of onFailure
});
}//end of getRoute
//addDestinationIconSymbolLayer
private void addDestinationIconSymbolLayer(#NonNull Style loadedMapStyle)
{
loadedMapStyle.addImage("destination-icon-id",
BitmapFactory.decodeResource(this.getResources(), R.drawable.mapbox_marker_icon_default));
GeoJsonSource geoJsonSource = new GeoJsonSource("destination-source-id");
loadedMapStyle.addSource(geoJsonSource);
SymbolLayer destinationSymbolLayer = new SymbolLayer("destination-symbol-layer-id", "destination-source-id");
destinationSymbolLayer.withProperties(
iconImage("destination-icon-id"),
iconAllowOverlap(true),
iconIgnorePlacement(true)
);
loadedMapStyle.addLayer(destinationSymbolLayer);
}//end of addDestinationIconSymbolLayer
//enableLocationComponent
#SuppressWarnings({"MissingPermission"})
private void enableLocationComponent(#NonNull Style loadedMapStyle)
{
// Check if permissions are enabled and if not request
if (PermissionsManager.areLocationPermissionsGranted(this))
{
// Activate the MapboxMap LocationComponent to show user location
// Adding in LocationComponentOptions is also an optional parameter
locationComponent = mapboxMap.getLocationComponent();
locationComponent.activateLocationComponent(this, loadedMapStyle);
locationComponent.setLocationComponentEnabled(true);
// Set the component's camera mode
locationComponent.setCameraMode(CameraMode.TRACKING);
}
else
{
permissionsManager = new PermissionsManager(this);
permissionsManager.requestLocationPermissions(this);
}
}//end of enableLocationComponent
//onRequestPermissionsResult
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults)
{
permissionsManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
}//end of onRequestPermissionsResult
//onExplanationNeeded
#Override
public void onExplanationNeeded(List<String> permissionsToExplain)
{
Toast.makeText(this, R.string.user_location_permission_explanation,
Toast.LENGTH_LONG).show();
}//end of onExplanationNeeded
//onPermissionResult
#Override
public void onPermissionResult(boolean granted)
{
if (granted)
{
enableLocationComponent(mapboxMap.getStyle());
}
else
{
Toast.makeText(this, R.string.user_location_permission_not_granted,
Toast.LENGTH_LONG).show();
finish();
}
}//end of onPermissionResult
// Add the mapView lifecycle to the activity's lifecycle methods
#Override
public void onResume() {
super.onResume();
mapView.onResume();
}
#Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
#Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
#Override
public void onPause() {
super.onPause();
mapView.onPause();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
#Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
} }
Could you please detail what you would like to achieve?
Origin and destination are just 2 positions on the map. You can retrieve these in multiple ways. You could select them by clicking on the map, entering an address into a geocoder that would translate the address to a geolocation. Therefore you could make use of the Mapbox Places Plugin.
This example lets you select features of the map by clicking on it. You can adapt it and return the geolocation, which in turn you could use as your destination: https://docs.mapbox.com/android/maps/examples/query-a-map-feature/
You can make use of the Mapbox locationComponent and retrieve the current device location, which you could utilize as your origin.
See this example: https://docs.mapbox.com/android/maps/examples/show-a-users-location/
In below snippet, you could use the location loc as origin:
private void enableLocationComponent(#NonNull Style loadedMapStyle) {
if (PermissionsManager.areLocationPermissionsGranted(this)) {
LocationComponent locationComponent = map.getLocationComponent();
Location loc = locationComponent.getLastKnownLocation();
im trying to get the city using Geocoder that android have
its app we creating as homework.
I'm trying to do it inside a AsyncTask but i get the this exception:
Can't create handler inside thread that has not called Looper.prepare()
the AsyncTask code:
public class GeocoderTask extends AsyncTask<Void, Void, String> {
LocationManager locationManager;
Location location;
Context context;
String city;
public GeocoderTask(Context context) {
this.context = context;
locationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
}
#SuppressLint("MissingPermission")
#Override
protected String doInBackground(Void... voids) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new LocationListener() {
#Override
public void onLocationChanged(Location location) {
GeocoderTask.this.location = location;
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
List<Address> addresses;
try {
addresses = geocoder.getFromLocation(GeocoderTask.this.location.getLatitude(), GeocoderTask.this.location.getLongitude(), 3);
city = addresses.get(0).getLocality();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e){
e.getMessage();
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
});
return city;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
FrgPersonInfo frgPersonInfo = new FrgPersonInfo();
System.out.println(s);
frgPersonInfo.saveUserToTable(s);
}
}
I'm calling the AsyncTask from fragment
the calling from the fragment:
view.findViewById(R.id.btnRegister).setOnClickListener(new View.OnClickListener() {
#SuppressLint("MissingPermission")
#Override
public void onClick(View v) {
checkPermissions();
GeocoderTask geocoderTask = new GeocoderTask(context);
geocoderTask.execute();
}
});
the method I'm calling in onPostExecute in the AsyncTask:
public void saveUserToTable(String city) {
String age = uAge.getText().toString();
String name = fName.getText().toString();
UserInfo userInfo = new UserInfo();
userInfo.setIsConnected(true);
userInfo.setUserImage(imageUrl);
userInfo.setAge(Integer.valueOf(age));
userInfo.setName(name);
userInfo.setCity(city);
Backendless.Data.of(UserInfo.class).save(userInfo, new AsyncCallback<UserInfo>() {
#Override
public void handleResponse(UserInfo response) {
System.out.println("Bitch, im here again!");
((TextView)parentView.findViewById(R.id.loginFrgBtn)).setTextColor(Color.BLUE);
((TextView)parentView.findViewById(R.id.registerFrgBtn)).setTextColor(Color.BLACK);
FragmentTransaction ft = fm.beginTransaction();
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
FrgLogin frgLogin = new FrgLogin();
ft.replace(R.id.container, frgLogin);
ft.commit();
TastyToast.makeText(context, "Welcome!", TastyToast.LENGTH_LONG, TastyToast.SUCCESS).show();
}
#Override
public void handleFault(BackendlessFault fault) {
TastyToast.makeText(context, fault.getMessage(), TastyToast.LENGTH_LONG, TastyToast.ERROR).show();
}
});
}
the checkPermission:
private void checkPermissions() {
List<String> neededPerms = new ArrayList<>();
int fineGpsPerm = context.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION);
int coarseGpsPerm = context.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION);
if (fineGpsPerm != PackageManager.PERMISSION_GRANTED || coarseGpsPerm != PackageManager.PERMISSION_GRANTED) {
neededPerms.add(Manifest.permission.ACCESS_FINE_LOCATION);
neededPerms.add(Manifest.permission.ACCESS_COARSE_LOCATION);
}
if (!neededPerms.isEmpty()) {
ActivityCompat.requestPermissions( getActivity(), neededPerms.toArray(new String[neededPerms.size()]), GPS_PERM_CODE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode){
case GPS_PERM_CODE:
if (grantResults[0] != PackageManager.PERMISSION_GRANTED|| grantResults[1] != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(context, "Need to Allow perms First", Toast.LENGTH_SHORT).show();
checkPermissions();
}
break;
}
}
the fragment class:
public class FrgPersonInfo extends Fragment{
public static final int GPS_PERM_CODE = 103;
Context context;
EditText fName, uAge, uCity;
String imageUrl = "";
FragmentManager fm;
View parentView;
LocationManager locationManager;
Location location;
boolean isLocEnabled = false;
String cityAddress = "";
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
this.context = context;
System.out.println("in person onattach");
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#SuppressLint("MissingPermission")
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
//inflating the wanted fragmentView
View myView = inflater.inflate(R.layout.frg_person_info, container, false);
// init the fields
fName = myView.findViewById(R.id.fName);
uAge = myView.findViewById(R.id.userAge);
uCity = myView.findViewById(R.id.userCity);
fm = getActivity().getSupportFragmentManager();
locationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
return myView;
}
#SuppressLint("MissingPermission")
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
parentView = view.getRootView();
//creating a bundle so we can (in this case) get data
Bundle bundle = getArguments();
//use the get.. method to get data by key
// imageUrl = bundle.getString(FrgRegister.IMAGE_KEY);
checkPermissions();
if (isLocEnabled) {
} else {
Toast.makeText(context, "dont have perms", Toast.LENGTH_SHORT).show();
}
view.findViewById(R.id.btnRegister).setOnClickListener(new View.OnClickListener() {
#SuppressLint("MissingPermission")
#Override
public void onClick(View v) {
checkPermissions();
GeocoderTask geocoderTask = new GeocoderTask(context);
geocoderTask.getUpdate();
}
});
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onDetach() {
super.onDetach();
this.fName = null;
this.uAge = null;
this.uCity = null;
this.fm = null;
this.imageUrl = null;
}
public void saveUserToTable(String city) {
String age = uAge.getText().toString();
String name = fName.getText().toString();
UserInfo userInfo = new UserInfo();
userInfo.setIsConnected(true);
userInfo.setUserImage(imageUrl);
userInfo.setAge(Integer.valueOf(age));
userInfo.setName(name);
userInfo.setCity(city);
Backendless.Data.of(UserInfo.class).save(userInfo, new AsyncCallback<UserInfo>() {
#Override
public void handleResponse(UserInfo response) {
System.out.println("Bitch, im here again!");
((TextView)parentView.findViewById(R.id.loginFrgBtn)).setTextColor(Color.BLUE);
((TextView)parentView.findViewById(R.id.registerFrgBtn)).setTextColor(Color.BLACK);
FragmentTransaction ft = fm.beginTransaction();
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
FrgLogin frgLogin = new FrgLogin();
ft.replace(R.id.container, frgLogin);
ft.commit();
TastyToast.makeText(context, "Welcome!", TastyToast.LENGTH_LONG, TastyToast.SUCCESS).show();
}
#Override
public void handleFault(BackendlessFault fault) {
TastyToast.makeText(context, fault.getMessage(), TastyToast.LENGTH_LONG, TastyToast.ERROR).show();
}
});
}
private void checkPermissions() {
List<String> neededPerms = new ArrayList<>();
int fineGpsPerm = context.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION);
int coarseGpsPerm = context.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION);
if (fineGpsPerm != PackageManager.PERMISSION_GRANTED || coarseGpsPerm != PackageManager.PERMISSION_GRANTED) {
neededPerms.add(Manifest.permission.ACCESS_FINE_LOCATION);
neededPerms.add(Manifest.permission.ACCESS_COARSE_LOCATION);
}
if (!neededPerms.isEmpty()) {
ActivityCompat.requestPermissions( getActivity(), neededPerms.toArray(new String[neededPerms.size()]), GPS_PERM_CODE);
} else {
isLocEnabled = true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode){
case GPS_PERM_CODE:
if (grantResults[0] != PackageManager.PERMISSION_GRANTED || grantResults[1] != PackageManager.PERMISSION_GRANTED) {
checkPermissions();
} else {
isLocEnabled = true;
}
break;
}
}
}
Create the locationListener to keep a reference to it.
Create a class to trigger the LocationUpdates
public class GeocoderTask {
LocationManager locationManager;
Location location;
Context context;
String city;
LocationListener locationListener = new LocationListener(){
#Override
public void onLocationChanged(Location location) {
GeocoderTask.this.location = location;
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
List<Address> addresses;
FrgPersonInfo frgPersonInfo = new FrgPersonInfo();
System.out.println(city);
frgPersonInfo.saveUserToTable(s);
try {
addresses = geocoder.getFromLocation(GeocoderTask.this.location.getLatitude(), GeocoderTask.this.location.getLongitude(), 3);
city = addresses.get(0).getLocality();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e){
e.getMessage();
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
#Override
public void onProviderEnabled(String provider) {}
#Override
public void onProviderDisabled(String provider) {}
}
public GeocoderTask(Context context) {
this.context = context;
locationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
}
public void getUpdate(){
locationManager.requestSingleUpdate(LocationManager.GPS_PROVIDER,locationListener,null
}
You just have to create the class and use the locationListener to call the Function getUpdate, this will call the Update once. You could also use requestUpdates and create a function to remove the listener if you want more updates.
Asynctask is a Thread, which only executes the tasks which it should and doesn't need a Looper and though there is no Looper called for this Thread. The Locationlistener works different, than that, what you have tried. OnLocationchanged get's called as long as you don't stop the listener, but this is happening asynchronously and you can't just wait inside an asynctask for this to finish. You have to start the locationlistener from your Mainthread and whenever your Location gets changed the function onLocationChanged gets called. You could for example put your onPostExecution inside the locationlistener.
#Override
public void onLocationChanged(Location location) {
GeocoderTask.this.location = location;
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
List<Address> addresses;
try {
addresses = geocoder.getFromLocation(GeocoderTask.this.location.getLatitude(), GeocoderTask.this.location.getLongitude(), 3);
city = addresses.get(0).getLocality();
FrgPersonInfo frgPersonInfo = new FrgPersonInfo();
System.out.println(city);
frgPersonInfo.saveUserToTable(s);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e){
e.getMessage();
}
}
"Using the default milestones requires the directions route to include the route options object"
public class MainActivity extends AppCompatActivity implements OnMapReadyCallback, PermissionsListener , MapboxMap.OnMapClickListener , MapboxMap.OnMapLongClickListener{
private PermissionsManager permissionsManager;
private MapboxMap mapboxMap;
private MapView mapView;
LocationComponent locationComponent;
Double lattt, langgg;
FloatingActionButton floatingActionButton , floatingActionButtonnavigate;
AlertDialog alertDialog;
public MapboxOptimization optimizedClient;
public DirectionsRoute optimizedRoute;
private Point origin;
private NavigationMapRoute navigationMapRoute;
private InstructionView instructionView;
private List<Point> stops = new ArrayList<>();
private static final String ICON_GEOJSON_SOURCE_ID = "icon-source-id";
private static final String FIRST = "first";
private static final String ANY = "any";
private static final String TEAL_COLOR = "#23D2BE";
private static final float POLYLINE_WIDTH = 5;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Mapbox.getInstance(this, getString(R.string.access_token));
token is configured.
setContentView(R.layout.activity_main);
mapView = findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(this);
floatingActionButton = findViewById(R.id.floatingActionButtonforsaveloc);
floatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
opendialoyge();
}
});
}
#Override
public void onMapReady(#NonNull final MapboxMap mapboxMap) {
MainActivity.this.mapboxMap = mapboxMap;
mapboxMap.setStyle(new Style.Builder().fromUri("mapbox://styles/mapbox/satellite-streets-v11"),
new Style.OnStyleLoaded() {
#Override
public void onStyleLoaded(#NonNull Style style) {
enableLocationComponent(style);
addFirstStopToStopsList();
initMarkerIconSymbolLayer(Objects.requireNonNull(style));
initOptimizedRouteLineLayer(style);
Toast.makeText(MainActivity.this, R.string.click_instructions, Toast.LENGTH_SHORT).show();
mapboxMap.addOnMapClickListener(MainActivity.this);
mapboxMap.addOnMapLongClickListener(MainActivity.this);
floatingActionButtonnavigate=findViewById(R.id.floatingActionButtonnavigation);
floatingActionButtonnavigate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
boolean simulateRoute = true;
NavigationLauncherOptions options = NavigationLauncherOptions.builder()
.directionsRoute(optimizedRoute)
.shouldSimulateRoute(simulateRoute)
.build();
NavigationLauncher.startNavigation(MainActivity.this, options);
}
});
}
});
}
private void addFirstStopToStopsList() {
origin = Point.fromLngLat(locationComponent.getLastKnownLocation().getLongitude(), locationComponent.getLastKnownLocation().getLatitude());
stops.add(origin);
}
private void initMarkerIconSymbolLayer(#NonNull Style loadedMapStyle) {
loadedMapStyle.addImage("icon-image", BitmapFactory.decodeResource(
this.getResources(), R.drawable.mapbox_marker_icon_default));
loadedMapStyle.addSource(new GeoJsonSource(ICON_GEOJSON_SOURCE_ID,
Feature.fromGeometry(Point.fromLngLat(origin.longitude(), origin.latitude()))));
loadedMapStyle.addLayer(new SymbolLayer("icon-layer-id", ICON_GEOJSON_SOURCE_ID).withProperties(
iconImage("icon-image"),
iconSize(1f),
iconAllowOverlap(true),
iconIgnorePlacement(true),
iconOffset(new Float[] {0f, -4f})
));
}
private void initOptimizedRouteLineLayer(#NonNull Style loadedMapStyle) {
loadedMapStyle.addSource(new GeoJsonSource("optimized-route-source-id"));
loadedMapStyle.addLayerBelow(new LineLayer("optimized-route-layer-id", "optimized-route-source-id")
.withProperties(
lineColor(Color.parseColor(TEAL_COLOR)),
lineWidth(POLYLINE_WIDTH)
), "icon-layer-id");
}
#SuppressWarnings({"MissingPermission"})
private void enableLocationComponent(#NonNull Style loadedMapStyle) {
if (PermissionsManager.areLocationPermissionsGranted(this)) {
locationComponent = mapboxMap.getLocationComponent();
locationComponent.activateLocationComponent(
LocationComponentActivationOptions.builder(this, loadedMapStyle).build());
locationComponent.setLocationComponentEnabled(true);
locationComponent.setCameraMode(CameraMode.TRACKING);
locationComponent.setRenderMode(RenderMode.COMPASS);
} else {
permissionsManager = new PermissionsManager(this);
permissionsManager.requestLocationPermissions(this);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
permissionsManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
#Override
public void onExplanationNeeded(List<String> permissionsToExplain) {
Toast.makeText(this, R.string.user_location_permission_explanation, Toast.LENGTH_LONG).show();
}
#Override
public void onPermissionResult(boolean granted) {
if (granted) {
mapboxMap.getStyle(new Style.OnStyleLoaded() {
#Override
public void onStyleLoaded(#NonNull Style style) {
enableLocationComponent(style);
}
});
} else {
Toast.makeText(this, R.string.user_location_permission_not_granted, Toast.LENGTH_LONG).show();
finish();
}
}
public void opendialoyge() {
AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
LayoutInflater inflater = LayoutInflater.from(MainActivity.this);
final View mView = inflater.inflate(R.layout.custome_dialouge, null);
final EditText txt_input = mView.findViewById(R.id.entertext);
Button btn_cancle = (Button) mView.findViewById(R.id.butcancle);
Button btn_ok = (Button) mView.findViewById(R.id.butok);
alert.setView(mView);
alertDialog = alert.create();
alertDialog.show();
alertDialog.setCanceledOnTouchOutside(false);
btn_cancle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
alertDialog.dismiss();
}
});
btn_ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String text = txt_input.getText().toString();
if (!text.isEmpty()) {
assert locationComponent.getLastKnownLocation() != null;
lattt = locationComponent.getLastKnownLocation().getLatitude();
langgg = locationComponent.getLastKnownLocation().getLongitude();
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("Hajj&Umrah_App");
myRef.child(text).child("lattt").setValue(lattt.toString());
myRef.child(text).child("lang").setValue(langgg.toString());
} else {
Toast.makeText(MainActivity.this, "Please Enter group Name", Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
public boolean onMapClick(#NonNull LatLng point) {
if (alreadyTwelveMarkersOnMap()) {
Toast.makeText(MainActivity.this, R.string.only_twelve_stops_allowed, Toast.LENGTH_LONG).show();
} else {
Style style = mapboxMap.getStyle();
if (style != null) {
addDestinationMarker(style, point);
addPointToStopsList(point);
getOptimizedRoute(style, stops);
}
}
return true;
}
#Override
public boolean onMapLongClick(#NonNull LatLng point) {
stops.clear();
if (mapboxMap != null) {
Style style = mapboxMap.getStyle();
if (style != null) {
resetDestinationMarkers(style);
removeOptimizedRoute(style);
addFirstStopToStopsList();
return true;
}
}
return false;
}
private void resetDestinationMarkers(#NonNull Style style) {
GeoJsonSource optimizedLineSource = style.getSourceAs(ICON_GEOJSON_SOURCE_ID);
if (optimizedLineSource != null) {
optimizedLineSource.setGeoJson(Point.fromLngLat(origin.longitude(), origin.latitude()));
}
}
private void removeOptimizedRoute(#NonNull Style style) {
GeoJsonSource optimizedLineSource = style.getSourceAs("optimized-route-source-id");
if (optimizedLineSource != null) {
optimizedLineSource.setGeoJson(FeatureCollection.fromFeatures(new Feature[] {}));
}
}
private boolean alreadyTwelveMarkersOnMap() {
return stops.size() == 3;
}
private void addDestinationMarker(#NonNull Style style, LatLng point) {
List<Feature> destinationMarkerList = new ArrayList<>();
for (Point singlePoint : stops) {
destinationMarkerList.add(Feature.fromGeometry(
Point.fromLngLat(singlePoint.longitude(), singlePoint.latitude())));
}
destinationMarkerList.add(Feature.fromGeometry(Point.fromLngLat(point.getLongitude(), point.getLatitude())));
GeoJsonSource iconSource = style.getSourceAs(ICON_GEOJSON_SOURCE_ID);
if (iconSource != null) {
iconSource.setGeoJson(FeatureCollection.fromFeatures(destinationMarkerList));
}
}
private void addPointToStopsList(LatLng point) {
stops.add(Point.fromLngLat(point.getLongitude(), point.getLatitude()));
}
private void getOptimizedRoute(#NonNull final Style style, List<Point> coordinates) {
NavigationRoute.builder(this);
optimizedClient = MapboxOptimization.builder()
.source(FIRST)
.destination(ANY)
.coordinates(coordinates)
.overview(DirectionsCriteria.OVERVIEW_FULL)
.profile(DirectionsCriteria.PROFILE_DRIVING)
.accessToken(Mapbox.getAccessToken())
.build();
optimizedClient.enqueueCall(new Callback<OptimizationResponse>() {
#Override
public void onResponse(Call<OptimizationResponse> call, Response<OptimizationResponse> response) {
if (!response.isSuccessful()) {
Timber.d( getString(R.string.no_success));
Toast.makeText(MainActivity.this, R.string.no_success, Toast.LENGTH_SHORT).show();
return;
} else {
if (response.body().trips().isEmpty()) {
Timber.d("%s size = %s", getString(R.string.successful_but_no_routes), response.body().trips().size());
Toast.makeText(MainActivity.this, R.string.successful_but_no_routes,
Toast.LENGTH_SHORT).show();
return;
}
}
optimizedRoute = Objects.requireNonNull(response.body().trips()).get(0);
if (navigationMapRoute!=null){
navigationMapRoute.removeRoute();
}
else {
navigationMapRoute = new NavigationMapRoute(null,mapView,mapboxMap,R.style.NavigationMapRoute);
}
drawOptimizedRoute(style, optimizedRoute);
}
#Override
public void onFailure(Call<OptimizationResponse> call, Throwable throwable) {
Timber.d("Error: %s", throwable.getMessage());
}
});
}
private void drawOptimizedRoute(#NonNull Style style, DirectionsRoute route) {
GeoJsonSource optimizedLineSource = style.getSourceAs("optimized-route-source-id");
if (optimizedLineSource != null) {
optimizedLineSource.setGeoJson(FeatureCollection.fromFeature(Feature.fromGeometry(
LineString.fromPolyline(route.geometry(), PRECISION_6))));
}
}
#Override
#SuppressWarnings({"MissingPermission"})
protected void onStart() {
super.onStart();
mapView.onStart();
}
#Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
#Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
#Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
#Override
protected void onDestroy() {
super.onDestroy();
if (optimizedClient != null) {
optimizedClient.cancelCall();
}
if (mapboxMap != null) {
mapboxMap.removeOnMapClickListener(this);
}
mapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
}
The exception I am getting:
2019-08-15 17:12:35.879 7522-7522/com.example.chekoptimizationnnnn
E/Mbgl-MapChangeReceiver: Exception in onDidFinishLoadingStyle
java.util.MissingFormatArgumentException: Format specifier 'Using the default milestones requires the directions route to include the
route options object.'
at com.mapbox.services.android.navigation.v5.utils.ValidationUtils.checkNullRouteOptions(ValidationUtils.java:26)
at com.mapbox.services.android.navigation.v5.utils.ValidationUtils.validDirectionsRoute(ValidationUtils.java:18)
at com.mapbox.services.android.navigation.v5.navigation.MapboxNavigation.startNavigationWith(MapboxNavigation.java:938)
at com.mapbox.services.android.navigation.v5.navigation.MapboxNavigation.startNavigation(MapboxNavigation.java:346)
at com.mapbox.services.android.navigation.ui.v5.NavigationViewModel.startNavigation(NavigationViewModel.java:434)
at com.mapbox.services.android.navigation.ui.v5.NavigationViewModel.updateRoute(NavigationViewModel.java:251)
at com.mapbox.services.android.navigation.ui.v5.NavigationViewRouteEngineListener.onRouteUpdate(NavigationViewRouteEngineListener.java:17)
at com.mapbox.services.android.navigation.ui.v5.NavigationViewRouter.updateCurrentRoute(NavigationViewRouter.java:96)
at com.mapbox.services.android.navigation.ui.v5.NavigationViewRouter.extractRouteFrom(NavigationViewRouter.java:121)
at com.mapbox.services.android.navigation.ui.v5.NavigationViewRouter.extractRouteOptions(NavigationViewRouter.java:72)
at com.mapbox.services.android.navigation.ui.v5.NavigationViewModel.initialize(NavigationViewModel.java:213)
at com.mapbox.services.android.navigation.ui.v5.NavigationView.initializeNavigation(NavigationView.java:618)
at com.mapbox.services.android.navigation.ui.v5.NavigationView.startNavigation(NavigationView.java:381)
at com.mapbox.services.android.navigation.ui.v5.MapboxNavigationActivity.onNavigationReady(MapboxNavigationActivity.java:99)
at com.mapbox.services.android.navigation.ui.v5.NavigationView$1.onStyleLoaded(NavigationView.java:225)
at com.mapbox.mapboxsdk.maps.MapboxMap.notifyStyleLoaded(MapboxMap.java:855)
at "Using the default milestones requires the directions route to include the route options object"
com.mapbox.mapboxsdk.maps.MapboxMap.onFinishLoadingStyle(MapboxMap.java:212)
at com.mapbox.mapboxsdk.maps.MapView$MapCallback.onDidFinishLoadingStyle(MapView.java:1264)
at com.mapbox.mapboxsdk.maps.MapChangeReceiver.onDidFinishLoadingStyle(MapChangeReceiver.java:198)
at com.mapbox.mapboxsdk.maps.NativeMapView.onDidFinishLoadingStyle(NativeMapView.java:1035)
at android.os.MessageQueue.nativePollOnce(Native Method)
at android.os.MessageQueue.next(MessageQueue.java:323)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
2019-08-15 17:12:35.886 7522-7522/com.example.chekoptimizationnnnn
A/libc:
/usr/local/google/buildbot/src/android/ndk-release-r19/external/libcxx/../../external/libcxxabi/src/abort_message.cpp:73:
abort_message: assertion "terminating with uncaught exception of type
jni::PendingJavaException" failed 2019-08-15 17:12:35.933
7522-7522/com.example.chekoptimizationnnnn A/libc: Fatal signal 6
(SIGABRT), code -6 in tid 7522 (ptimizationnnnn)
I have following script to get Location using GoogleAPI. Working on My App is based on Location. When This Activity was opened, thanks to using GoogleAPI is got Location Known as Latitude and Longitude.
When MainActivity is opened, if Location turns on within Device Settings.(Android smart Phone).Location Knowledge is obtained as a successfully way and in MainActivity doesn't happen any Problems. Conversely, when Location Turns off on
my android device, while the Activity is started, I have error and App close with a message that called "Unfortunately The App has stopped".
How can I solve this problem? while The Activity is opening How to Control whether Location turns on or off.
thanks in advance for the whole help.
public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener
, LocationListener , DialogInterface.OnClickListener {
public static final String KEY_LOC_ADD_URL = "http://xxxxxxxx/android_api/insertlocation.php";
public static final String KEY_LATITUDE = "enlem";
public static final String KEY_LONGITUDE = "boylam";
public static final String KEY_ID="id";
private GoogleApiClient googleApiClient;
private LocationRequest locationRequest;
private Location mevcutKonum;
private String[] seconds={"1","3","5","7","10"};
private String sonGuncellemeZamani;
private String employee_id;
private Long requestTime;
private TextView enlemTextView;
private TextView boylamTextView;
private TextView sonGuncellemeTextView;
private TextView employee_name;
private AlertDialog dialogSelectInternal;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
enlemTextView = (TextView) findViewById(R.id.enlem);
boylamTextView = (TextView) findViewById(R.id.boylam);
sonGuncellemeTextView = (TextView) findViewById(R.id.guncellemezamani);
sonGuncellemeZamani = "";
employee_name= (TextView) findViewById(R.id.userName);
Intent intent = getIntent();
employee_name.setText("Welcome User " + intent.getStringExtra(Login_Activity.KEY_USERNAME));
employee_id=intent.getStringExtra(Login_Activity.KEY_ID);
buildGoogleApiClient();
selectRequestTimeDialog();
createLocationRequest();
}
protected void buildGoogleApiClient() {
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
protected void createLocationRequest() {
locationRequest = LocationRequest.create()
.setInterval(3000)
.setFastestInterval(1000)
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
protected void startLocationUpdates() {
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(
googleApiClient, locationRequest, this);
}
protected void stopLocationUpdates() {
LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this);
}
private void updateUI() {
if (mevcutKonum != null) {
enlemTextView.setText(String.valueOf(mevcutKonum.getLatitude()));
boylamTextView.setText(String.valueOf(mevcutKonum.getLongitude()));
sonGuncellemeTextView.setText(sonGuncellemeZamani);
}
}
#Override
protected void onResume() {
super.onResume();
googleApiClient.connect();
}
#Override
protected void onPause() {
super.onPause();
if (googleApiClient.isConnected()) {
stopLocationUpdates();
}
googleApiClient.disconnect();
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public void onConnected(#Nullable Bundle bundle) {
if (mevcutKonum == null) {
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mevcutKonum = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
sonGuncellemeZamani = DateFormat.getTimeInstance().format(new Date());
try {
addLocationToUser(String.valueOf(mevcutKonum.getLatitude()),String.valueOf(mevcutKonum.getLongitude()),employee_id);
} catch (JSONException e) {
e.printStackTrace();
}
updateUI();
}
startLocationUpdates();
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onLocationChanged(Location location) {
mevcutKonum = location;
sonGuncellemeZamani = DateFormat.getTimeInstance().format(new Date());
updateUI();
}
private void addLocationToUser(final String latitude, final String longitude,final String id) throws JSONException {
StringRequest stringRequest = new StringRequest(Request.Method.POST, KEY_LOC_ADD_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(MainActivity.this, response, Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put(KEY_LATITUDE,latitude);
params.put(KEY_LONGITUDE, longitude);
params.put(KEY_ID,id);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void selectRequestTimeDialog(){
AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setTitle("Konumunuzu Güncellemek istediğiniz zaman aralığını seçiniz");
builder.setItems(seconds,this);
builder.setNegativeButton("Cancel", null);
dialogSelectInternal=builder.create();
dialogSelectInternal.show();
}
#Override
public void onClick(DialogInterface dialog, int which) {
}
}
Above Code has worked when location only turns on
In your onCreate() , First check if your GPS is enabled in your device, if yes create location update, else go to Location Settings.
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
createLocationRequest();
} else {
Toast.makeText(this, "Please enable your gps first.", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent, 1);
}
On GPS -> HIGH ACCURACY selection:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == 1) {
switch (requestCode) {
case 1:
createLocationRequest();
break;
}
}
}
Hope this helps.
I am using a Sinch tutorial(https://github.com/sinch/android-app-app-calling-headers) as a framework for an app I am trying to develop. The following is the login class from the tutorial which I have updated and been successful in initializing the sinch client.
public class LoginActivity extends BaseActivity implements SinchService.StartFailedListener {
private Button mLoginButton;
private EditText mLoginName;
private static final int REQUEST_PERMISSION = 10;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
mLoginName = (EditText) findViewById(R.id.loginName);
mLoginButton = (Button) findViewById(R.id.loginButton);
mLoginButton.setEnabled(false);
requestAppPermissions(new String[]{Manifest.permission.RECORD_AUDIO, Manifest.permission.ACCESS_FINE_LOCATION}, R.string.msg, REQUEST_PERMISSION);
mLoginButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
loginClicked();
}
});
}
#Override
public void onPermissionGranted(int requestCode) {
}
#Override
protected void onServiceConnected() {
mLoginButton.setEnabled(true);
getSinchServiceInterface().setStartListener(this);
}
#Override
protected void onPause() {
super.onPause();
}
#Override
public void onStartFailed(SinchError error) {
Toast.makeText(this, error.toString(), Toast.LENGTH_LONG).show();
}
#Override
public void onStarted() {
openPlaceCallActivity();
}
private void loginClicked() {
String userName = mLoginName.getText().toString();
if (userName.isEmpty()) {
Toast.makeText(this, "Please enter a name", Toast.LENGTH_LONG).show();
return;
}
if (!getSinchServiceInterface().isStarted()) {
getSinchServiceInterface().startClient(userName);
} else {
openPlaceCallActivity();
}
}
private void openPlaceCallActivity() {
Intent mainActivity = new Intent(this, PlaceCallActivity.class);
startActivity(mainActivity);
}
}
The instantiation of the client occurs in the SinchService Class which is as follows:
private static final String APP_KEY = "";
private static final String APP_SECRET = "";
private static final String ENVIRONMENT = "sandbox.sinch.com";
public static final String LOCATION = "LOCATION";
public static final String CALL_ID = "CALL_ID";
static final String TAG = SinchService.class.getSimpleName();
private SinchServiceInterface mSinchServiceInterface = new SinchServiceInterface();
private SinchClient mSinchClient;
private String mUserId;
private StartFailedListener mListener;
#Override
public void onCreate() {
super.onCreate();
}
#Override
public void onDestroy() {
if (mSinchClient != null && mSinchClient.isStarted()) {
mSinchClient.terminate();
}
super.onDestroy();
}
private void start(String userName) {
if (mSinchClient == null) {
mUserId = userName;
mSinchClient = Sinch.getSinchClientBuilder().context(getApplicationContext()).userId(userName)
.applicationKey(APP_KEY)
.applicationSecret(APP_SECRET)
.environmentHost(ENVIRONMENT).build();
mSinchClient.setSupportCalling(true);
mSinchClient.startListeningOnActiveConnection();
mSinchClient.addSinchClientListener(new MySinchClientListener());
mSinchClient.getCallClient().addCallClientListener(new SinchCallClientListener());
mSinchClient.start();
}
}
private void stop() {
if (mSinchClient != null) {
mSinchClient.terminate();
mSinchClient = null;
}
}
private boolean isStarted() {
return (mSinchClient != null && mSinchClient.isStarted());
}
#Override
public IBinder onBind(Intent intent) {
return mSinchServiceInterface;
}
public class SinchServiceInterface extends Binder {
public Call callPhoneNumber(String phoneNumber) {
return mSinchClient.getCallClient().callPhoneNumber(phoneNumber);
}
public Call callUser(String userId) {
return mSinchClient.getCallClient().callUser(userId);
}
public Call callUser(String userId, Map<String, String> headers) {
return mSinchClient.getCallClient().callUser(userId, headers);
}
public String getUserName() {
return mUserId;
}
public boolean isStarted() {
return SinchService.this.isStarted();
}
public void startClient(String userName) {
start(userName);
}
public void stopClient() {
stop();
}
public void setStartListener(StartFailedListener listener) {
mListener = listener;
}
public Call getCall(String callId) {
return mSinchClient.getCallClient().getCall(callId);
}
}
public interface StartFailedListener {
void onStartFailed(SinchError error);
void onStarted();
}
private class MySinchClientListener implements SinchClientListener {
#Override
public void onClientFailed(SinchClient client, SinchError error) {
if (mListener != null) {
mListener.onStartFailed(error);
}
mSinchClient.terminate();
mSinchClient = null;
}
#Override
public void onClientStarted(SinchClient client) {
Log.d(TAG, "SinchClient started");
if (mListener != null) {
mListener.onStarted();
}
}
#Override
public void onClientStopped(SinchClient client) {
Log.d(TAG, "SinchClient stopped");
}
#Override
public void onLogMessage(int level, String area, String message) {
switch (level) {
case Log.DEBUG:
Log.d(area, message);
break;
case Log.ERROR:
Log.e(area, message);
break;
case Log.INFO:
Log.i(area, message);
break;
case Log.VERBOSE:
Log.v(area, message);
break;
case Log.WARN:
Log.w(area, message);
break;
}
}
#Override
public void onRegistrationCredentialsRequired(SinchClient client,
ClientRegistration clientRegistration) {
}
}
private class SinchCallClientListener implements CallClientListener {
#Override
public void onIncomingCall(CallClient callClient, Call call) {
Log.d(TAG, "Incoming call");
Intent intent = new Intent(SinchService.this, IncomingCallScreenActivity.class);
intent.putExtra(CALL_ID, call.getCallId());
intent.putExtra(LOCATION, call.getHeaders().get("location"));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
SinchService.this.startActivity(intent);
}
}
}
For my purposes, I need to derive the username for the client from my shared preferences folder. I made a dummy app that uses the same framework above with the addition of shared preferences but I always get a NullPointerException error. The following is my login class from my dummy app.
public class LoginActivity extends BaseActivity implements SinchService.StartFailedListener {
private EditText mLoginName, recipientName, coordinateA, coordinateB;
private Button loginButton;
private static final int REQUEST_PERMISSION = 10;
public static final String DEFAULT = "N/A";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
userName = (EditText) findViewById(R.id.userInput);
recipientName = (EditText) findViewById(R.id.recipientInput);
loginButton = (Button) findViewById(R.id.loginButton);
requestAppPermissions(new String[]{Manifest.permission.RECORD_AUDIO, Manifest.permission.ACCESS_FINE_LOCATION}, R.string.msg, REQUEST_PERMISSION);
SharedPreferences sharedPreferences = getSharedPreferences("MyData", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("user_name", mLoginName.getText().toString());
editor.putString("recipient_name", recipientName.getText().toString());
editor.commit();
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
loginClicked();
}
});
}
#Override
public void onPermissionGranted(int requestCode) {
}
#Override
protected void onServiceConnected() {
getSinchServiceInterface().setStartListener(this);
}
#Override
protected void onPause() {
super.onPause();
}
#Override
public void onStartFailed(SinchError error) {
Toast.makeText(this, error.toString(), Toast.LENGTH_LONG).show();
}
#Override
public void onStarted() {
openPlaceCallActivity();
}
private void loginClicked() {
SharedPreferences sharedPreferences = getSharedPreferences("MyData", MODE_PRIVATE);
String userName = sharedPreferences.getString("user_name", DEFAULT);
if (userName.isEmpty()) {
Toast.makeText(this, "Please enter a name",
Toast.LENGTH_LONG).show();
return;
}
if (!getSinchServiceInterface().isStarted()) {
getSinchServiceInterface().startClient(userName);
} else {
openPlaceCallActivity();
}
}
private void openPlaceCallActivity() {
Intent mainActivity = new Intent(LoginActivity.this, PlaceCallActivity.class);
startActivity(mainActivity);
}
}
When comparing my login class with the tutorial's login class-- the only difference is where the variable "userName" is derived. We both have a value attached to the username; however, only one client is able to establish while the other throws a NullPointerException Error. Anyone know why?
EDIT: The error message is as follows:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.dejon_000.sinchtest2, PID: 32470
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean com.example.dejon_000.sinchtest2.SinchService$SinchServiceInterface.isStarted()' on a null object reference
at com.example.dejon_000.sinchtest2.LoginActivity.loginClicked(LoginActivity.java:83)
at com.example.dejon_000.sinchtest2.LoginActivity.access$000(LoginActivity.java:17)
at com.example.dejon_000.sinchtest2.LoginActivity$1.onClick(LoginActivity.java:47)
at android.view.View.performClick(View.java:4802)
at android.view.View$PerformClick.run(View.java:20059)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5422)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:914)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:707)
SECOND EDIT: The getSinchServiceInterface() method is found in the BaseActivity class. It is as follows:
public abstract class BaseActivity extends Activity implements ServiceConnection {
private SparseIntArray mErrorString;
public static final String DEFAULT = "N/A";
private SinchService.SinchServiceInterface mSinchServiceInterface;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getApplicationContext().bindService(new Intent(this, SinchService.class), this,
BIND_AUTO_CREATE);
mErrorString = new SparseIntArray();
}
#Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
if (SinchService.class.getName().equals(componentName.getClassName())) {
mSinchServiceInterface = (SinchService.SinchServiceInterface) iBinder;
onServiceConnected();
}
}
#Override
public void onServiceDisconnected(ComponentName componentName) {
if (SinchService.class.getName().equals(componentName.getClassName())) {
mSinchServiceInterface = null;
onServiceDisconnected();
}
}
protected void onServiceConnected() {
// for subclasses
}
protected void onServiceDisconnected() {
// for subclasses
}
protected SinchService.SinchServiceInterface getSinchServiceInterface() {
return mSinchServiceInterface;
}
public abstract void onPermissionGranted(int requestCode);
public void requestAppPermissions(final String[] requestedPermissions, final int stringId, final int requestCode) {
mErrorString.put(requestCode, stringId);
int permissionCheck = PackageManager.PERMISSION_GRANTED;
boolean showRequestPermissions = false;
for (String permission : requestedPermissions) {
permissionCheck = permissionCheck + ContextCompat.checkSelfPermission(this, permission);
showRequestPermissions = showRequestPermissions || ActivityCompat.shouldShowRequestPermissionRationale(this, permission);
}
if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
if (showRequestPermissions) {
Snackbar.make(findViewById(android.R.id.content), stringId, Snackbar.LENGTH_INDEFINITE).setAction("GRANT", new View.OnClickListener() {
#Override
public void onClick(View view) {
ActivityCompat.requestPermissions(BaseActivity.this, requestedPermissions, requestCode);
}
}).show();
} else {
ActivityCompat.requestPermissions(this, requestedPermissions, requestCode);
}
} else {
onPermissionGranted(requestCode);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
int permissionCheck = PackageManager.PERMISSION_GRANTED;
for(int permission : grantResults){
permissionCheck = permissionCheck + permission;
}
if((grantResults.length > 0)&& PackageManager.PERMISSION_GRANTED == permissionCheck ){
onPermissionGranted(requestCode);
}else{
Snackbar.make(findViewById(android.R.id.content), mErrorString.get(requestCode), Snackbar.LENGTH_INDEFINITE).setAction("ENABLE", new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent();
i.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
i.setData(Uri.parse("package:"+ getPackageName()));
i.addCategory(Intent.CATEGORY_DEFAULT);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
i.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
startActivity(i);
}
}).show();
}
}
}
Try this :
on your BaseActivity.java
instead of
protected void onServiceConnected() {
// for subclasses
}
put
protected void onServiceConnected(IBinder iBinder) {
mSinchServiceInterface = (SinchService.SinchServiceInterface) iBinder;
}
and in your LoginActivity.java
Override the function onServiceConnected(IBinder iBinder)
#Override
protected void onServiceConnected(IBinder iBinder) {
super.onServiceConnected(iBinder);
getSinchServiceInterface().setStartListener(this);
}