Rerouting in Here Map Android SDK - android

I am using Here Map Android SDK for navigation functionalities. Currently my app can calculate the route and draw it through NavigationManager. But the rerouting function can't work even I have added the RerouteListener to NavigationManager. My code is as following:
public class Navigation extends ActionBarActivity {
private GeoCoordinate destinationGeo;
private GeoCoordinate originGeo;
private static Map mMap = null;
private static MapFragment mMapFragment = null;
private static MapRoute mMapRoute = null;
private static RouteManager mRouteManager = null;
private static PositioningManager mPositoningManager = null;
private static NavigationManager mNavigationManager = null;
private static boolean mPositioningListenerPaused = true;
RouteCalculationTask mRouteCalculationTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navigation);
/*
//get destination geo passed from CarParkingActivity
Intent intent = getIntent();
Bundle extras = intent.getExtras();
String lat = extras.getString("lat");
String lng = extras.getString("lng");
*/
//destinationGeo = new GeoCoordinate(Double.parseDouble(lat), Double.parseDouble(lng));
destinationGeo = new GeoCoordinate(1.37374, 103.9707);
mMapFragment = (MapFragment)getFragmentManager().findFragmentById(R.id.navigation_nokia);
if (mMapFragment == null){
System.out.println("mapfragment null");
}
mMapFragment.init(new OnEngineInitListener() {
#Override
public void onEngineInitializationCompleted(Error error) {
if (error == Error.NONE){
System.out.println("map engine init no error");
mMap = mMapFragment.getMap();
mMapFragment.getView().setVisibility(View.INVISIBLE);
mMap.setZoomLevel(mMap.getMaxZoomLevel());
mMap.setCenter(destinationGeo, Map.Animation.NONE);
//set destination marker on map
Image image = new Image();
try{
image.setImageResource(R.drawable.carpark4);
}
catch (IOException e){
e.printStackTrace();
}
MapMarker mapMarker = new MapMarker(destinationGeo, image);
mMap.addMapObject(mapMarker);
//set navigation marker on map
try{
image.setImageResource(R.drawable.gnavigation);
}catch (IOException e){
e.printStackTrace();
}
mMap.getPositionIndicator().setMarker(image);
mMap.getPositionIndicator().setVisible(true);
//set traffic information
mMap.setTrafficInfoVisible(true);
//set map scheme
mMap.setMapScheme(Map.Scheme.CARNAV_DAY);
mRouteManager = RouteManager.getInstance();
mPositoningManager = PositioningManager.getInstance();
mPositoningManager.addListener(new WeakReference<PositioningManager.OnPositionChangedListener>(mPositioningListener));
// start positioning manager
if (mPositoningManager.start(PositioningManager.LocationMethod.GPS_NETWORK)){
MapEngine.getInstance().onResume();
mPositioningListenerPaused = false;
mRouteCalculationTask = new RouteCalculationTask(RouteOptions.Type.FASTEST);
mRouteCalculationTask.execute("hello");
}
mNavigationManager = NavigationManager.getInstance();
mNavigationManager.setMap(mMap);
//set map update mode when movement
mNavigationManager.setMapUpdateMode(NavigationManager.MapUpdateMode.ROADVIEW);
//set up road view in navigation
NavigationManager.RoadView roadView = mNavigationManager.getRoadView();
roadView.addListener(new WeakReference<NavigationManager.RoadView.Listener>(mNavigationManagerRoadViewListener));
roadView.setOrientation(NavigationManager.RoadView.Orientation.DYNAMIC); //heading is at the top of the screen
//set up route recalculation in navigation
mNavigationManager.addRerouteListener(new WeakReference<NavigationManager.RerouteListener>(mNavigaionRerouteListener));
}else {
System.out.println("ERROR: cannot init MapFragment");
}
}
});
}
#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_navigation, 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);
}
#Override
public void onResume(){
super.onResume();
if (mPositoningManager != null){
// start positioning manager
if (mPositoningManager.start(PositioningManager.LocationMethod.GPS_NETWORK)){
mPositioningListenerPaused = false;
mRouteCalculationTask = new RouteCalculationTask(RouteOptions.Type.FASTEST);
mRouteCalculationTask.execute("hello");
}
}
}
#Override
public void onPause(){
super.onPause();
//stop positioning manager
mPositoningManager.stop();
mPositioningListenerPaused = true;
MapEngine.getInstance().onPause();
}
//RouteManager
private RouteManager.Listener mRouteMangerListener = new RouteManager.Listener() {
#Override
public void onProgress(int i) {
}
#Override
public void onCalculateRouteFinished(RouteManager.Error error, List<RouteResult> list) {
if (error == RouteManager.Error.NONE && list.get(0).getRoute() != null){
//create a map route and place it on the map
Route route = list.get(0).getRoute();
mMapRoute = new MapRoute(route);
mMap.addMapObject(mMapRoute);
//begin navigation
NavigationManager.Error navigationError = mNavigationManager.startNavigation(route);
if (navigationError != NavigationManager.Error.NONE)
{
System.out.println(navigationError);
}
else {
System.out.println("start navigation no error");
mNavigationManager.addNavigationManagerEventListener(new WeakReference< NavigationManager.NavigationManagerEventListener>(mNavigationManagerEventListener));
}
//get boundingbox containing the route and zoom in (no animation)
GeoBoundingBox gbb = route.getBoundingBox();
mMap.zoomTo(gbb, Map.Animation.NONE, Map.MOVE_PRESERVE_ORIENTATION);
}
}
};
private NavigationManager.NavigationManagerEventListener mNavigationManagerEventListener = new NavigationManager.NavigationManagerEventListener() {
#Override
public void onRunningStateChanged() {
super.onRunningStateChanged();
System.out.println("onRunningStateChanged");
}
#Override
public void onNavigationModeChanged(){
super.onNavigationModeChanged();
System.out.println("onNavigationModeChanged");
}
};
private NavigationManager.RoadView.Listener mNavigationManagerRoadViewListener = new NavigationManager.RoadView.Listener() {
#Override
public void onPositionChanged(GeoCoordinate geoCoordinate) {
Log.d("Roadview pos", geoCoordinate.toString());
}
};
private class RouteCalculationTask extends AsyncTask<String, String, String> {
private RouteOptions.Type routeType;
private ProgressDialog progressDialog = new ProgressDialog(Navigation.this);
public RouteCalculationTask(RouteOptions.Type type) {
/*
FASTEST(0),
SHORTEST(1),
ECONOMIC(2);
*/
routeType = type;
}
#Override
protected String doInBackground(String... url){
//clear previous results
if (mMap != null && mMapRoute != null){
mMap.removeMapObject(mMapRoute);
mMapRoute = null;
}
//select routing opitions
RoutePlan routePlan = new RoutePlan();
RouteOptions routeOptions = new RouteOptions();
routeOptions.setTransportMode(RouteOptions.TransportMode.PEDESTRIAN);
routeOptions.setRouteType(routeType);
routePlan.setRouteOptions(routeOptions);
//set start point
for(int i = 0; i < 100; i++)
{
if(mPositoningManager.hasValidPosition())
break;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
originGeo = mPositoningManager.getPosition().getCoordinate();
routePlan.addWaypoint(originGeo);
System.out.println("get originGeo");
//set end point
routePlan.addWaypoint(destinationGeo);
//retrieve routing information via RouteManagerEventListener
RouteManager.Error error = mRouteManager.calculateRoute(routePlan, mRouteMangerListener);
if (error != RouteManager.Error.NONE)
{
/*
NONE(0),
UNKNOWN(1),
OUT_OF_MEMORY(2),
INVALID_PARAMETERS(3),
INVALID_OPERATION(4),
GRAPH_DISCONNECTED(5),
GRAPH_DISCONNECTED_CHECK_OPTIONS(6),
NO_START_POINT(7),
NO_END_POINT(8),
NO_END_POINT_CHECK_OPTIONS(9),
CANNOT_DO_PEDESTRIAN(10),
ROUTING_CANCELLED(11),
VIOLATES_OPTIONS(12),
ROUTE_CORRUPTED(13),
INVALID_CREDENTIALS(14),
REQUEST_TIMEOUT(15),
PT_ROUTING_UNAVAILABLE(16),
OPERATION_NOT_ALLOWED(17),
NO_CONNECTIVITY(18);
*/
System.out.println(error);
}
String data = "";
return data;
}
#Override
protected void onPreExecute(){
super.onPreExecute();
progressDialog.show();
}
#Override
protected void onPostExecute(String result){
super.onPostExecute(result);
mMapFragment.getView().setVisibility(View.VISIBLE);
if (progressDialog.isShowing())
progressDialog.dismiss();
}
}
//define positoning listener
private PositioningManager.OnPositionChangedListener mPositioningListener = new PositioningManager.OnPositionChangedListener() {
#Override
public void onPositionUpdated(PositioningManager.LocationMethod locationMethod, GeoPosition geoPosition, boolean b) {
if (!mPositioningListenerPaused && geoPosition.isValid()){
//originGeo = geoPosition.getCoordinate();
mMap.setCenter(geoPosition.getCoordinate(), Map.Animation.NONE);
Double speed = geoPosition.getSpeed();
Double heading = geoPosition.getHeading();
originGeo = geoPosition.getCoordinate();
System.out.println(originGeo.toString());
System.out.println(speed);
}
}
#Override
public void onPositionFixChanged(PositioningManager.LocationMethod locationMethod, PositioningManager.LocationStatus locationStatus) {
//determine if tunnel extrapolation is active
if (locationMethod == PositioningManager.LocationMethod.GPS){
boolean isExtrapolated = ((mPositoningManager.getRoadElement() != null)
&& (mPositoningManager.getRoadElement().getAttributes().contains(RoadElement.Attribute.TUNNEL)));
boolean hasGPS = (locationStatus == locationStatus.AVAILABLE);
}
}
};
//Route recalculation
private NavigationManager.RerouteListener mNavigaionRerouteListener = new NavigationManager.RerouteListener() {
#Override
public void onRerouteBegin() {
super.onRerouteBegin();
Toast.makeText(getApplicationContext(), "reroute begin", Toast.LENGTH_SHORT).show();
}
#Override
public void onRerouteEnd(Route route){
super.onRerouteEnd(route);
Toast.makeText(getApplicationContext(), "reroute end", Toast.LENGTH_SHORT).show();
}
};
}

from my understanding when your position strays off the calculated route, it should trigger a route (re)calculation. I have tried it and I received both onRerouteBegin and onReRouteEnd callbacks. From my observation staying on route does not trigger any re-routing.

Related

android new autocomplete place sdk is unable to shown all locations

I implemented the new autocomplete place sdk in an Android app but it does not show most of places for Nigeria. For example, when I enter spar PH it should show the location SPAR PH, Forces Avenue, Port Harcourt, Nigeria in the suggestion but doesn't. There are other examples that aren't working, too. This was working with the autocomplete Place API but not the new autocomplete .
activity code
public class LocationPickActivity extends BaseActivity
implements OnMapReadyCallback,
GoogleMap.OnCameraMoveListener,
GoogleMap.OnCameraIdleListener,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationPickIView {
private static final LatLngBounds BOUNDS_INDIA = new LatLngBounds(new LatLng(-0, 0), new LatLng(0, 0));
private Location mLastKnownLocation;
protected GoogleApiClient mGoogleApiClient;
#BindView(R.id.appbar)
AppBarLayout appbar;
#BindView(R.id.toolbar)
Toolbar toolbar;
#BindView(R.id.source)
EditText source;
#BindView(R.id.destination)
EditText destination;
#BindView(R.id.destination_layout)
LinearLayout destinationLayout;
#BindView(R.id.home_address_layout)
LinearLayout homeAddressLayout;
#BindView(R.id.work_address_layout)
LinearLayout workAddressLayout;
#BindView(R.id.home_address)
TextView homeAddress;
#BindView(R.id.work_address)
TextView workAddress;
#BindView(R.id.locations_rv)
RecyclerView locationsRv;
#BindView(R.id.location_bs_layout)
CardView locationBsLayout;
#BindView(R.id.dd)
CoordinatorLayout dd;
boolean isEnableIdle = false;
#BindView(R.id.llSource)
LinearLayout llSource;
private boolean isLocationRvClick = false;
private boolean isSettingLocationClick = false;
private boolean mLocationPermissionGranted;
private GoogleMap mGoogleMap;
private String s_address;
private Double s_latitude;
private Double s_longitude;
private FusedLocationProviderClient mFusedLocationProviderClient;
private BottomSheetBehavior mBottomSheetBehavior;
private Boolean isEditable = true;
private UserAddress home, work = null;
private LocationPickPresenter<LocationPickActivity> presenter = new LocationPickPresenter<>();
private EditText selectedEditText;
private PlacesAutoCompleteAdapter mAutoCompleteAdapter;
//Base on action we are show/hide view and setResults
private String actionName = Constants.LocationActions.SELECT_SOURCE;
PlacesClient placesClient =null;
private TextWatcher filterTextWatcher = new TextWatcher() {
public void afterTextChanged(Editable s) {
if (isEditable) if (!s.toString().equals("") && mGoogleApiClient.isConnected()) {
locationsRv.setVisibility(View.VISIBLE);
mAutoCompleteAdapter.getFilter().filter(s.toString());
if (mBottomSheetBehavior.getState() != BottomSheetBehavior.STATE_EXPANDED)
mBottomSheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED);
} else if (!mGoogleApiClient.isConnected()) Log.e("ERROR", "API_NOT_CONNECTED");
if (s.toString().equals("")) locationsRv.setVisibility(View.GONE);
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
};
#Override
public int getLayoutId() {
return R.layout.activity_location_pick;
}
#Override
public void initView() {
buildGoogleApiClient();
ButterKnife.bind(this);
presenter.attachView(this);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Places.initialize(getApplicationContext(), getString(R.string.google_map_key));
placesClient = Places.createClient(this);
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
mBottomSheetBehavior = BottomSheetBehavior.from(locationBsLayout);
mBottomSheetBehavior.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
#Override
public void onStateChanged(#NonNull View bottomSheet, int newState) {
}
#Override
public void onSlide(#NonNull View bottomSheet, float slideOffset) {
}
});
mAutoCompleteAdapter = new PlacesAutoCompleteAdapter(this, R.layout.list_item_location, mGoogleApiClient, BOUNDS_INDIA);
LinearLayoutManager mLinearLayoutManager = new LinearLayoutManager(this);
locationsRv.setLayoutManager(mLinearLayoutManager);
locationsRv.setAdapter(mAutoCompleteAdapter);
source.addTextChangedListener(filterTextWatcher);
destination.addTextChangedListener(filterTextWatcher);
source.setOnFocusChangeListener((view, hasFocus) -> {
if (hasFocus) selectedEditText = source;
});
destination.setOnFocusChangeListener((view, hasFocus) -> {
if (hasFocus) selectedEditText = destination;
});
destination.setOnEditorActionListener((v, actionId, event) -> {
if (actionId == EditorInfo.IME_ACTION_DONE) {
setResult(Activity.RESULT_OK, new Intent());
finish();
return true;
}
return false;
});
source.setText(MvpApplication.RIDE_REQUEST.containsKey(Constants.RIDE_REQUEST.SRC_ADD)
? TextUtils.isEmpty(Objects.requireNonNull(MvpApplication.RIDE_REQUEST.get(Constants.RIDE_REQUEST.SRC_ADD)).toString())
? ""
: String.valueOf(MvpApplication.RIDE_REQUEST.get(Constants.RIDE_REQUEST.SRC_ADD))
: "");
destination.setText(MvpApplication.RIDE_REQUEST.containsKey(Constants.RIDE_REQUEST.DEST_ADD)
? TextUtils.isEmpty(Objects.requireNonNull(MvpApplication.RIDE_REQUEST.get(Constants.RIDE_REQUEST.DEST_ADD)).toString())
? ""
: String.valueOf(MvpApplication.RIDE_REQUEST.get(Constants.RIDE_REQUEST.DEST_ADD))
: "");
locationsRv.addOnItemTouchListener(new RecyclerItemClickListener(this, (view, position) -> {
if (mAutoCompleteAdapter.getItemCount() == 0) return;
final PlacesAutoCompleteAdapter.PlaceAutocomplete item = mAutoCompleteAdapter.getItem(position);
final String placeId = String.valueOf(item.placeId);
Log.i("LocationPickActivity", "Autocomplete item selected: " + item.address);
List<Field> placeFields = Arrays.asList(Field.LAT_LNG);
);
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
actionName = bundle.getString("actionName",Constants.LocationActions.SELECT_SOURCE);
if (!TextUtils.isEmpty(actionName) && actionName.equalsIgnoreCase(Constants.LocationActions.SELECT_SOURCE)) {
destination.setCursorVisible(false);
source.setCursorVisible(true);
source.requestFocus();
selectedEditText = source;
}else if (!TextUtils.isEmpty(actionName) && actionName.equalsIgnoreCase(Constants.LocationActions.SELECT_DESTINATION)){
source.setCursorVisible(false);
destination.setCursorVisible(true);
destination.setText("");
destination.requestFocus();
selectedEditText = destination;
}else if (!TextUtils.isEmpty(actionName) && actionName.equals(Constants.LocationActions.CHANGE_DESTINATION)){
llSource.setVisibility(View.GONE);
source.setHint(getString(R.string.select_location));
selectedEditText = destination;
}else if (!TextUtils.isEmpty(actionName) && (actionName.equals(Constants.LocationActions.SELECT_HOME)|| actionName.equals(Constants.LocationActions.SELECT_WORK))){
destinationLayout.setVisibility(View.GONE);
selectedEditText = destination;
source.setText("");
source.setHint(getString(R.string.select_location));
} else{
destinationLayout.setVisibility(View.VISIBLE);
llSource.setVisibility(View.VISIBLE);
source.setHint(getString(R.string.pickup_location));
selectedEditText = source;
}
}
presenter.address();
}
private void setLocationText(String address, LatLng latLng, boolean isLocationRvClick,
boolean isSettingLocationClick) {
if (address != null && latLng != null) {
isEditable = false;
selectedEditText.setText(address);
isEditable = true;
if (selectedEditText.getTag().equals("source")) {
s_address = address;
s_latitude = latLng.latitude;
s_longitude = latLng.longitude;
MvpApplication.RIDE_REQUEST.put(Constants.RIDE_REQUEST.SRC_ADD, address);
MvpApplication.RIDE_REQUEST.put(Constants.RIDE_REQUEST.SRC_LAT, latLng.latitude);
MvpApplication.RIDE_REQUEST.put(Constants.RIDE_REQUEST.SRC_LONG, latLng.longitude);
}
if (selectedEditText.getTag().equals("destination")) {
MvpApplication.RIDE_REQUEST.put(Constants.RIDE_REQUEST.DEST_ADD, address);
MvpApplication.RIDE_REQUEST.put(Constants.RIDE_REQUEST.DEST_LAT, latLng.latitude);
MvpApplication.RIDE_REQUEST.put(Constants.RIDE_REQUEST.DEST_LONG, latLng.longitude);
if (isLocationRvClick) {
// Done functionality called...
setResult(Activity.RESULT_OK, new Intent());
finish();
}
}
} else {
isEditable = false;
selectedEditText.setText("");
locationsRv.setVisibility(View.GONE);
isEditable = true;
if (selectedEditText.getTag().equals("source")) {
MvpApplication.RIDE_REQUEST.remove(Constants.RIDE_REQUEST.SRC_ADD);
MvpApplication.RIDE_REQUEST.remove(Constants.RIDE_REQUEST.SRC_LAT);
MvpApplication.RIDE_REQUEST.remove(Constants.RIDE_REQUEST.SRC_LONG);
}
if (selectedEditText.getTag().equals("destination")) {
MvpApplication.RIDE_REQUEST.remove(Constants.RIDE_REQUEST.DEST_ADD);
MvpApplication.RIDE_REQUEST.remove(Constants.RIDE_REQUEST.DEST_LAT);
MvpApplication.RIDE_REQUEST.remove(Constants.RIDE_REQUEST.DEST_LONG);
}
}
if (isSettingLocationClick) {
hideKeyboard();
locationsRv.setVisibility(View.GONE);
}
}
#Override
public void onResume() {
super.onResume();
if (!mGoogleApiClient.isConnected() && !mGoogleApiClient.isConnecting()) {
Log.v("Google API", "Connecting");
mGoogleApiClient.connect();
}
}
#Override
public void onPause() {
super.onPause();
if (mGoogleApiClient.isConnected()) {
Log.v("Google API", "Dis-Connecting");
mGoogleApiClient.disconnect();
}
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
#OnClick({R.id.source, R.id.destination, R.id.reset_source, R.id.reset_destination, R.id.home_address_layout, R.id.work_address_layout})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.source:
break;
case R.id.destination:
break;
case R.id.reset_source:
selectedEditText = source;
source.requestFocus();
setLocationText(null, null, isLocationRvClick, isSettingLocationClick);
break;
case R.id.reset_destination:
destination.requestFocus();
selectedEditText = destination;
setLocationText(null, null, isLocationRvClick, isSettingLocationClick);
break;
case R.id.home_address_layout:
if (home != null)
setLocationText(home.getAddress(),
new LatLng(home.getLatitude(), home.getLongitude()),
isLocationRvClick, isSettingLocationClick);
break;
case R.id.work_address_layout:
if (work != null)
setLocationText(work.getAddress(),
new LatLng(work.getLatitude(), work.getLongitude()),
isLocationRvClick, isSettingLocationClick);
break;
}
}
#Override
public void onCameraIdle() {
try {
CameraPosition cameraPosition = mGoogleMap.getCameraPosition();
if (isEnableIdle) {
String address = getAddress(cameraPosition.target);
System.out.println("onCameraIdle " + address);
hideKeyboard();
setLocationText(address, cameraPosition.target, isLocationRvClick, isSettingLocationClick);
}
isEnableIdle = true;
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onCameraMove() {
System.out.println("LocationPickActivity.onCameraMove");
}
#Override
public void onMapReady(GoogleMap googleMap) {
try {
// Google map custom style...
googleMap.setMapStyle(MapStyleOptions.loadRawResourceStyle(this, R.raw.style_json));
} catch (Resources.NotFoundException e) {
Log.d("Map:Style", "Can't find style. Error: ");
}
this.mGoogleMap = googleMap;
getLocationPermission();
updateLocationUI();
getDeviceLocation();
}
void getDeviceLocation() {
try {
if (mLocationPermissionGranted) {
Task<Location> locationResult = mFusedLocationProviderClient.getLastLocation();
locationResult.addOnCompleteListener(this, task -> {
if (task.isSuccessful() && task.getResult() != null) {
mLastKnownLocation = task.getResult();
mGoogleMap.moveCamera(CameraUpdateFactory
.newLatLngZoom(new LatLng(
mLastKnownLocation.getLatitude(),
mLastKnownLocation.getLongitude()
), DEFAULT_ZOOM));
} else {
Log.d("Map", "Current location is null. Using defaults.");
Log.e("Map", "Exception: %s", task.getException());
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(mDefaultLocation, DEFAULT_ZOOM));
mGoogleMap.getUiSettings().setMyLocationButtonEnabled(false);
}
});
}
} catch (SecurityException e) {
Log.e("Exception: %s", e.getMessage());
}
}
public void getLocationPermission() {
if (ContextCompat.checkSelfPermission(this.getApplicationContext(),
android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
mLocationPermissionGranted = true;
else
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_ACCESS_FINE_LOCATION);
}
private void updateLocationUI() {
if (mGoogleMap == null) return;
try {
if (mLocationPermissionGranted) {
mGoogleMap.setMyLocationEnabled(true);
mGoogleMap.getUiSettings().setMyLocationButtonEnabled(false);
mGoogleMap.setOnCameraMoveListener(this);
mGoogleMap.setOnCameraIdleListener(this);
} else {
mGoogleMap.setMyLocationEnabled(false);
mGoogleMap.getUiSettings().setMyLocationButtonEnabled(false);
mLastKnownLocation = null;
getLocationPermission();
}
} catch (SecurityException e) {
Log.e("Exception: %s", e.getMessage());
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String permissions[], #NonNull int[] grantResults) {
mLocationPermissionGranted = false;
if (requestCode == REQUEST_ACCESS_FINE_LOCATION)
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
mLocationPermissionGranted = true;
updateLocationUI();
getDeviceLocation();
}
}
#Override
public void onConnected(#Nullable Bundle bundle) {
}
#Override
public void onConnectionSuspended(int i) {
Log.v("Google API Callback", "Connection Suspended");
Log.v("Code", String.valueOf(i));
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Log.v("Error Code", String.valueOf(connectionResult.getErrorCode()));
Toast.makeText(this, "API_NOT_CONNECTED", Toast.LENGTH_SHORT).show();
}
#Override
public void onBackPressed() {
if (mBottomSheetBehavior.getState() == BottomSheetBehavior.STATE_EXPANDED)
mBottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
else super.onBackPressed();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.location_pick_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_done:
if (!TextUtils.isEmpty(actionName) && actionName.equals(Constants.LocationActions.SELECT_HOME) || actionName.equals(Constants.LocationActions.SELECT_WORK)){
Intent intent = new Intent();
intent.putExtra(Constants.RIDE_REQUEST.SRC_ADD, s_address);
intent.putExtra(Constants.RIDE_REQUEST.SRC_LAT, s_latitude);
intent.putExtra(Constants.RIDE_REQUEST.SRC_LONG, s_longitude);
setResult(Activity.RESULT_OK, intent);
finish();
} else {
setResult(Activity.RESULT_OK, new Intent());
finish();
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onSuccess(AddressResponse address) {
if (address.getHome().isEmpty()) homeAddressLayout.setVisibility(View.GONE);
else {
home = address.getHome().get(address.getHome().size() - 1);
homeAddress.setText(home.getAddress());
homeAddressLayout.setVisibility(View.VISIBLE);
}
if (address.getWork().isEmpty()) workAddressLayout.setVisibility(View.GONE);
else {
work = address.getWork().get(address.getWork().size() - 1);
workAddress.setText(work.getAddress());
workAddressLayout.setVisibility(View.VISIBLE);
}
}
#Override
public void onError(Throwable e) {
handleError(e);
}
#Override
protected void onDestroy() {
presenter.onDetach();
super.onDestroy();
}
}
public class PlacesAutoCompleteAdapter extends RecyclerView.Adapter<PlacesAutoCompleteAdapter.PredictionHolder> implements Filterable {
private static final String TAG = "PlacesAutoAdapter";
private ArrayList<PlaceAutocomplete> mResultList = new ArrayList<>();
private GoogleApiClient mGoogleApiClient;
private LatLngBounds mBounds;
private Context mContext;
private int layout;
private CharacterStyle STYLE_BOLD;
private CharacterStyle STYLE_NORMAL;
PlacesClient placesClient =null;
public PlacesAutoCompleteAdapter(Context context, int resource, GoogleApiClient googleApiClient, LatLngBounds bounds) {
mContext = context;
layout = resource;
mGoogleApiClient = googleApiClient;
mBounds = bounds;
STYLE_BOLD = new StyleSpan(Typeface.BOLD);
STYLE_NORMAL = new StyleSpan(Typeface.NORMAL);
if (!Places.isInitialized()) {
Places.initialize(context, context.getString(R.string.google_api_key));
}
placesClient = Places.createClient(context);
}
public void setBounds(LatLngBounds bounds) {
mBounds = bounds;
}
/**
* Returns the filter for the current set of autocomplete results.
*/
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
// Skip the autocomplete query if no constraints are given.
if (constraint != null) {
// Query the autocomplete API for the (constraint) search string.
mResultList = getAutocomplete(constraint);
if (mResultList != null) {
// The API successfully returned results.
results.values = mResultList;
results.count = mResultList.size();
}
}
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
if (results != null && results.count > 0) {
// The API returned at least one result, update the data.
notifyDataSetChanged();
} else {
// The API did not return any results, invalidate the data set.
//notifyDataSetInvalidated();
}
}
};
}
private ArrayList getAutocomplete(CharSequence constraint) {
if (mGoogleApiClient.isConnected()) {
Log.i("", "Starting autocomplete query for: " + constraint);
// Create a new token for the autocomplete session. Pass this to FindAutocompletePredictionsRequest,
fetchPlace()).
AutocompleteSessionToken token = AutocompleteSessionToken.newInstance();
FindAutocompletePredictionsRequest request = FindAutocompletePredictionsRequest.builder()
.setTypeFilter(TypeFilter.ADDRESS)
.setSessionToken(token)
.setQuery(constraint.toString())
.build();
ArrayList<PlaceAutocomplete> resultList = new ArrayList<>();
placesClient.findAutocompletePredictions(request).addOnSuccessListener((response) -> {
for (AutocompletePrediction prediction : response.getAutocompletePredictions()) {
Log.i(TAG, prediction.getPlaceId());
Log.i(TAG, prediction.getPrimaryText(null).toString());
resultList.add(new PlaceAutocomplete(prediction.getPlaceId(), prediction.getPrimaryText(STYLE_NORMAL),
prediction.getFullText(STYLE_BOLD)));
}
}).addOnFailureListener((exception) -> {
return resultList;
}
Log.e(TAG, "Google API client is not connected for autocomplete query.");
return null;
}
#NonNull
#Override
public PredictionHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
LayoutInflater layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View convertView = Objects.requireNonNull(layoutInflater).inflate(layout, viewGroup, false);
return new PredictionHolder(convertView);
}
#Override
public void onBindViewHolder(#NonNull PredictionHolder mPredictionHolder, final int i) {
mPredictionHolder.area.setText(mResultList.get(i).area);
mPredictionHolder.address.setText(mResultList.get(i).address.toString()
.replace(mResultList.get(i).area + ", ", ""));
}
#Override
public int getItemCount() {
return (mResultList == null) ? 0 : mResultList.size();
}
public PlaceAutocomplete getItem(int position) {
return mResultList.get(position);
}
class PredictionHolder extends RecyclerView.ViewHolder {
private TextView address, area;
PredictionHolder(View itemView) {
super(itemView);
area = itemView.findViewById(R.id.area);
address = itemView.findViewById(R.id.address);
}
}
public class PlaceAutocomplete {
public CharSequence placeId;
public CharSequence address, area;
PlaceAutocomplete(CharSequence placeId, CharSequence area, CharSequence address) {
this.placeId = placeId;
this.area = area;
this.address = address;
}
#Override
public String toString() {
return area.toString();
}
}
}
The Place Picker is deprecated as of January 29, 2019. This feature will be turned off on July 29, 2019, and will no longer be available after that date. You must install the compatibility library to continue using the Place Picker during the deprecation period. Once the deprecation period has ended, the Place Picker will no longer be available for use (including the version in the compatibility library).

how can I store parsed data locally on the mobile device

I have already parsed the data and I need store the parsed data locally on the mobile device in such a way that the app can access it.Im not sure what the best option would be as the data needs to be updated each time I run the app.....
I was going to try a database but I wasn't sure if that was appropriate for this problem
public class MainActivity extends AppCompatActivity implements OnMapReadyCallback {
SupportMapFragment mapFragment;
GoogleMap googleMap;
ArrayList<Item> mItems = new ArrayList<>();
FrameLayout mapsLayout;
Button loadDataButton;
boolean listLoad = true;
LinearLayoutManager linearLayoutManager;
RecyclerView recycleView;
ListDataAdapter listDataAdapter;
ListView listView;
EditText editText;
private Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = this;
linearLayoutManager = new LinearLayoutManager(context);
// EditText editText = findViewById((R.id.search_text));
//
// editText.addTextChangedListener(new TextWatcher() {
// #Override
// public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
// }
// #Override
// public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
// }
// #Override
// public void afterTextChanged(Editable editable)
// {
// //filter(editable.toString());
// }
// });
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mapsLayout = findViewById(R.id.mapsLayout);
loadDataButton = findViewById(R.id.loadDataButton);
recycleView = findViewById(R.id.recycleView);
recycleView.setLayoutManager(linearLayoutManager);
mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
loadDataButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (listLoad) {
listLoad = false;
mapsLayout.setVisibility(View.VISIBLE);
recycleView.setVisibility(View.GONE);
loadMapsData(mItems);
loadDataButton.setText(getString(R.string.show_list));
} else {
listLoad = true;
mapsLayout.setVisibility(View.GONE);
recycleView.setVisibility(View.VISIBLE);
loadListData(mItems);
loadDataButton.setText(getString(R.string.show_maps));
}
}
});
}
#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);
}
#Override
public void onMapReady(GoogleMap googleMap) {
this.googleMap = googleMap;
new ProcessInBackground().execute();
}
public class ProcessInBackground extends AsyncTask<Integer, Void, ArrayList<Item>> {
ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
Exception exception = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog.setMessage("Busy loading rss feed...please wait...");
progressDialog.show();
}
#Override
protected ArrayList<Item> doInBackground(Integer... params) {
try {
URL url = new URL("http://quakes.bgs.ac.uk/feeds/MhSeismology.xml");
//creates new instance of PullParserFactory that can be used to create XML pull parsers
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
//Specifies whether the parser produced by this factory will provide support
//for XML namespaces
factory.setNamespaceAware(false);
//creates a new instance of a XML pull parser using the currently configured
//factory features
XmlPullParser xpp = factory.newPullParser();
// We will get the XML from an input stream
xpp.setInput(getInputStream(url), "UTF_8");
/* We will parse the XML content looking for the "<title>" tag which appears inside the "<item>" tag.
* We should take into consideration that the rss feed name is also enclosed in a "<title>" tag.
* Every feed begins with these lines: "<channel><title>Feed_Name</title> etc."
* We should skip the "<title>" tag which is a child of "<channel>" tag,
* and take into consideration only the "<title>" tag which is a child of the "<item>" tag
*
* In order to achieve this, we will make use of a boolean variable called "insideItem".
*/
boolean insideItem = false;
// Returns the type of current event: START_TAG, END_TAG, START_DOCUMENT, END_DOCUMENT etc..
int eventType = xpp.getEventType(); //loop control variable
Item item = null;
while (eventType != XmlPullParser.END_DOCUMENT) {
//if we are at a START_TAG (opening tag)
if (eventType == XmlPullParser.START_TAG) {
//if the tag is called "item"
if (xpp.getName().equalsIgnoreCase("item")) {
insideItem = true;
item = new Item();
}
//if the tag is called "title"
else if (xpp.getName().equalsIgnoreCase("title")) {
if (insideItem) {
// extract the text between <title> and </title>
item.setTitle(xpp.nextText());
}
}
//if the tag is called "link"
else if (xpp.getName().equalsIgnoreCase("link")) {
if (insideItem) {
// extract the text between <link> and </link>
item.setLink(xpp.nextText());
}
} else if (xpp.getName().equalsIgnoreCase("geo:lat")) {
if (insideItem) {
//extract the text between <geo:lat> and </geo:lat>
item.setLat(Double.valueOf(xpp.nextText()));
}
} else if (xpp.getName().equalsIgnoreCase("geo:long")) {
if (insideItem) {
//extract the text between <geo:lat> and </geo:lat>
item.setLon(Double.valueOf(xpp.nextText()));
}
}
}
//if we are at an END_TAG and the END_TAG is called "item"
else if (eventType == XmlPullParser.END_TAG && xpp.getName().equalsIgnoreCase("item")) {
insideItem = false;
mItems.add(item);
}
eventType = xpp.next(); //move to next element
}
} catch (MalformedURLException e) {
exception = e;
} catch (XmlPullParserException e) {
exception = e;
} catch (IOException e) {
exception = e;
}
return mItems;
}
#Override
protected void onPostExecute(ArrayList<Item> s) {
super.onPostExecute(s);
// ArrayAdapter<Item> adapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_list_item_1, mItems);
// lvRss.setAdapter(adapter);
progressDialog.dismiss();
loadDataButton.setVisibility(View.VISIBLE);
loadListData(s);
}
}
public InputStream getInputStream(URL url) {
try {
//openConnection() returns instance that represents a connection to the remote object referred to by the URL
//getInputStream() returns a stream that reads from the open connection
return url.openConnection().getInputStream();
} catch (IOException e) {
return null;
}
}
private void loadMapsData(ArrayList<Item> listData) {
int i = 0;
for (Item item : listData) {
if (i % 5 == 0) {
googleMap.addMarker(new MarkerOptions()
.position(new LatLng(item.getLat(), item.getLon()))
.title(item.getTitle())
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)));
} else if (i % 5 == 1) {
googleMap.addMarker(new MarkerOptions()
.position(new LatLng(item.getLat(), item.getLon()))
.title(item.getTitle())
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
} else if (i % 5 == 2) {
googleMap.addMarker(new MarkerOptions()
.position(new LatLng(item.getLat(), item.getLon()))
.title(item.getTitle())
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW)));
} else if (i % 5 == 3) {
googleMap.addMarker(new MarkerOptions()
.position(new LatLng(item.getLat(), item.getLon()))
.title(item.getTitle())
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE)));
} else if (i % 5 == 4) {
googleMap.addMarker(new MarkerOptions()
.position(new LatLng(item.getLat(), item.getLon()))
.title(item.getTitle())
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_VIOLET)));
}
i++;
}
LatLngBounds.Builder builder = new LatLngBounds.Builder();
//the include method will calculate the min and max bound.
for (Item item : listData) {
builder.include(new LatLng(item.getLat(), item.getLon()));
}
LatLngBounds bounds = builder.build();
int width = getResources().getDisplayMetrics().widthPixels;
int height = getResources().getDisplayMetrics().heightPixels;
int padding = (int) (width * 0.10); // offset from edges of the map 10% of screen
CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, width, height, padding);
googleMap.animateCamera(cu);
}
private void loadListData(ArrayList<Item> listData) {
listDataAdapter = new ListDataAdapter(context, listData);
recycleView.setAdapter(listDataAdapter);
}
}

HERE Map Turn By Turn Activate

i'm developing turn by turn based navigation application on android. I'm using HERE maps sdk for android. I can't switch to navigation driver mode for turn by turn navigation. How can i switch normal map to turn by turn mode.
Note: I changed to map scheme mode
map.setMapScheme(Map.Scheme.CARNAV_TRAFFIC_DAY);
public class BasicMapActivity extends Activity {
// permissions request code
private final static int REQUEST_CODE_ASK_PERMISSIONS = 1;
private PositioningManager posManager;
private MapRoute mapRoute;
private Route route;
private GeoPosition myPosition;
/**
* Permissions that need to be explicitly requested from end user.
*/
private static final String[] REQUIRED_SDK_PERMISSIONS = new String[] {
Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE };
// map embedded in the map fragment
private Map map = null;
// map fragment embedded in this activity
private MapFragment mapFragment = null;
private PositioningManager.OnPositionChangedListener positionListener = new PositioningManager.OnPositionChangedListener() {
#Override
public void onPositionUpdated(PositioningManager.LocationMethod locationMethod, GeoPosition geoPosition, boolean b) {
Log.v("HERE MAP",geoPosition.getCoordinate().toString());
myPosition = geoPosition;
map.setCenter(geoPosition.getCoordinate(),
Map.Animation.BOW);
// Set the zoom level to the average between min and max
}
#Override
public void onPositionFixChanged(PositioningManager.LocationMethod locationMethod, PositioningManager.LocationStatus locationStatus) {
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
checkPermissions();
}
#Override
protected void onResume() {
super.onResume();
if (posManager != null) {
posManager.start(
PositioningManager.LocationMethod.GPS_NETWORK);
}
}
#Override
protected void onPause() {
super.onPause();
if (posManager != null) {
posManager.stop();
}
}
public void onDestroy() {
if (posManager != null) {
// Cleanup
posManager.removeListener(
positionListener);
}
map = null;
super.onDestroy();
}
private void initialize() {
setContentView(R.layout.activity_main);
findViewById(R.id.btnDrawRoute).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
drawRoute();
}
});
findViewById(R.id.btnChangeMap).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setNavigationManager();
NavigationManager.Error error = NavigationManager.getInstance().startNavigation(route);
if(error.equals(NavigationManager.Error.NONE)){
map.setExtrudedBuildingsVisible(false);
}
}
});
// Search for the map fragment to finish setup by calling init().
mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.mapfragment);
mapFragment.init(new OnEngineInitListener() {
#Override
public void onEngineInitializationCompleted(OnEngineInitListener.Error error) {
if (error == OnEngineInitListener.Error.NONE) {
// retrieve a reference of the map from the map fragment
map = mapFragment.getMap();
// Set the map center to the Vancouver region (no animation)
map.setZoomLevel((map.getMaxZoomLevel() + map.getMinZoomLevel()) / 2);
map.setCartoMarkersVisible(true);
map.setLandmarksVisible(true);
map.setMapScheme(Map.Scheme.CARNAV_DAY);
map.setTrafficInfoVisible(true);
map.setExtrudedBuildingsVisible(true);
map.setStreetLevelCoverageVisible(true);
mapFragment.getPositionIndicator().setVisible(true);
try {
posManager = PositioningManager.getInstance();
posManager.addListener(new WeakReference<>(positionListener));
posManager.start(
PositioningManager.LocationMethod.GPS_NETWORK);
}catch (Exception ex){
Log.v("Error",ex.getMessage());
}
} else {
System.out.println("ERROR: Cannot initialize Map Fragment");
}
}
});
}
private void setNavigationManager() {
NavigationManager.getInstance().setMap(map);
NavigationManager.getInstance().setMapUpdateMode(NavigationManager.MapUpdateMode.ROADVIEW);
NavigationManager.getInstance().setTrafficAvoidanceMode(NavigationManager.TrafficAvoidanceMode.DYNAMIC);
NavigationManager.getInstance().setRealisticViewMode(NavigationManager.RealisticViewMode.DAY);
NavigationManager.getInstance().setDistanceUnit(NavigationManager.UnitSystem.METRIC);
ArrayList<NavigationManager.NaturalGuidanceMode> arrayList = new ArrayList<NavigationManager.NaturalGuidanceMode>();
arrayList.add(NavigationManager.NaturalGuidanceMode.JUNCTION);
arrayList.add(NavigationManager.NaturalGuidanceMode.STOP_SIGN);
arrayList.add(NavigationManager.NaturalGuidanceMode.TRAFFIC_LIGHT);
EnumSet<NavigationManager.NaturalGuidanceMode> enumSet = EnumSet.copyOf(arrayList);
NavigationManager.getInstance().setNaturalGuidanceMode(enumSet);
setVoice();
ArrayList<NavigationManager.AudioEvent> audioEvents = new ArrayList<>();
audioEvents.add(NavigationManager.AudioEvent.ROUTE);
audioEvents.add(NavigationManager.AudioEvent.GPS);
NavigationManager.getInstance().setEnabledAudioEvents(EnumSet.copyOf(audioEvents));
NavigationManager.getInstance().addNewInstructionEventListener(new WeakReference<NavigationManager.NewInstructionEventListener>(new NavigationManager.NewInstructionEventListener() {
#Override
public void onNewInstructionEvent() {
super.onNewInstructionEvent();
Maneuver maneuver = NavigationManager.getInstance().getNextManeuver();
Log.v("Manevra",maneuver.getNextRoadName() + " "+maneuver.getRoadName());
maneuver.getRoadName();
}
}));
NavigationManager.getInstance().addManeuverEventListener(new WeakReference<NavigationManager.ManeuverEventListener>(new NavigationManager.ManeuverEventListener() {
#Override
public void onManeuverEvent() {
super.onManeuverEvent();
}
}));
NavigationManager.getInstance().addPositionListener(new WeakReference<NavigationManager.PositionListener>(new NavigationManager.PositionListener() {
#Override
public void onPositionUpdated(GeoPosition geoPosition) {
super.onPositionUpdated(geoPosition);
geoPosition.getCoordinate();
geoPosition.getHeading();
geoPosition.getSpeed();
// also remaining time and distance can be
// fetched from navigation manager
NavigationManager.getInstance().getTta(Route.TrafficPenaltyMode.DISABLED, true);
NavigationManager.getInstance().getDestinationDistance();
}
}));
}
private void setVoice() {
// Get the list of voice packages from the voice catalog list
List<VoicePackage> voicePackages = VoiceCatalog.getInstance().getCatalogList();
long id = -1;
// select
for (VoicePackage vPackage : voicePackages) {
if (vPackage.getMarcCode().compareToIgnoreCase("eng") == 0) {
if (vPackage.isTts()) {
id = vPackage.getId();
break;
}
}
}
if(id>-1)
NavigationManager.getInstance().setVoiceSkin(VoiceCatalog.getInstance().getLocalVoiceSkin(id));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
/**
* Checks the dynamically controlled permissions and requests missing permissions from end user.
*/
protected void checkPermissions() {
final List<String> missingPermissions = new ArrayList<String>();
// check all required dynamic permissions
for (final String permission : REQUIRED_SDK_PERMISSIONS) {
final int result = ContextCompat.checkSelfPermission(this, permission);
if (result != PackageManager.PERMISSION_GRANTED) {
missingPermissions.add(permission);
}
}
if (!missingPermissions.isEmpty()) {
// request all missing permissions
final String[] permissions = missingPermissions
.toArray(new String[missingPermissions.size()]);
ActivityCompat.requestPermissions(this, permissions, REQUEST_CODE_ASK_PERMISSIONS);
} else {
final int[] grantResults = new int[REQUIRED_SDK_PERMISSIONS.length];
Arrays.fill(grantResults, PackageManager.PERMISSION_GRANTED);
onRequestPermissionsResult(REQUEST_CODE_ASK_PERMISSIONS, REQUIRED_SDK_PERMISSIONS,
grantResults);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String permissions[],
#NonNull int[] grantResults) {
switch (requestCode) {
case REQUEST_CODE_ASK_PERMISSIONS:
for (int index = permissions.length - 1; index >= 0; --index) {
if (grantResults[index] != PackageManager.PERMISSION_GRANTED) {
// exit the app if one permission is not granted
Toast.makeText(this, "Required permission '" + permissions[index]
+ "' not granted, exiting", Toast.LENGTH_LONG).show();
finish();
return;
}
}
// all permissions were granted
initialize();
break;
}
}
private void drawRoute(){
CoreRouter router = new CoreRouter();
GeoCoordinate gebzeCoord = new GeoCoordinate(40.9047617,29.4065243);
GeoCoordinate maslakCoord = new GeoCoordinate(41.1066509,29.0204711);
// Create the RoutePlan and add two waypoints
RoutePlan routePlan = new RoutePlan();
routePlan.addWaypoint(new RouteWaypoint(myPosition.getCoordinate()));
routePlan.addWaypoint(new RouteWaypoint(maslakCoord));
// Create the RouteOptions and set its transport mode & routing type
RouteOptions routeOptions = new RouteOptions();
routeOptions.setTransportMode(RouteOptions.TransportMode.CAR);
routeOptions.setRouteType(RouteOptions.Type.FASTEST);
routePlan.setRouteOptions(routeOptions);
// Calculate the route
router.calculateRoute(routePlan, new RouteListener());
TrafficUpdater trafficUpdater = TrafficUpdater.getInstance();
trafficUpdater.request(route, new TrafficUpdater.Listener() {
#Override
public void onStatusChanged(TrafficUpdater.RequestState requestState) {
}
});
}
private class RouteListener implements CoreRouter.Listener {
// Method defined in Listener
public void onProgress(int percentage) {
// Display a message indicating calculation progress
}
// Method defined in Listener
public void onCalculateRouteFinished(List<RouteResult> routeResult, RoutingError error) {
// If the route was calculated successfully
if (error == RoutingError.NONE) {
// Render the route on the map
mapRoute = new MapRoute(routeResult.get(0).getRoute());
route = routeResult.get(0).getRoute();
map.addMapObject(mapRoute);
}
else {
// Display a message indicating route calculation failure
}
}
}
}
Declare NavigationManager's object as a global object.
private NavigationManager m_navigationManager;
after that initialize it in your setNavigationManager() method.
m_navigationManager = NavigationManager.getInstance();
m_navigationManager.setMap(map);
// try to change current MapUpdateMode to POSITION_ANIMATION
m_navigationManager.setMapUpdateMode(NavigationManager.MapUpdateMode.POSITION_ANIMATION);
m_navigationManager.setTrafficAvoidanceMode(NavigationManager.TrafficAvoidanceMode.DYNAMIC);
m_navigationManager.setRealisticViewMode(NavigationManager.RealisticViewMode.DAY);
// set all other method on this object.
m_navigationManager.......
After you have to start navigation like this
NavigationManager.Error error = m_navigationManager.startNavigation(route);
if (error != NavigationManager.Error.NONE) {
m_navigationManager.setMap(null);
}
//set Tilt to at some angle that you can look in 3d mode
map.setTilt(70f, com.here.android.mpa.mapping.Map.Animation.NONE);
map.setZoomLevel(18);

Google Maps makes the app stop Unfortunately

We are working with an Android Application the first page is Splash screen and the later page is google map . This google map activity makes the app stop unfortunately in some android phones like android version 4.4.2. But in some android phone it is working fine . Is the google map has some restriction with the android API.
When it is run in Android version like 4.4.2 . It is showing this error.
java.lang.RuntimeException: Unable to start activity ComponentInfo{salon.com.barber/salon.com.barber.GoogleMapsActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2342)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2392)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1266)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5421)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:970)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:786)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at salon.com.barber.GoogleMapsActivity.populateMap(GoogleMapsActivity.java:287)
at salon.com.barber.GoogleMapsActivity.onCreate(GoogleMapsActivity.java:205)
at android.app.Activity.performCreate(Activity.java:5263)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1099)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2282)
... 11 more
My Google Map Activity is
public class GoogleMapsActivity extends FragmentActivity {
ImageButton imageButton;
NavDrawerListAdapterSalonDetails adapternav;
DrawerLayout dLayout;
List<NavDrawerSalonDetailsItem> menu;
private ProgressDialog pDialog;
ListView dList1;
private GoogleMap mMap;
GPSTracker gps;
boolean isGpsON;
ArrayList<String> arry_salondetails;
String SaloonDetails = "";
String Street = null;
String Zipcode = null;
String HouseNumber = null;
String City = null;
//final ArrayList<String> SalonNames = new ArrayList<String>();
final HashMap SalonData = new HashMap();
double lati,longi;
final ArrayList<String> serviceDataList = new ArrayList<String>();
Boolean isInternetPresent;
JSONObject objectNextClass;
private GoogleMap googleMap;
JSONArray saloonDetails = null;
RelativeLayout selectedLayout;
double latitude, longitude, range;
String tableName = "barber";
Marker selectedMarker;
ImageButton button_bookmark ;
String objectId = "";
public static final String BARBER_MAP_PREFS = "MAP_PREFS";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_google_maps);
selectedLayout = (RelativeLayout) findViewById(R.id.selectedView);
networkCheck cd = new networkCheck(getApplicationContext());
isInternetPresent = cd.isConnectingToInternet(); // true or
// false
Log.i("sfeeee", "wwwwwww111w");
SharedPreferences prefs = getSharedPreferences(BARBER_MAP_PREFS, MODE_PRIVATE);
String r = prefs.getString("range", null);
if (r == null) {
SharedPreferences.Editor editor = prefs.edit();
editor.putString("range", "10");
editor.commit();
}
AndroidLog.appendLog("En:2");
imageButton =(ImageButton) findViewById(R.id.Search_btn);
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
// On click function
public void onClick(View view) {
// Create the intent to start another activity
Log.i("sfeeee1111111", "wwwwwwww");
Intent i = new Intent(GoogleMapsActivity.this, Search.class);
startActivity(i);
}
});
AndroidLog.appendLog("Ex:2");
dLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
dList1 = (ListView) findViewById(R.id.list_slidermenu);
menu = getNavDraweItemList();
adapternav = new NavDrawerListAdapterSalonDetails(this, menu);
LayoutInflater inflater=this.getLayoutInflater();
View header=inflater.inflate(R.layout.footer, null);
dList1.addHeaderView(header);
dList1.setAdapter(adapternav);
ImageButton buttonMenu =((ImageButton) findViewById(R.id.buttonMenu));
dList1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
getListPosition(position);
// TODO Auto-generated method stub
}
});
buttonMenu.setOnClickListener(new View.OnClickListener() {
#Override
// On click function
public void onClick(View view) {
dLayout.openDrawer(dList1);
}
});
ImageButton button_map=(ImageButton) findViewById(R.id.button_map);
Log.i("111111111111111", "qqqqqqqqqqqqq");
button_map.setOnClickListener(new View.OnClickListener() {
#Override
// On click function
public void onClick(View view) {
// Create the intent to start another activity
if (isInternetPresent) {
LatLng myCurrentLoc = getCurrentLoaction();
Log.i("mycurrentLoc", myCurrentLoc.toString());
Log.i("2222222222211", "qqqqqqqqqqqqq");
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
(myCurrentLoc), 11));
Log.i("3333333333333331", "qqqqqqqqqqqqq");
}
}
});
AndroidLog.appendLog("En:3");
if (isInternetPresent) {
// Calling async task to get json
//new getLocationData().execute();
populateMap();
AndroidLog.appendLog("Ex:3");
Log.i("4444444411111", "qqqqqqqqqqqqq");
} else {
// Internet connection not present
// Ask user to connect to Internet
showAlertDialog(GoogleMapsActivity.this, "No Internet Connection",
"You don't have internet connection.", false);
}
selectedLayout.setVisibility(View.GONE);
Button button = ((Button) selectedLayout
.findViewById(R.id.selec_button_id));
button.setOnClickListener(new View.OnClickListener() {
#Override
// On click function
public void onClick(View view) {
// Create the intent to start another activity
Intent intent = new Intent(view.getContext(),
Salon_Detail.class);
//intent.putExtra("SalonName", (CharSequence) nameView);
// intent.putExtra("json", objectNextClass.toString());
startActivity(intent);
}
});
}
public void onDestroy() {
super.onDestroy();
SharedPreferences prefs = getSharedPreferences(BARBER_MAP_PREFS, MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.clear();
}
public void populateMap(){
Log.d("searched", "map");
pDialog = new ProgressDialog(GoogleMapsActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
if (mMap == null) {
mMap = ((MapFragment) getFragmentManager()
.findFragmentById(R.id.map)).getMap();
}
LatLng myCurrentLoc = getCurrentLoaction();
if(!isGpsON)
{
Toast.makeText(getApplicationContext(),"Switch on the location service for more accuracy",
30000).show();
}
Log.i("Latti and Longii", myCurrentLoc.toString());
latitude = myCurrentLoc.latitude;
Log.i("latitude of current Loc", String.valueOf(latitude));
longitude = myCurrentLoc.longitude;
Log.i("longitudeofcurrent Loc",String.valueOf(longitude));
mMap.addCircle(new CircleOptions()
.center(new LatLng(myCurrentLoc.latitude,
myCurrentLoc.longitude)).radius(10000)
.strokeColor(Color.parseColor("#34DDDD")).strokeWidth(6.0f)
.fillColor(Color.parseColor("#93D5E4")));
Log.i("777777777777777", "qqqqqqqqqqqqq");
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
(myCurrentLoc), 11));
Log.i("666666666666666666", "qqqqqqqqqqqqq");
Marker TP = mMap.addMarker(new MarkerOptions().position(
myCurrentLoc).title("").icon(BitmapDescriptorFactory.fromResource(R.mipmap.pin_blue)));
//icon(BitmapDescriptorFactory.fromResource(R.drawable.navigate))
TP.showInfoWindow();
Log.i("5555555555555555555555", "qqqqqqqqqqqqq");
TP.setSnippet("currentLocation");
SharedPreferences prefs = getSharedPreferences(BARBER_MAP_PREFS, MODE_PRIVATE);
range = Double.parseDouble(prefs.getString("range",null));
//range = 100;
new GmapUtil().onGetCustomMarkers(getApplicationContext(), longitude, latitude, range, tableName,
new GmapUtil.CustomMarker() {
#Override
public void onSuccess(String data) {
Log.i("resulttttttt od dataaa", data);
pDialog.hide();
try {
JSONObject jsonObject = new JSONObject(data);
Log.i("jsonObjectttttttttttt", jsonObject.toString());
JSONObject jsonObject1 = jsonObject.getJSONObject("data");
Log.i("jsonObjecttttttt1", jsonObject1.toString());
JSONArray jsonArray = jsonObject1.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
final JSONObject child = jsonArray.getJSONObject(i);
//final String sName = child.getString("SalonName");
//SalonNames.add(child.getString("SalonName"));
//Log.i("salonn namesss", SalonNames.toString());
latitude = child.getDouble("Latitude");
longitude = child.getDouble("Longitude");
LatLng saloonLoc = new LatLng(latitude, longitude);
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
Marker marker = mMap.addMarker(new MarkerOptions()
.position(saloonLoc).title("TutorialsPoint").icon(BitmapDescriptorFactory.fromResource(R.mipmap.map_red)));
marker.setSnippet(child.getString("objectId"));
SalonData.put(child.getString("objectId"), child);
Log.i("8888888888888888", "qqqqqqqqqqqqq");
// googleMap.setOnMarkerClickListener(this);
mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
SaloonDetails = "";
// Take some action here
String snippet = marker.getSnippet();
objectId = snippet;
if (selectedMarker != null && !("currentLocation".equals(snippet))) {
selectedMarker.setIcon(BitmapDescriptorFactory.fromResource(R.mipmap.map_red));
}
selectedMarker = marker;
if (!("currentLocation".equals(snippet)))
marker.setIcon(BitmapDescriptorFactory.fromResource(R.mipmap.map_blue));
Log.i("TAG", "snippet::::" + snippet);
if ("currentLocation".equals(snippet)) {
selectedLayout.setVisibility(View.GONE);
//button_bookmark.setVisibility(View.GONE);
return false;
} else {
selectedLayout
.setVisibility(View.VISIBLE);
TextView nameView = ((TextView) selectedLayout
.findViewById(R.id.name_txt_id));
TextView addressView = ((TextView) selectedLayout
.findViewById(R.id.address_txt_id));
try {
JSONObject jSalonData = (JSONObject)SalonData.get(snippet);
nameView.setText(jSalonData.getString("SalonName"));
} catch (Exception e) {
e.printStackTrace();
}
try {
JSONObject jSalonData = (JSONObject)SalonData.get(snippet);
Log.i("jSalonData",jSalonData.toString());
//addressView.append(System.getProperty("line.separator"));
City = jSalonData.optString("City");
SaloonDetails = SaloonDetails + City;
Zipcode = jSalonData.optString("Zipcode");
SaloonDetails = SaloonDetails +" "+ Zipcode;
HouseNumber = jSalonData.optString("HouseNumber");
SaloonDetails = SaloonDetails +" "+ HouseNumber;
Street = jSalonData.optString("Street");
SaloonDetails = SaloonDetails +" "+ Street;
Log.i("SaloonDetails", SaloonDetails);
//addressView.setText(jSalonData.getString("Zipcode"));
//addressView.setText(jSalonData.getString("City"));
addressView.setText(SaloonDetails);
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
}
});
}
} catch (Exception e) {
Log.i("Exception", e.toString());
}
}
#Override
public void onError(String data) {
}
});
}
private LatLng getCurrentLoaction() {
// TODO Auto-generated method stub
Log.i("sfeeee","wwwwwwww");
gps = new GPSTracker(GoogleMapsActivity.this);
// check if GPS enabled
if (gps.canGetLocation()) {
isGpsON=true;
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
Log.i("Latiiiiiiiiii",latLng.toString());
return latLng;
// \n is for new line
} else {
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
isGpsON=false;
LatLng latLng = new LatLng(52.156111,5.387827);
return latLng;
}
}
private List<NavDrawerSalonDetailsItem> getNavDraweItemList() {
String search = "Search";
String Privacypolicy = "Privacy policy";
String termsofconditions = "Terms and Conditions";
String favorite = " Favourites";
String Setting = "Settings";
String[] list = new String[] {search, Privacypolicy,termsofconditions,favorite,Setting};
int[] icons = { R.mipmap.small_search, R.mipmap.small_about_us };
List<NavDrawerSalonDetailsItem> menu = new ArrayList<NavDrawerSalonDetailsItem>();
for (int i = 0; i < list.length; i++) {
menu.add(new NavDrawerSalonDetailsItem(list[i], i));
}
return menu;
}
/**
* Function to display simple Alert Dialog
*
* #param context
* - application context
* #param title
* - alert dialog title
* #param message
* - alert message
* #param status
* - success/failure (used to set icon)
* */
#SuppressWarnings("deprecation")
public void showAlertDialog(Context context, String title, String message,
Boolean status) {
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
// Setting Dialog Title
alertDialog.setTitle(title);
// Setting Dialog Message
alertDialog.setMessage(message);
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, final int which) {
}
});
// Showing Alert Message
alertDialog.show();
}
public void search(){
// Create the intent to start another activity
Intent intent = new Intent(GoogleMapsActivity.this, Search.class);
startActivity(intent);
}
public void privacyPolicy(){
// Create the intent to start another activity
Intent intent = new Intent(GoogleMapsActivity.this, privacypolicy.class);
startActivity(intent);
}
public void termsAndCondition(){
// Create the intent to start another activity
Intent intent = new Intent(GoogleMapsActivity.this, Terms_and_condition.class);
startActivity(intent);
}
public void favorite(){
Intent intent = new Intent(GoogleMapsActivity.this,comingsoon.class);
startActivity(intent);
}
public void Settings(){
Intent intent = new Intent(GoogleMapsActivity.this,comingsoon.class);
startActivity(intent);
}
public void getListPosition(int position) {
switch (position) {
case 1: {
search();
break;
}
case 2: {
privacyPolicy();
break;
}
case 3: {
termsAndCondition();
break;
}
case 4: {
favorite();
break;
}
case 5: {
Settings();
break;
}
default: {
break;
}
}
}
}
To ensure that you are using a non-null instance of GoogleMap you should implement OnMapReadyCallback. From the documentation https://developers.google.com/android/reference/com/google/android/gms/maps/OnMapReadyCallback
Once an instance of this interface is set on a MapFragment or MapView object, the onMapReady(GoogleMap) method is triggered when the map is ready to be used and provides a non-null instance of GoogleMap.:
So, your GoogleMapsActivity needs to implement OnMapReadyCallback and you have to move the call your populateMap(); method to the onMapReady method:
public class GoogleMapsActivity extends FragmentActivity implements OnMapReadyCallback {
// ...
#Override
protected void onCreate(Bundle savedInstanceState) {
// Remove populateMap(); and change it for
((MapFragment) getFragmentManager()
.findFragmentById(R.id.map)).getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
populateMap();
}
}

Does vuforia support Andengine?

public class Demo extends LayoutGameActivity implements SampleApplicationControl,SampleAppMenuInterface {
private static final int CAMERA_WIDTH = 720;
private static final int CAMERA_HEIGHT = 480;
private static final float AUTOWRAP_WIDTH = 720 - 50 - 50;
private EditText mEditText;
private Font mFont;
private Text mText;
private Line mRight;
private Line mLeft;
private static final String LOGTAG = "ImageTargets";
SampleApplicationSession vuforiaAppSession;
private DataSet mCurrentDataset;
private int mCurrentDatasetSelectionIndex = 0;
private int mStartDatasetsIndex = 0;
private int mDatasetsNumber = 0;
private ArrayList<String> mDatasetStrings = new ArrayList<String>();
// Our OpenGL view:
private SampleApplicationGLView mGlView;
// Our renderer:
private ImageTargetRenderer mRenderer;
private GestureDetector mGestureDetector;
// The textures we will use for rendering:
private Vector<Texture> mTextures;
private boolean mSwitchDatasetAsap = false;
private boolean mFlash = false;
private boolean mContAutofocus = false;
private boolean mExtendedTracking = false;
private View mFlashOptionView;
private RelativeLayout mUILayout;
private SampleAppMenu mSampleAppMenu;
LoadingDialogHandler loadingDialogHandler = new LoadingDialogHandler(this);
// Alert Dialog used to display SDK errors
private AlertDialog mErrorDialog;
boolean mIsDroidDevice = false;
// Called when the activity first starts or the user navigates back to an
// activity.
// Process Single Tap event to trigger autofocus
private class GestureListener extends
GestureDetector.SimpleOnGestureListener
{
// Used to set autofocus one second after a manual focus is triggered
private final Handler autofocusHandler = new Handler();
#Override
public boolean onDown(MotionEvent e)
{
return true;
}
#Override
public boolean onSingleTapUp(MotionEvent e)
{
// Generates a Handler to trigger autofocus
// after 1 second
autofocusHandler.postDelayed(new Runnable()
{
public void run()
{
boolean result = CameraDevice.getInstance().setFocusMode(
CameraDevice.FOCUS_MODE.FOCUS_MODE_TRIGGERAUTO);
if (!result)
Log.e("SingleTapUp", "Unable to trigger focus");
}
}, 1000L);
return true;
}
}
// We want to load specific textures from the APK, which we will later use
// for rendering.
private void loadTextures()
{
mTextures.add(Texture.loadTextureFromApk("TextureTeapotBrass.png",
getAssets()));
mTextures.add(Texture.loadTextureFromApk("TextureTeapotBlue.png",
getAssets()));
mTextures.add(Texture.loadTextureFromApk("TextureTeapotRed.png",
getAssets()));
mTextures.add(Texture.loadTextureFromApk("ImageTargets/Buildings.jpeg",
getAssets()));
}
// Called when the activity will start interacting with the user.
#Override
protected void onResume()
{
Log.d(LOGTAG, "onResume");
super.onResume();
vuforiaAppSession = new SampleApplicationSession(this);
startLoadingAnimation();
mDatasetStrings.add("StonesAndChips.xml");
mDatasetStrings.add("Tarmac.xml");
// mDatasetStrings.add("my_first.xml");
vuforiaAppSession
.initAR(this, ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
mGestureDetector = new GestureDetector(this, new GestureListener());
// Load any sample specific textures:
mTextures = new Vector<Texture>();
loadTextures();
mIsDroidDevice = android.os.Build.MODEL.toLowerCase().startsWith(
"droid");
// This is needed for some Droid devices to force portrait
if (mIsDroidDevice)
{
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
try
{
vuforiaAppSession.resumeAR();
} catch (SampleApplicationException e)
{
Log.e(LOGTAG, e.getString());
}
// Resume the GL view:
if (mGlView != null)
{
mGlView.setVisibility(View.VISIBLE);
mGlView.onResume();
}
}
// Callback for configuration changes the activity handles itself
#Override
public void onConfigurationChanged(Configuration config)
{
Log.d(LOGTAG, "onConfigurationChanged");
super.onConfigurationChanged(config);
vuforiaAppSession.onConfigurationChanged();
}
// Called when the system is about to start resuming a previous activity.
#Override
protected void onPause()
{
Log.d(LOGTAG, "onPause");
super.onPause();
if (mGlView != null)
{
mGlView.setVisibility(View.INVISIBLE);
mGlView.onPause();
}
// Turn off the flash
if (mFlashOptionView != null && mFlash)
{
// OnCheckedChangeListener is called upon changing the checked state
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1)
{
((Switch) mFlashOptionView).setChecked(false);
} else
{
((CheckBox) mFlashOptionView).setChecked(false);
}
}
try
{
vuforiaAppSession.pauseAR();
} catch (SampleApplicationException e)
{
Log.e(LOGTAG, e.getString());
}
}
// The final call you receive before your activity is destroyed.
#Override
protected void onDestroy()
{
Log.d(LOGTAG, "onDestroy");
super.onDestroy();
try
{
vuforiaAppSession.stopAR();
} catch (SampleApplicationException e)
{
Log.e(LOGTAG, e.getString());
}
// Unload texture:
mTextures.clear();
mTextures = null;
System.gc();
}
// Initializes AR application components.
private void initApplicationAR()
{
// Create OpenGL ES view:
int depthSize = 16;
int stencilSize = 0;
boolean translucent = Vuforia.requiresAlpha();
mGlView = new SampleApplicationGLView(this);
mGlView.init(translucent, depthSize, stencilSize);
mRenderer = new ImageTargetRenderer(this, vuforiaAppSession);
mRenderer.setTextures(mTextures);
mGlView.setRenderer(mRenderer);
}
private void startLoadingAnimation()
{
LayoutInflater inflater = LayoutInflater.from(this);
mUILayout = (RelativeLayout) inflater.inflate(R.layout.camera_overlay,
null, false);
mUILayout.setVisibility(View.VISIBLE);
mUILayout.setBackgroundColor(Color.BLACK);
// Gets a reference to the loading dialog
loadingDialogHandler.mLoadingDialogContainer = mUILayout
.findViewById(R.id.loading_indicator);
// Shows the loading indicator at start
loadingDialogHandler
.sendEmptyMessage(LoadingDialogHandler.SHOW_LOADING_DIALOG);
// Adds the inflated layout to the view
addContentView(mUILayout, new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT));
}
// Methods to load and destroy tracking data.
#Override
public boolean doLoadTrackersData()
{
TrackerManager tManager = TrackerManager.getInstance();
ObjectTracker objectTracker = (ObjectTracker) tManager
.getTracker(ObjectTracker.getClassType());
if (objectTracker == null)
return false;
if (mCurrentDataset == null)
mCurrentDataset = objectTracker.createDataSet();
if (mCurrentDataset == null)
return false;
if (!mCurrentDataset.load(
mDatasetStrings.get(mCurrentDatasetSelectionIndex),
STORAGE_TYPE.STORAGE_APPRESOURCE))
return false;
if (!objectTracker.activateDataSet(mCurrentDataset))
return false;
int numTrackables = mCurrentDataset.getNumTrackables();
for (int count = 0; count < numTrackables; count++)
{
Trackable trackable = mCurrentDataset.getTrackable(count);
if(isExtendedTrackingActive())
{
trackable.startExtendedTracking();
}
String name = "Current Dataset : " + trackable.getName();
trackable.setUserData(name);
Log.d(LOGTAG, "UserData:Set the following user data "
+ (String) trackable.getUserData());
}
return true;
}
#Override
public boolean doUnloadTrackersData()
{
// Indicate if the trackers were unloaded correctly
boolean result = true;
TrackerManager tManager = TrackerManager.getInstance();
ObjectTracker objectTracker = (ObjectTracker) tManager
.getTracker(ObjectTracker.getClassType());
if (objectTracker == null)
return false;
if (mCurrentDataset != null && mCurrentDataset.isActive())
{
if (objectTracker.getActiveDataSet().equals(mCurrentDataset)
&& !objectTracker.deactivateDataSet(mCurrentDataset))
{
result = false;
} else if (!objectTracker.destroyDataSet(mCurrentDataset))
{
result = false;
}
mCurrentDataset = null;
}
return result;
}
#Override
public void onInitARDone(SampleApplicationException exception)
{
if (exception == null)
{
initApplicationAR();
mRenderer.mIsActive = true;
// Now add the GL surface view. It is important
// that the OpenGL ES surface view gets added
// BEFORE the camera is started and video
// background is configured.
addContentView(mGlView, new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT));
// Sets the UILayout to be drawn in front of the camera
mUILayout.bringToFront();
// Sets the layout background to transparent
mUILayout.setBackgroundColor(Color.TRANSPARENT);
try
{
vuforiaAppSession.startAR(CameraDevice.CAMERA.CAMERA_DEFAULT);
} catch (SampleApplicationException e)
{
Log.e(LOGTAG, e.getString());
}
boolean result = CameraDevice.getInstance().setFocusMode(
CameraDevice.FOCUS_MODE.FOCUS_MODE_CONTINUOUSAUTO);
if (result)
mContAutofocus = true;
else
Log.e(LOGTAG, "Unable to enable continuous autofocus");
mSampleAppMenu = new SampleAppMenu(this, this, "Image Targets",
mGlView, mUILayout, null);
setSampleAppMenuSettings();
} else
{
Log.e(LOGTAG, exception.getString());
showInitializationErrorMessage(exception.getString());
}
}
// Shows initialization error messages as System dialogs
public void showInitializationErrorMessage(String message)
{
final String errorMessage = message;
runOnUiThread(new Runnable()
{
public void run()
{
if (mErrorDialog != null)
{
mErrorDialog.dismiss();
}
// Generates an Alert Dialog to show the error message
AlertDialog.Builder builder = new AlertDialog.Builder(
Demo.this);
builder
.setMessage(errorMessage)
.setTitle(getString(R.string.INIT_ERROR))
.setCancelable(false)
.setIcon(0)
.setPositiveButton(getString(R.string.button_OK),
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
finish();
}
});
mErrorDialog = builder.create();
mErrorDialog.show();
}
});
}
#Override
public void onQCARUpdate(State state)
{
if (mSwitchDatasetAsap)
{
mSwitchDatasetAsap = false;
TrackerManager tm = TrackerManager.getInstance();
ObjectTracker ot = (ObjectTracker) tm.getTracker(ObjectTracker
.getClassType());
if (ot == null || mCurrentDataset == null
|| ot.getActiveDataSet() == null)
{
Log.d(LOGTAG, "Failed to swap datasets");
return;
}
doUnloadTrackersData();
doLoadTrackersData();
}
}
#Override
public boolean doInitTrackers()
{
// Indicate if the trackers were initialized correctly
boolean result = true;
TrackerManager tManager = TrackerManager.getInstance();
Tracker tracker;
// Trying to initialize the image tracker
tracker = tManager.initTracker(ObjectTracker.getClassType());
if (tracker == null)
{
Log.e(
LOGTAG,
"Tracker not initialized. Tracker already initialized or the camera is already started");
result = false;
} else
{
Log.i(LOGTAG, "Tracker successfully initialized");
}
return result;
}
#Override
public boolean doStartTrackers()
{
// Indicate if the trackers were started correctly
boolean result = true;
Tracker objectTracker = TrackerManager.getInstance().getTracker(
ObjectTracker.getClassType());
if (objectTracker != null)
objectTracker.start();
return result;
}
#Override
public boolean doStopTrackers()
{
// Indicate if the trackers were stopped correctly
boolean result = true;
Tracker objectTracker = TrackerManager.getInstance().getTracker(
ObjectTracker.getClassType());
if (objectTracker != null)
objectTracker.stop();
return result;
}
#Override
public boolean doDeinitTrackers()
{
// Indicate if the trackers were deinitialized correctly
boolean result = true;
TrackerManager tManager = TrackerManager.getInstance();
tManager.deinitTracker(ObjectTracker.getClassType());
return result;
}
#Override
public boolean onTouchEvent(MotionEvent event)
{
// Process the Gestures
if (mSampleAppMenu != null && mSampleAppMenu.processEvent(event))
return true;
return mGestureDetector.onTouchEvent(event);
}
boolean isExtendedTrackingActive()
{
return mExtendedTracking;
}
final public static int CMD_BACK = -1;
final public static int CMD_EXTENDED_TRACKING = 1;
final public static int CMD_AUTOFOCUS = 2;
final public static int CMD_FLASH = 3;
final public static int CMD_CAMERA_FRONT = 4;
final public static int CMD_CAMERA_REAR = 5;
final public static int CMD_DATASET_START_INDEX = 6;
// This method sets the menu's settings
private void setSampleAppMenuSettings()
{
SampleAppMenuGroup group;
group = mSampleAppMenu.addGroup("", false);
group.addTextItem(getString(R.string.menu_back), -1);
group = mSampleAppMenu.addGroup("", true);
group.addSelectionItem(getString(R.string.menu_extended_tracking),
CMD_EXTENDED_TRACKING, false);
group.addSelectionItem(getString(R.string.menu_contAutofocus),
CMD_AUTOFOCUS, mContAutofocus);
mFlashOptionView = group.addSelectionItem(
getString(R.string.menu_flash), CMD_FLASH, false);
CameraInfo ci = new CameraInfo();
boolean deviceHasFrontCamera = false;
boolean deviceHasBackCamera = false;
for (int i = 0; i < Camera.getNumberOfCameras(); i++)
{
Camera.getCameraInfo(i, ci);
if (ci.facing == CameraInfo.CAMERA_FACING_FRONT)
deviceHasFrontCamera = true;
else if (ci.facing == CameraInfo.CAMERA_FACING_BACK)
deviceHasBackCamera = true;
}
if (deviceHasBackCamera && deviceHasFrontCamera)
{
group = mSampleAppMenu.addGroup(getString(R.string.menu_camera),
true);
group.addRadioItem(getString(R.string.menu_camera_front),
CMD_CAMERA_FRONT, false);
group.addRadioItem(getString(R.string.menu_camera_back),
CMD_CAMERA_REAR, true);
}
group = mSampleAppMenu
.addGroup(getString(R.string.menu_datasets), true);
mStartDatasetsIndex = CMD_DATASET_START_INDEX;
mDatasetsNumber = mDatasetStrings.size();
group.addRadioItem("Stones & Chips", mStartDatasetsIndex, true);
group.addRadioItem("Tarmac", mStartDatasetsIndex + 1, false);
// group.addRadioItem("my_first", mStartDatasetsIndex + 2, false);
mSampleAppMenu.attachMenu();
}
#SuppressLint("NewApi") #Override
public boolean menuProcess(int command)
{
boolean result = true;
switch (command)
{
case CMD_BACK:
finish();
break;
case CMD_FLASH:
result = CameraDevice.getInstance().setFlashTorchMode(!mFlash);
if (result)
{
mFlash = !mFlash;
} else
{
showToast(getString(mFlash ? R.string.menu_flash_error_off
: R.string.menu_flash_error_on));
Log.e(LOGTAG,
getString(mFlash ? R.string.menu_flash_error_off
: R.string.menu_flash_error_on));
}
break;
case CMD_AUTOFOCUS:
if (mContAutofocus)
{
result = CameraDevice.getInstance().setFocusMode(
CameraDevice.FOCUS_MODE.FOCUS_MODE_NORMAL);
if (result)
{
mContAutofocus = false;
} else
{
showToast(getString(R.string.menu_contAutofocus_error_off));
Log.e(LOGTAG,
getString(R.string.menu_contAutofocus_error_off));
}
} else
{
result = CameraDevice.getInstance().setFocusMode(
CameraDevice.FOCUS_MODE.FOCUS_MODE_CONTINUOUSAUTO);
if (result)
{
mContAutofocus = true;
} else
{
showToast(getString(R.string.menu_contAutofocus_error_on));
Log.e(LOGTAG,
getString(R.string.menu_contAutofocus_error_on));
}
}
break;
case CMD_CAMERA_FRONT:
case CMD_CAMERA_REAR:
// Turn off the flash
if (mFlashOptionView != null && mFlash)
{
// OnCheckedChangeListener is called upon changing the checked state
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1)
{
((Switch) mFlashOptionView).setChecked(false);
} else
{
((CheckBox) mFlashOptionView).setChecked(false);
}
}
vuforiaAppSession.stopCamera();
try
{
vuforiaAppSession
.startAR(command == CMD_CAMERA_FRONT ? CameraDevice.CAMERA.CAMERA_FRONT
: CameraDevice.CAMERA.CAMERA_BACK);
} catch (SampleApplicationException e)
{
showToast(e.getString());
Log.e(LOGTAG, e.getString());
result = false;
}
doStartTrackers();
break;
case CMD_EXTENDED_TRACKING:
for (int tIdx = 0; tIdx < mCurrentDataset.getNumTrackables(); tIdx++)
{
Trackable trackable = mCurrentDataset.getTrackable(tIdx);
if (!mExtendedTracking)
{
if (!trackable.startExtendedTracking())
{
Log.e(LOGTAG,
"Failed to start extended tracking target");
result = false;
} else
{
Log.d(LOGTAG,
"Successfully started extended tracking target");
}
} else
{
if (!trackable.stopExtendedTracking())
{
Log.e(LOGTAG,
"Failed to stop extended tracking target");
result = false;
} else
{
Log.d(LOGTAG,
"Successfully started extended tracking target");
}
}
}
if (result)
mExtendedTracking = !mExtendedTracking;
break;
default:
if (command >= mStartDatasetsIndex
&& command < mStartDatasetsIndex + mDatasetsNumber)
{
mSwitchDatasetAsap = true;
mCurrentDatasetSelectionIndex = command
- mStartDatasetsIndex;
}
break;
}
return result;
}
private void showToast(String text)
{
Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
}
#Override
protected void onCreate(Bundle pSavedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(pSavedInstanceState);
}
#Override
public EngineOptions onCreateEngineOptions() {
final org.andengine.engine.camera.Camera camera = new org.andengine.engine.camera.Camera(0, 0, Demo.CAMERA_WIDTH, Demo.CAMERA_HEIGHT);
return new EngineOptions(true, ScreenOrientation.PORTRAIT_FIXED, new RatioResolutionPolicy(Demo.CAMERA_WIDTH, Demo.CAMERA_HEIGHT), camera);
}
private void updateText() {
final String string = this.mEditText.getText().toString();
this.mText.setText(string);
final float left = (this.mText.getWidth() * 0.5f) - (this.mText.getLineWidthMaximum() * 0.5f);
this.mLeft.setPosition(left, 0, left, Demo.CAMERA_HEIGHT);
final float right = (this.mText.getWidth() * 0.5f) + (this.mText.getLineWidthMaximum() * 0.5f);
this.mRight.setPosition(right, 0, right, Demo.CAMERA_HEIGHT);
}
#Override
protected int getLayoutID() {
// TODO Auto-generated method stub
return R.layout.camera_overlay;
}
#Override
protected int getRenderSurfaceViewID() {
// TODO Auto-generated method stub
return R.id.textbreakexample_rendersurfaceview;
}
#Override
protected void onSetContentView() {
// TODO Auto-generated method stub
super.onSetContentView();
}
#Override
public void onCreateResources(
OnCreateResourcesCallback pOnCreateResourcesCallback)
throws IOException {
// TODO Auto-generated method stub
}
#Override
public void onCreateScene(OnCreateSceneCallback pOnCreateSceneCallback)
throws IOException {
// TODO Auto-generated method stub
}
#Override
public void onPopulateScene(Scene pScene,
OnPopulateSceneCallback pOnPopulateSceneCallback)
throws IOException {
// TODO Auto-generated method stub
}
}
I am using andEngine for Developing game and I also use vuforia for AR (Augmented Reality).But if i combine both the codes then i getting error as surfaceview null.
**and if it's not supported then what is the use for augmented reality object tracking in andenginre **

Categories

Resources