Android MapView load location from searchView - java

Is it possible in mapView to load a marker when the user clicks a button or submits a search in searchView. I am having trouble getting marker locations to show when the user submits data. When the user submits the info it pulls the lat and long but does not update the position from the view model immediately.
public class SearchFragment extends Fragment implements OnMapReadyCallback {
private static final String TAG = "SearchFragment";
private SearchViewModel searchViewModel;
private LatLng location;
private Marker marker;
//UI
private MapView mapView;
private SearchView searchView;
private TextView cityTv, countryTv, regionTv, ispTv, timezoneTv, postalTv, countryCallingCodeTv;
private static final String MAPVIEW_BUNDLE = "MAPVIEW_BUNDLE";
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, final Bundle savedInstanceState) {
Log.d(TAG, "onCreateView: ");
final View view = inflater.inflate(R.layout.fragment_search, container, false);
searchView = view.findViewById(R.id.search_searchview);
cityTv = view.findViewById(R.id.city_input_textview);
countryTv = view.findViewById(R.id.country_input_textview);
regionTv = view.findViewById(R.id.region_input_textview);
ispTv = view.findViewById(R.id.isp_input_textview);
timezoneTv = view.findViewById(R.id.timezone_input_textview);
postalTv = view.findViewById(R.id.postal_input_textview);
countryCallingCodeTv = view.findViewById(R.id.countrycallingcode_input_textview);
Bundle mapViewBundle = null;
if (savedInstanceState != null) {
mapViewBundle = savedInstanceState.getBundle(MAPVIEW_BUNDLE);
}
mapView = view.findViewById(R.id.location_mapview);
mapView.onCreate(mapViewBundle);
searchViewModel = ViewModelProviders.of(this).get(SearchViewModel.class);
searchView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View view) {
searchView.setIconified(false);
//returns result from search view
getSearchViewResults(view);
}
});
return view;
}
#Override
public void onSaveInstanceState(#NonNull Bundle outState) {
super.onSaveInstanceState(outState);
Bundle mapViewBundle = outState.getBundle(MAPVIEW_BUNDLE);
if (mapViewBundle == null) {
mapViewBundle = new Bundle();
outState.putBundle(MAPVIEW_BUNDLE, mapViewBundle);
}
mapView.onSaveInstanceState(mapViewBundle);
}
//retrieves the search results from searchView and passes information to searchviewmodel
public void getSearchViewResults(final View view) {
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
Log.d(TAG, "onQueryTextSubmit: ");
//TODO: add input validation to make sure addres is correct
//TODO: if incorrect display toast message saying input is invalid
searchViewModel.getIpAddress(query);
//observer to observe data change and display search results in textview
observeSearchView();
mapView.getMapAsync(SearchFragment.this);
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
return false;
}
});
}
private void observeSearchView() {
searchViewModel.getIpLocation().observe(SearchFragment.this, new Observer<IPLocation>() {
#Override
public void onChanged(IPLocation ipLocation) {
cityTv.setText(ipLocation.getCity());
countryTv.setText(ipLocation.getCountry());
regionTv.setText(ipLocation.getRegion());
ispTv.setText(ipLocation.getOrg());
timezoneTv.setText(ipLocation.getTimezone());
countryCallingCodeTv.setText(ipLocation.getCountryCallingCode());
postalTv.setText(ipLocation.getPostal());
location = new LatLng(ipLocation.getLatitude(), ipLocation.getLongitude());
// Toast.makeText(getContext(), "Lat: " + location, Toast.LENGTH_SHORT).show();
}
});
}
//displays the lat/lon of entered address
#Override
public void onMapReady(GoogleMap googleMap) {
Log.d(TAG, "onMapReady: ");
//test adds marker in sydney and moves the camera to location
if (searchViewModel.getResult()) {
try {
marker = googleMap.addMarker(new MarkerOptions().position(location).title("Location"));
marker.setPosition(location);
googleMap.moveCamera(CameraUpdateFactory.newLatLng(location));
googleMap.getMinZoomLevel();
} catch (Exception e) {
Toast.makeText(getContext(), "Exception: " + e, Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(getContext(), "FALSE", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onResume() {
Log.d(TAG, "onResume: map ");
super.onResume();
mapView.onResume();
}
#Override
public void onStart() {
Log.d(TAG, "onStart: map");
super.onStart();
mapView.onStart();
}
#Override
public void onStop() {
Log.d(TAG, "onStop: map");
super.onStop();
mapView.onStop();
}
#Override
public void onPause() {
Log.d(TAG, "onPause: map ");
super.onPause();
mapView.onPause();
}
#Override
public void onDestroy() {
Log.d(TAG, "onDestroy: map");
super.onDestroy();
mapView.onDestroy();
}
public class SearchViewModel extends ViewModel {
private static final String TAG = "SearchViewModel";
private Boolean result = false;
private String input;
private ArrayList<IPLocation> ipLocationsList;
private MutableLiveData<IPLocation> ipLocation;
private MutableLiveData<Double> latResult = new MutableLiveData<>();
private MutableLiveData<Double> lonResult = new MutableLiveData<>();
public SearchViewModel() {
Log.d(TAG, "SearchViewModel: ");
ipLocation = new MutableLiveData<>();
ipLocationsList = new ArrayList<>();
}
public void getIpAddress(String ipAdress) {
Log.d(TAG, "getInfo: Start");
Calendar calendar = Calendar.getInstance();
final Date dateNow = calendar.getTime();
final GetDataService[] getDataService = {RetrofitClientInstance.getRetrofit()
.create(GetDataService.class)};
Call<IPLocation> call = getDataService[0].getLocationByIP(ipAdress);
call.enqueue(new Callback<IPLocation>() {
#Override
public void onResponse(Call<IPLocation> call, Response<IPLocation> response) {
Log.d(TAG, "onResponse: Start");
ipLocation.setValue(new IPLocation(0, response.body().getIp(),
response.body().getCity(), response.body().getRegion(),
response.body().getRegionCode(), response.body().getCountry(), response.body().getCountryName(),
response.body().getContinentCode(), response.body().getInEu(), response.body().getPostal(),
response.body().getLatitude(), response.body().getLongitude(), response.body().getTimezone(),
response.body().getUtcOffset(), response.body().getCountryCallingCode(), response.body().getCurrency(),
response.body().getLanguages(), response.body().getAsn(), response.body().getOrg(), dateNow));
latResult.setValue(response.body().getLatitude());
lonResult.setValue(response.body().getLongitude());
setResult(true);
}
#Override
public void onFailure(Call<IPLocation> call, Throwable t) {
Log.d(TAG, "onFailure: Fail");
}
});
}
public Boolean getResult() {
return result;
}
public void setResult(Boolean result) {
this.result = result;
}
public MutableLiveData<IPLocation> getIpLocation() {
return ipLocation;
}
public MutableLiveData<Double> getLatResult() {
return latResult;
}
public void setLatResult(MutableLiveData<Double> latResult) {
this.latResult = latResult;
}
public MutableLiveData<Double> getLonResult() {
return lonResult;
}
public void setLonResult(MutableLiveData<Double> lonResult) {
this.lonResult = lonResult;
}
}
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/location_title_textview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="#string/location_title"
android:textAlignment="center"
android:textSize="24sp" />
<com.google.android.gms.maps.MapView
android:id="#+id/location_mapview"
android:layout_width="match_parent"
android:layout_height="319dp" />
</LinearLayout>

Save your google map object globally after receiving object from onMapReady(GoogleMap googleMap) callback.
After making an API call and fetching the result, do something like this to your map
LatLng latlng = new LatLng(response.body().getLatitude(), response.body().getLongitude());
MarkerOptions markerOption = new MarkerOption();
markerOptions.setPosition(latlng);
markerOptions.setIcon(*PASS_YOUR_BITMAP_FOR_ICON_HERE*);
markerOptions.title("Location")
Marker marker = googleMap.addMarker(markerOption);
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latlng));

Related

NavigationView with useroffroute MapBox Android

I'm actually trying to use the useroffroute function but it's not working, I saw this other post and it said to NavigationView, only I don't know how to do it exactly. I am currently using this code to detect if the user has left the route, but he is not calling the useroffroute function. What I'm trying to do is that when the user leaves the route he fires a Toast for the user, but unfortunately I was not successful.
public class mapbox extends AppCompatActivity{
private MapView mapView;
Button button;
private static final String TAG = "resultados";
private MapboxNavigation navigation;
private boolean running;
private NavigationMapboxMap map;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Mapbox.getInstance(this, getString(R.string.mapbox_access_token));
setContentView(R.layout.activity_mapbox);
button = findViewById(R.id.button);
MapboxNavigationOptions options = MapboxNavigationOptions.builder().isDebugLoggingEnabled(true).build();
navigation = new MapboxNavigation(getApplicationContext(), getString(R.string.mapbox_access_token), options);
/*
navigation.addOffRouteListener(new OffRouteListener() {
#Override
public void userOffRoute(Location location) {
Toast.makeText(getApplicationContext(), "Off route detected.........", Toast.LENGTH_SHORT).show();
// Make sure you call for a new DirectionsRoute object
// and end by calling MapboxNavigation#startNavigation on a successful
}
});
*/
/*
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(#NonNull MapboxMap mapboxMap) {
mapboxMap.setStyle(Style.MAPBOX_STREETS, new Style.OnStyleLoaded() {
#Override
public void onStyleLoaded(#NonNull Style style) {
// Map is set up and the style has loaded. Now you can add data or make other map adjustments
}
});
}
});
*/
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// From Mapbox to The White House
Point origin = Point.fromLngLat(-38.62882018, -3.78666528);
Point destination = Point.fromLngLat(-38.56038094, -3.7337361F);
NavigationRoute.builder(mapbox.this)
.accessToken(getString(R.string.mapbox_access_token))
.origin(origin)
.destination(destination)
.build()
.getRoute(new Callback<DirectionsResponse>() {
#Override
public void onResponse(Call<DirectionsResponse> call, Response<DirectionsResponse> response) {
Log.i(TAG, response+"");
// Route fetched from NavigationRoute
DirectionsRoute route = response.body().routes().get(0);
// Create a NavigationLauncherOptions object to package everything together
NavigationLauncherOptions options = NavigationLauncherOptions.builder()
.directionsRoute(route)
.shouldSimulateRoute(false)
.build();
// Call this method with Context from within an Activity
NavigationLauncher.startNavigation(mapbox.this, options);
}
#Override
public void onFailure(Call<DirectionsResponse> call, Throwable t) {
}
});
}
});
}
#Override
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
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();
//mapView.onDestroy();
}
}
After many hours looking for a solution, I finally found one. You have to use NavigationViewer to obtain the parameters that the application passes, so you can listen if the user leaves the route. Here's an example:
public class last extends AppCompatActivity implements OnNavigationReadyCallback,
NavigationListener, RouteListener, ProgressChangeListener {
private NavigationView navigationView;
private boolean dropoffDialogShown;
private Location lastKnownLocation;
private List<Point> points = new ArrayList<>();
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
Mapbox.getInstance(this, getString(R.string.mapbox_access_token));
setTheme(R.style.Theme_AppCompat_NoActionBar);
super.onCreate(savedInstanceState);
points.add(Point.fromLngLat(-38.62882018, -3.78666528));
points.add(Point.fromLngLat(-38.56038094, -3.7337361));
setContentView(R.layout.activity_last);
navigationView = findViewById(R.id.navigationView);
navigationView.onCreate(savedInstanceState);
navigationView.initialize(this);
}
#Override
public void onStart() {
super.onStart();
navigationView.onStart();
}
#Override
public void onResume() {
super.onResume();
navigationView.onResume();
}
#Override
public void onLowMemory() {
super.onLowMemory();
navigationView.onLowMemory();
}
#Override
public void onBackPressed() {
// If the navigation view didn't need to do anything, call super
if (!navigationView.onBackPressed()) {
super.onBackPressed();
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
navigationView.onSaveInstanceState(outState);
super.onSaveInstanceState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
navigationView.onRestoreInstanceState(savedInstanceState);
}
#Override
public void onPause() {
super.onPause();
navigationView.onPause();
}
#Override
public void onStop() {
super.onStop();
navigationView.onStop();
}
#Override
protected void onDestroy() {
super.onDestroy();
navigationView.onDestroy();
}
#Override
public void onNavigationReady(boolean isRunning) {
fetchRoute(points.remove(0), points.remove(0));
}
#Override
public void onCancelNavigation() {
// Navigation canceled, finish the activity
finish();
}
#Override
public void onNavigationFinished() {
// Intentionally empty
}
#Override
public void onNavigationRunning() {
// Intentionally empty
}
#Override
public boolean allowRerouteFrom(Point offRoutePoint) {
return true;
}
#Override
public void onOffRoute(Point offRoutePoint) {
Toast.makeText(this, "Off route", Toast.LENGTH_SHORT).show();
}
#Override
public void onRerouteAlong(DirectionsRoute directionsRoute) {
}
#Override
public void onFailedReroute(String errorMessage) {
}
#Override
public void onArrival() {
if (!dropoffDialogShown && !points.isEmpty()) {
showDropoffDialog();
dropoffDialogShown = true; // Accounts for multiple arrival events
Toast.makeText(this, "You have arrived!", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onProgressChange(Location location, RouteProgress routeProgress) {
lastKnownLocation = location;
}
private void startNavigation(DirectionsRoute directionsRoute) {
NavigationViewOptions navigationViewOptions = setupOptions(directionsRoute);
navigationView.startNavigation(navigationViewOptions);
}
private void showDropoffDialog() {
AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setMessage(getString(R.string.dropoff_dialog_text));
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, getString(R.string.dropoff_dialog_positive_text),
(dialogInterface, in) -> fetchRoute(getLastKnownLocation(), points.remove(0)));
alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE, getString(R.string.dropoff_dialog_negative_text),
(dialogInterface, in) -> {
// Do nothing
});
alertDialog.show();
}
private void fetchRoute(Point origin, Point destination) {
NavigationRoute.builder(this)
.accessToken(Mapbox.getAccessToken())
.origin(origin)
.destination(destination)
.alternatives(true)
.build()
.getRoute(new Callback<DirectionsResponse>() {
#Override
public void onResponse(Call<DirectionsResponse> call, Response<DirectionsResponse> response) {
DirectionsResponse directionsResponse = response.body();
if (directionsResponse != null && !directionsResponse.routes().isEmpty()) {
startNavigation(directionsResponse.routes().get(0));
}
}
#Override
public void onFailure(Call<DirectionsResponse> call, Throwable t) {
}
});
}
private NavigationViewOptions setupOptions(DirectionsRoute directionsRoute) {
dropoffDialogShown = false;
NavigationViewOptions.Builder options = NavigationViewOptions.builder();
options.directionsRoute(directionsRoute)
.navigationListener(this)
.progressChangeListener(this)
.routeListener(this)
.shouldSimulateRoute(false);
return options.build();
}
private Point getLastKnownLocation() {
return Point.fromLngLat(lastKnownLocation.getLongitude(), lastKnownLocation.getLatitude());
}
}
XML File:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.mapbox.services.android.navigation.ui.v5.NavigationView
android:id="#+id/navigationView"
android:layout_width="0dp"
android:layout_height="0dp"
app:navigationLightTheme="#style/NavigationViewLight"
app:navigationDarkTheme="#style/NavigationViewDark"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
When I start navigation with multiple waypoints, the navigation stops after reaching first waypoint.
Please suggest changes.`
try{
NavigationRoute.Builder builder = NavigationRoute.builder(this)
.accessToken("pk." + getString(R.string.gh_key))
.baseUrl(getString(R.string.base_url))
.user("gh")
.alternatives(true);
Location lastKnownLocation = new Location(LocationManager.GPS_PROVIDER);
lastKnownLocation.setLatitude(Double.parseDouble(SharePref.getInstance(MapBoxNavActivity.this).getJavaRXPref(getString(R.string.latitude))));
lastKnownLocation.setLongitude(Double.parseDouble(SharePref.getInstance(MapBoxNavActivity.this).getJavaRXPref(getString(R.string.longitude))));
Point location = Point.fromLngLat(lastKnownLocation.getLongitude(), lastKnownLocation.getLatitude());
if (lastKnownLocation.hasBearing()){
// 90 seems to be the default tolerance of the SDK
builder.origin(location, (double) lastKnownLocation.getBearing(), 90.0);
}
else{
builder.origin(location);
}
try {
if(waypoints.size()>0){
for (int i = 0; i < waypoints.size(); i++) {
Point p = waypoints.get(i);
if (i < waypoints.size() - 1) {
try {
builder.addWaypoint(p);
}catch (Exception e){
e.printStackTrace();
}
} else {
builder.destination(p);
}
}
}
}catch (Exception se){
se.printStackTrace();
}
builder.build().getRoute(new SimplifiedCallback() {
#Override
public void onResponse(Call<DirectionsResponse> call, Response<DirectionsResponse> response) {
if (validRouteResponse(response)) {
route = response.body().routes().get(0);
try {
MapboxNavigationOptions.Builder navigationOptions = MapboxNavigationOptions.builder();
NavigationViewOptions.Builder options = NavigationViewOptions.builder();
options.navigationListener(MapBoxNavActivity.this);
options.directionsRoute(route);
options.shouldSimulateRoute(false);
options.directionsProfile(DirectionsCriteria.PROFILE_DRIVING_TRAFFIC);
navigationOptions.enableOffRouteDetection(true);
navigationOptions.snapToRoute(true);
options.navigationOptions(navigationOptions.build());
navigationView.startNavigation(options.build());
}catch (Exception e){
e.printStackTrace();
}
}
}
#Override
public void onFailure(Call<DirectionsResponse> call, Throwable throwable) {
super.onFailure(call, throwable);
Log.i("Fetch route error",throwable.getMessage());
}
});
}
}
catch ( Exception se){
se.printStackTrace();
}
}
`

Can't create handler inside thread that has not called Looper.prepare() in AsyncTask

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

Implement Back Pressed In Android Fragments

I've been stuck in a situation and i need some help over here. There are many articles on this topic here but none of them answered my question. I want to implement onBackPressed() in fragments and show dialog box which shows to exit the application or not. Any help would be appreciated.
LoginFragment.java
public class LoginFragment extends Fragment {
public static final String TAG = LoginFragment.class.getSimpleName();
private EditText mEtEmail;
private EditText mEtPassword;
private Button mBtLogin;
private TextView mTvRegister;
private TextView mTvForgotPassword;
private TextInputLayout mTiEmail;
private TextInputLayout mTiPassword;
private ProgressBar mProgressBar;
private CompositeSubscription mSubscriptions;
private SharedPreferences mSharedPreferences;
#NonNull
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_login,container,false);
mSubscriptions = new CompositeSubscription();
initViews(view);
initSharedPreferences();
return view;
}
private void initViews(View v) {
mEtEmail = v.findViewById(R.id.et_email);
mEtPassword = v.findViewById(R.id.et_password);
mBtLogin = v.findViewById(R.id.btn_login);
mTiEmail = v.findViewById(R.id.ti_email);
mTiPassword = v.findViewById(R.id.ti_password);
mProgressBar = v.findViewById(R.id.progress);
mTvRegister = v.findViewById(R.id.tv_register);
mTvForgotPassword = v.findViewById(R.id.tv_forgot_password);
mBtLogin.setOnClickListener(view -> login());
mTvRegister.setOnClickListener(view -> goToRegister());
mTvForgotPassword.setOnClickListener(view -> showDialog());
}
private void initSharedPreferences() {
mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
}
private void login() {
setError();
String email = mEtEmail.getText().toString();
String password = mEtPassword.getText().toString();
int err = 0;
if (!validateEmail(email)) {
err++;
mTiEmail.setError("Email should be valid !");
}
if (!validateFields(password)) {
err++;
mTiPassword.setError("Password should not be empty !");
}
if (err == 0) {
loginProcess(email,password);
mProgressBar.setVisibility(View.VISIBLE);
} else {
showSnackBarMessage("Enter Valid Details !");
}
}
private void setError() {
mTiEmail.setError(null);
mTiPassword.setError(null);
}
private void loginProcess(String email, String password) {
mSubscriptions.add(NetworkUtil.getRetrofit(email, password).login()
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe(this::handleResponse,this::handleError));
}
private void handleResponse(Response response) {
mProgressBar.setVisibility(View.GONE);
SharedPreferences.Editor editor = mSharedPreferences.edit();
editor.putString(Constants.TOKEN,response.getToken());
editor.putString(Constants.EMAIL,response.getMessage());
editor.apply();
mEtEmail.setText(null);
mEtPassword.setText(null);
Intent intent = new Intent(getActivity(), HomeActivity.class);
startActivity(intent);
}
private void handleError(Throwable error) {
mProgressBar.setVisibility(View.GONE);
if (error instanceof HttpException) {
Gson gson = new GsonBuilder().create();
try {
String errorBody = ((HttpException) error).response().errorBody().string();
Response response = gson.fromJson(errorBody,Response.class);
showSnackBarMessage(response.getMessage());
} catch (IOException e) {
e.printStackTrace();
}
} else {
showSnackBarMessage("No Internet Connection!");
}
}
private void showSnackBarMessage(String message) {
if (getView() != null) {
Snackbar.make(getView(),message,Snackbar.LENGTH_SHORT).show();
}
}
private void goToRegister(){
FragmentTransaction ft = getFragmentManager().beginTransaction();
RegisterFragment fragment = new RegisterFragment();
ft.replace(R.id.fragmentFrame,fragment,RegisterFragment.TAG);
ft.addToBackStack(null).commit();
}
private void showDialog(){
ResetPasswordDialog fragment = new ResetPasswordDialog();
fragment.show(getFragmentManager(), ResetPasswordDialog.TAG);
}
#Override
public void onDestroy() {
super.onDestroy();
mSubscriptions.unsubscribe();
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity implements ResetPasswordDialog.Listener {
public static final String TAG = MainActivity.class.getSimpleName();
private LoginFragment mLoginFragment;
private ResetPasswordDialog mResetPasswordDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
loadFragment();
}
}
private void loadFragment() {
if (mLoginFragment == null) {
mLoginFragment = new LoginFragment();
}
getFragmentManager().beginTransaction().replace(R.id.fragmentFrame, mLoginFragment, LoginFragment.TAG).commit();
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
String data = intent.getData().getLastPathSegment();
Log.d(TAG, "onNewIntent: " + data);
mResetPasswordDialog = (ResetPasswordDialog) getFragmentManager().findFragmentByTag(ResetPasswordDialog.TAG);
if (mResetPasswordDialog != null)
mResetPasswordDialog.setToken(data);
}
#Override
public void onPasswordReset(String message) {
showSnackBarMessage(message);
}
private void showSnackBarMessage(String message) {
Snackbar.make(findViewById(R.id.activity_main), message, Snackbar.LENGTH_SHORT).show();
}
}
In My Login Fragment, I want to show a dialog box "Do you want to exit the application or not". On Yes it dismiss the current fragment and end the activity otherwise it'll remain active. Help please!
You can even try this way
MainActivity.java
#Override
public void onBackPressed() {
if (getFragmentManager() != null && getFragmentManager().getBackStackEntryCount() >= 1) {
String fragmentTag = getFragmentManager().findFragmentById(R.id.frame_container).getTag();
if(fragmentTag.equals(LoginFragment.getTag())){
// show Dialog code
}else{
super.onBackPressed();
}
} else {
super.onBackPressed();
}
}
Add this code in your main activity so that when login fragment is added and you click backpress, then on first if the fragment is added to fragment transaction, then first it finds the fragment and check if its tag is equals to the login fragment tag. Then if both tag matches, then you can show your exit alert dialog.
Android team has prepared a new way of handling the back button pressed on Fragments for us, so you should check this out. It's called OnBackPressedDispatcher.
You need to register OnBackPressedCallback to the fragment where do you want to intercept back button pressed. You can do it like this inside of the Fragment:
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
OnBackPressedCallback callback = new OnBackPressedCallback(true) {
#Override
public void handleOnBackPressed() {
//show exit dialog
}
};
requireActivity().getOnBackPressedDispatcher().addCallback(this, callback);
}

I am trying to Navigate optimize route but getting Error in Logcat

"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)

How to display sqlite database in the form of cards in android?

This is my code how i store the data in sqlite database.Now i want that all the data from the database display in the form of cards in other activity suppose when i press showdb button then the data displayed.
public class ConfigureNode extends AppCompatActivity implements
LocationListener,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private static final String TAG = "LocationActivity";
private static final long INTERVAL = 1000 * 10;
private static final long FASTEST_INTERVAL = 1000 * 5;
private SQLiteDatabase db;
Button btnFusedLocation, btnPushData;
TextView tvLocation;
EditText Latval, LongVal,NodeId;
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
Location mCurrentLocation;
String mLastUpdateTime;
public String DBPath;
public static String DBName = "sample";
public static final int version = '1';
public static Context currentContext;
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(INTERVAL);
mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
createDatabase();
Log.d(TAG, "onCreate ...............................");
//show error dialog if GoolglePlayServices not available
if (!isGooglePlayServicesAvailable()) {
finish();
}
createLocationRequest();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
setContentView(R.layout.activity_configure_node);
tvLocation = (TextView) findViewById(R.id.tvLocation);
btnFusedLocation = (Button) findViewById(R.id.btnShowLocation);
Latval = (EditText) findViewById(R.id.latVal);
LongVal = (EditText) findViewById(R.id.longVal);
NodeId=(EditText)findViewById(R.id.NodeId);
btnPushData = (Button) findViewById(R.id.btnPushLoc);
btnPushData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
insertIntoDB();
}
});
btnFusedLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
updateUI();
}
});
}
#Override
public void onStart() {
super.onStart();
Log.d(TAG, "onStart fired ..............");
mGoogleApiClient.connect();
}
#Override
public void onStop() {
super.onStop();
Log.d(TAG, "onStop fired ..............");
mGoogleApiClient.disconnect();
Log.d(TAG, "isConnected ...............: " + mGoogleApiClient.isConnected());
}
private boolean isGooglePlayServicesAvailable() {
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (ConnectionResult.SUCCESS == status) {
return true;
} else {
GooglePlayServicesUtil.getErrorDialog(status, this, 0).show();
return false;
}
}
#Override
public void onConnected(Bundle bundle) {
Log.d(TAG, "onConnected - isConnected ...............: " + mGoogleApiClient.isConnected());
startLocationUpdates();
}
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) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
PendingResult<Status> pendingResult = LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, (com.google.android.gms.location.LocationListener) this);
Log.d(TAG, "Location update started ..............: ");
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.d(TAG, "Connection failed: " + connectionResult.toString());
}
#Override
public void onLocationChanged(Location location) {
Log.d(TAG, "Firing onLocationChanged..............................................");
mCurrentLocation = location;
mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
updateUI();
}
private void updateUI() {
Log.d(TAG, "UI update initiated .............");
if (null != mCurrentLocation) {
String lat = String.valueOf(mCurrentLocation.getLatitude());
String lng = String.valueOf(mCurrentLocation.getLongitude());
tvLocation.setText("At Time: " + mLastUpdateTime + "\n" +
"Latitude: " + lat + "\n" +
"Longitude: " + lng + "\n" +
"Accuracy: " + mCurrentLocation.getAccuracy() + "\n" +
"Provider: " + mCurrentLocation.getProvider());
LongVal.setText(lng);
Latval.setText(lat);
} else {
Toast.makeText(ConfigureNode.this,"location not detected ",Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onPause() {
super.onPause();
stopLocationUpdates();
}
protected void stopLocationUpdates() {
LocationServices.FusedLocationApi.removeLocationUpdates(
mGoogleApiClient, (LocationListener) this);
Log.d(TAG, "Location update stopped .......................");
}
#Override
public void onResume() {
super.onResume();
if (mGoogleApiClient.isConnected()) {
startLocationUpdates();
Log.d(TAG, "Location update resumed .....................");
}
}
protected void createDatabase(){
db=openOrCreateDatabase("PersonDB", Context.MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS persons(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, name VARCHAR,address VARCHAR,NodeId VARCHAR);");
}
protected void insertIntoDB(){
String name = Latval.getText().toString().trim();
String add = LongVal.getText().toString().trim();
String Nodid=NodeId.getText().toString().trim();
if(name.equals("") || add.equals("")||Nodid.equals("")){
Toast.makeText(getApplicationContext(),"Please fill all fields", Toast.LENGTH_LONG).show();
return;
}
String query = "INSERT INTO persons (name,address,NodeId) VALUES('"+name+"', '"+add+"', '"+Nodid+"');";
db.execSQL(query);
Toast.makeText(getApplicationContext(),"Saved Successfully", Toast.LENGTH_LONG).show();
}
}
From what I can see you have added data to your database. You now need to retrieve data from your database via a query.
Imagine I was storing a bunch of templates in a database, and then want to display all of these in cards or a list.
What I tend to do is create an object, such as Template.java. This object will have getter and setter methods.
I then perform a query on the database fetching all data in there and assigning each one to these Template objects.
I can then create a custom list view for example to display them in a list of cards. To create this custom list I give it an array of all the Template objects I have fetched from the database and in this custom adapter class set the values and styling.
Here are some coding examples:
Fetching from database and creating custom list:
public void populateListView() {
templates.clear();
final String query = "SELECT * FROM tableTemplates ";
Cursor c1 = db.selectQuery(query);
if (c1 != null && c1.getCount() != 0) {
if (c1.moveToFirst()) {
do {
template = new Template();
template.setTemplateName(c1.getString(c1
.getColumnIndex("templateName")));
template.setBuildingNumber(c1.getString(c1
.getColumnIndex("buildingNumber")));
template.setGroupNumber(c1.getString(c1
.getColumnIndex("groupNumber")));
template.setRemote(c1.getString(c1
.getColumnIndex("remote")));
template.setFrequency(c1.getString(c1
.getColumnIndex("frequency")));
templates.add(template);
} while (c1.moveToNext());
}
}
c1.close();
adapter = new TemplateCustomAdapter(
getApplicationContext(), templates);
presetList.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
The custom list adapter:
public class TemplateCustomAdapter extends BaseAdapter {
private Context context;
private ArrayList<Template> templateList;
public TemplateCustomAdapter(Context context, ArrayList<Template> list) {
this.context = context;
templateList = list;
}
#Override
public int getCount() {
return templateList.size();
}
#Override
public Object getItem(int position) {
return templateList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
/**
* Here we inflate our layout with the view row xml file.
* What the file does is set the look of each row of the list view.
* */
#Override
public View getView(int position, View convertView, ViewGroup arg2) {
final Template template = templateList.get(position);
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.view_row, null);
}
/**
* Set the layout components with the object variable and return to the activity/fragment.
* */
final TextView templateName = (TextView) convertView.findViewById(R.id.name);
templateName.setText(template.getTemplateName());
return convertView;
}
}
This may help with the list adapter

Categories