I have the following class:
...
public class FragmentMapa extends Fragment {
/*
* Atributos
*/
private static String LOG_TAG = "FragmentMapa";
private HomeActivity homeActivity;
private GoogleMap mMapa;
private DrawerLayout mDrawer;
private ActionBarDrawerToggle mDrawerToggle;
private ListView mDrawerList;
private ListView mDrawerRightList;
private RelativeLayout mDrawerRelativeLayout;
private String[] mRightDrawerMenuTitles;
private ImageView mDiputacionLogo;
private IncidenciasFetchAsyncTask mFetchIncidenciasTask;
private Incidencias mIs;
private CamarasFetchAsyncTask mFetchCamarasTask;
private Camaras mCams;
private ViabilidadesInvernalesFetchAsyncTask mFetchViabilidadesInvernalesTask;
private ViabilidadesInvernales mVis;
private static LatLng POS_CENTRAL = new LatLng(43.243968,-2.896957);
private static LatLng limiteSurOesteBizkaia = new LatLng(42.895853,-3.594589);
private static LatLng limiteNorEsteBizkaia = new LatLng(43.540351,-2.180099);
private static final LatLngBounds BOUNDS = new LatLngBounds(limiteSurOesteBizkaia, limiteNorEsteBizkaia);
private ArrayList<Marker> markersIncidencias = new ArrayList<Marker>();
private ArrayList<Marker> markersObras = new ArrayList<Marker>();
private ArrayList<Marker> markersCamaras = new ArrayList<Marker>();
private ArrayList<Marker> markersViabilidadInvernal = new ArrayList<Marker>();
/*
* Métodos
*/
public FragmentMapa() {
}
#Override
public void onAttach (Activity activity) {
super.onAttach(activity);
homeActivity = (HomeActivity) activity;
mRightDrawerMenuTitles = getResources().getStringArray(R.array.mapa_submenu_options);
mDrawer = homeActivity.getmDrawer();
mDrawerRightList = homeActivity.getmDrawerRightList();
mDrawerRightList.setAdapter(new ArrayAdapter<String>(
homeActivity.getSupportActionBar().getThemedContext(),
R.layout.rightdrawer_map_list_item,
mRightDrawerMenuTitles
));
mDrawerRightList.setOnItemClickListener(new DrawerItemClickListener());
}
#Override
public void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.mapa, container, false);
setupMapIfNeeded();
return rootView;
}
private void setupMapIfNeeded() {
if( mMapa == null ){
SupportMapFragment smf = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.mapaPrincipal);
if( smf != null ){
//Toast.makeText(getActivity(), "VAAAMOOSS", Toast.LENGTH_SHORT).show();
mMapa = smf.getMap();
}/*else{
Toast.makeText(getActivity(), "smf es null...", Toast.LENGTH_SHORT).show();
}*/
if( mMapa != null ){
setupMap();
}
}
}
private void setupMap() {
//Toast.makeText(getActivity(), "A configurar el mapa!!", Toast.LENGTH_SHORT).show();
CameraPosition camPos;
camPos = new CameraPosition.Builder()
.target(POS_CENTRAL)
.zoom((float) 9.5)
.build();
final CameraUpdate camUpd =
CameraUpdateFactory.newCameraPosition(camPos);
mMapa.animateCamera(camUpd);
mMapa.setOnCameraChangeListener(new OnCameraChangeListener() {
#Override
public void onCameraChange(CameraPosition newPos) {
float maxZoom = 17.0f;
if( !BOUNDS.contains(newPos.target) ){
//Mover la cámara al centro si se
//va más allá de los límites
mMapa.animateCamera(camUpd);
}
if(newPos.zoom > maxZoom){
mMapa.animateCamera(CameraUpdateFactory.zoomTo(maxZoom));
}
}
});
mMapa.setOnInfoWindowClickListener( new OnInfoWindowClickListener(){
public void onInfoWindowClick(Marker aMarker) {
Toast.makeText(getActivity(), "info window pulsado", Toast.LENGTH_SHORT).show();
if( markersCamaras.contains(aMarker) ){
Camara c = mCams.getCamaraByCoord(aMarker.getPosition());
homeActivity.showCameraFragment(c);
}
}
});
}
#Override
public void onActivityCreated (Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onViewStateRestored (Bundle savedInstanceState) {
super.onViewStateRestored(savedInstanceState);
}
#Override
public void onStart () {
super.onStart();
}
#Override
public void onResume () {
super.onResume();
}
#Override
public void onPause () {
super.onPause();
}
#Override
public void onStop () {
super.onStop();
}
#Override
public void onDestroyView () {
super.onDestroyView();
}
#Override
public void onDestroy () {
super.onDestroy();
}
#Override
public void onDetach () {
super.onDetach();
}
/* The click listener for ListView in the navigation drawer */
private class DrawerItemClickListener implements OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final int thePos = position;
mDrawer.setDrawerListener( new DrawerLayout.SimpleDrawerListener(){
#Override
public void onDrawerClosed(View drawerView) {
boolean wasChecked = !mDrawerRightList.isItemChecked(thePos);
//Toast.makeText(homeActivity, "Item pulsado: " + wasChecked, Toast.LENGTH_SHORT).show();
mDrawerRightList.setItemChecked(thePos, !wasChecked);
switch (thePos) {
case 0:
//Incidencias
//Toast.makeText(homeActivity, "Incidencias", Toast.LENGTH_SHORT).show();
if(!wasChecked){
//Toast.makeText(homeActivity, "Incidencias estaba sin pulsar", Toast.LENGTH_SHORT).show();
getIncidenciasObras();
introducirIncidencias();
}else{
//Toast.makeText(homeActivity, "Incidencias estaba pulsado", Toast.LENGTH_SHORT).show();
removeIncidenciasMarkers();
}
break;
case 1:
//Obras
//Toast.makeText(homeActivity, "Obras", Toast.LENGTH_SHORT).show();
if(!wasChecked){
//Toast.makeText(homeActivity, "Obras estaba sin pulsar", Toast.LENGTH_SHORT).show();
getIncidenciasObras();
introducirObras();
}else{
//Toast.makeText(homeActivity, "Obras estaba pulsado", Toast.LENGTH_SHORT).show();
removeObrasMarkers();
}
break;
case 2:
//Cámaras
//Toast.makeText(homeActivity, "Cámaras", Toast.LENGTH_SHORT).show();
if(!wasChecked) {
getCamaras();
introducirCamaras();
}else
removeCamarasMarkers();
break;
case 3:
//Viabilidad invernal
//Toast.makeText(homeActivity, "Viabilidad invernal", Toast.LENGTH_SHORT).show();
if(!wasChecked){
getViabilidadesInvernales();
introducirViabilidadInvernal();
}else
removeViabilidadInvernalMarkers();
break;
default:
//Toast.makeText(homeActivity, "Default", Toast.LENGTH_SHORT).show();
break;
}
}
});
if(mDrawer.isDrawerOpen(Gravity.END))
mDrawer.closeDrawer(mDrawerRightList);
}
}
private void getViabilidadesInvernales(){
mVis = ViabilidadesInvernales.getInstance();
if(mVis.isEmptyViabilidadesInvernales()){
mFetchViabilidadesInvernalesTask = new ViabilidadesInvernalesFetchAsyncTask(homeActivity);
try {
mVis = mFetchViabilidadesInvernalesTask.execute("es").get();
} catch (InterruptedException e) {
Log.e(LOG_TAG, "Error InterruptedException: " + e.getMessage());
e.printStackTrace();
} catch (ExecutionException e) {
Log.e(LOG_TAG, "Error ExecutionException: " + e.getMessage());
e.printStackTrace();
}
}
}
...
private void introducirViabilidadInvernal() {
if(markersViabilidadInvernal.isEmpty()){
Marker aMarker;
for (ViabilidadInvernal vi : mVis.getViabilidades()) {
String estado = "";
BitmapDescriptor icon;
if(vi.getEstado() == PuertoEstado.ABIERTO){
estado = getResources().getString(R.string.mapa_puerto_abierto);
icon = BitmapDescriptorFactory.fromResource(R.drawable.marker_puertoabierto);
}else{
//vi.getEstado() == PuertoEstado.CERRADO
estado = getResources().getString(R.string.mapa_puerto_cerrado);
icon = BitmapDescriptorFactory.fromResource(R.drawable.marker_puertocerrado);
}
aMarker = mMapa.addMarker(new MarkerOptions()
.position(vi.getCoord())
.title(vi.getT())
.snippet(estado)
.icon(icon));
markersViabilidadInvernal.add(aMarker);
}
}
}
private void removeViabilidadInvernalMarkers() {
for(Marker aMarker : markersViabilidadInvernal){
aMarker.remove();
}
}
...
private class ViabilidadesInvernalesFetchAsyncTask extends AsyncTask<String, Void, ViabilidadesInvernales>{
private ProgressDialog mPd;
private HomeActivity ownerActivity;
private Context context;
private Exception exceptionToBeThrown;
public ViabilidadesInvernalesFetchAsyncTask(Activity activity){
this.ownerActivity = (HomeActivity) activity;
context = activity;
this.exceptionToBeThrown = null;
mPd = new ProgressDialog(context);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
mPd.setTitle("cargando");
mPd.setMessage("miralo");
//mPd.setTitle(getResources().getString(R.string.mapa_cargando_titulo));
//mPd.setMessage(getResources().getString(R.string.mapa_cargando, getResources().getString(R.string.mapa_cargando_elemento_viabilidad)));
mPd.setCancelable(false);
mPd.setIndeterminate(true);
mPd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mPd.show();
}
#Override
protected ViabilidadesInvernales doInBackground(String... params) {
String idioma = params[0];
if(!idioma.equalsIgnoreCase("es") && !idioma.equalsIgnoreCase("eu")){
idioma = "es";
}
SystemClock.sleep(5000);
ViabilidadesInvernalesParser vip = new ViabilidadesInvernalesParser();
ViabilidadesInvernales lasViabilidades = vip.parse(idioma);
Log.d(LOG_TAG, lasViabilidades.toString());
ViabilidadesInvernales vis = ViabilidadesInvernales.getInstance();
return vis;
}
#Override
protected void onPostExecute(ViabilidadesInvernales vis) {
super.onPostExecute(vis);
mVis = vis;
if(mPd != null){
mPd.dismiss();
}
// Check if exception exists.
//if (exceptionToBeThrown != null) {
//TODO
//ownerActivity.handleXXX();
//throw exceptionToBeThrown;
//}
}
}
....
}
The aim is to show a Dialog (ProgressDialog) when an AsyncTask is executed, so that the Dialog remains in front of the UI for a moment and then, the map (which was being shown previously) returns to the front. More exactly, you launch the application (home activity), you open the left drawer, press Mapa and go to the current fragment. An empty map is shown. You open the right drawer and press a button. Just afterwards, the process of launching AsyncTask is executed (and my desired ProgressDialog).
I don't know why, but the ProgressDialog is not being shown, but I have realised that the "sleep" process is ok (and the AsyncTask is executed properly every time).
Can anybody lend me a hand?
PS: My main activity (HomeActivity) launches fragments. The main activity has two drawers: left drawer is always visible, and right drawer is only visible when launching the FragmentMapa (the fragment I'm showing you right now). Might this issue be due to the Drawer behaviour?
THANK YOU SO MUCH
SOLVED. Anyone who faces this problem, check the following post: https://stackoverflow.com/a/3291713/828551.
You must create an interface, create an instance of it within the AsyncTask and implement the interface the main class where you launch the AsyncTask.
Related
I am trying to launch the NavigationLauncher.startNavigation, from another activity but am unable to do so. I have a button in the second activity which I want to use to start the navigation.
Any suggestions are welcome. Thanks
Here is my code:
/*
fabstart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
boolean simulateRoute = false;
NavigationLauncherOptions options = NavigationLauncherOptions.builder()
.directionsRoute(route)
.shouldSimulateRoute(simulateRoute)
.build();
// Call this method with Context from within an Activity
NavigationLauncher.startNavigation(MainActivity.this, options);
}
});
*/
fabstart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, Before_Go.class);
startActivity(intent);
// Here is where I want to go to a new activity, inside this activity have a button to
// launch the "NavigationLauncher.startNavigation"
}
});
NavigationLauncher.startnavigation() opens a new activity that handles the navigation. Therefore it does not matter from where it is called. However, wherever it is called from, the NavigationLauncher must be defined, and the options object that is passed as the second parameter has to contain the directionsRoute object.
Can you please share code of the activity from which you call it, as well as how you initialize and define the options object?
thanks for your response to my question. I am new to stakoverflow, so i hope i get this additional posting of code right.
MainActivity
public class MainActivity extends AppCompatActivity implements OnMapReadyCallback, PermissionsListener,
MapboxMap.OnMapLongClickListener, OnRouteSelectionChangeListener {
private static final int REQUEST_CODE_AUTOCOMPLETE = 1;
private static final int ONE_HUNDRED_MILLISECONDS = 100;
//private static final String DROPPED_MARKER_LAYER_ID = "DROPPED_MARKER_LAYER_ID";
//Mapbox
private MapView mapView;
private MapboxMap mapboxMap;
private LocationComponent locationComponent;
private PermissionsManager permissionsManager;
private LocationEngine locationEngine;
private long DEFAULT_INTERVAL_IN_MILLISECONDS = 1000L;
private long DEFAULT_MAX_WAIT_TIME = DEFAULT_INTERVAL_IN_MILLISECONDS * 5;
private final MainActivityLocationCallback callback = new MainActivityLocationCallback(this);
private NavigationMapRoute mapRoute;
private DirectionsRoute route;
private String symbolIconId = "symbolIconId";
private String geojsonSourceLayerId = "geojsonSourceLayerId";
private StyleCycle styleCycle = new StyleCycle();
CarmenFeature selectedCarmenFeature;
CarmenFeature feature;
Layer layer;
private static final String TAG = "DirectionsActivity";
// variables
private FloatingActionButton fablocation;
private FloatingActionButton fabstart;
private FloatingActionButton fabRemoveRoute;
private FloatingActionButton fabStyles;
private TextView search;
private TextView kmDisplay;
private TextView timeDisplay;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Mapbox.getInstance(this, getString(R.string.access_token));
setContentView(R.layout.activity_main);
mapView = findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(this);
search=findViewById(R.id.search);
kmDisplay = findViewById(R.id.kmDisplay);
timeDisplay = findViewById(R.id.timeDisplay);
fablocation=findViewById(R.id.fabLocation);
fabstart=findViewById(R.id.fabStart);
fabRemoveRoute=findViewById(R.id.fabRemoveRoute);
fabStyles=findViewById(R.id.fabStyles);
fablocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Location lastKnownLocation = mapboxMap.getLocationComponent().getLastKnownLocation();
// Move map camera back to current device location
mapboxMap.animateCamera(CameraUpdateFactory.newCameraPosition(
new CameraPosition.Builder()
.target(new LatLng(lastKnownLocation.getLatitude(), lastKnownLocation.getLongitude()))
.zoom(15)
.build()), 3000);
}
});
}
#Override
public boolean onMapLongClick(#NonNull LatLng point) {
vibrate();
Point destinationPoint = Point.fromLngLat(point.getLongitude(), point.getLatitude());
Point originPoint = Point.fromLngLat(locationComponent.getLastKnownLocation().getLongitude(),
locationComponent.getLastKnownLocation().getLatitude());
GeoJsonSource source = mapboxMap.getStyle().getSourceAs("destination-source-id");
if (source != null) {
source.setGeoJson(Feature.fromGeometry(destinationPoint));
} else {
// Use the map camera target's coordinates to make a reverse geocoding search
reverseGeocode(Point.fromLngLat(point.getLongitude(), point.getLatitude()));
}
getRoute(originPoint, destinationPoint);
if(destinationPoint !=originPoint) {
fabRemoveRoute.setOnClickListener(new View.OnClickListener() {
#SuppressLint("RestrictedApi")
#Override
public void onClick(View view) {
removeRouteAndMarkers();
fabstart.setVisibility(View.INVISIBLE);
fabRemoveRoute.setVisibility(View.INVISIBLE);
//fablocation.setVisibility(View.INVISIBLE);
kmDisplay.setText("");
timeDisplay.setText("");
search.setText(String.format(getString(R.string.hint_where_to)));
Location lastKnownLocation = mapboxMap.getLocationComponent().getLastKnownLocation();
// Move map camera back to current device location
mapboxMap.animateCamera(CameraUpdateFactory.newCameraPosition(
new CameraPosition.Builder()
.target(new LatLng(lastKnownLocation.getLatitude(), lastKnownLocation.getLongitude()))
.zoom(15)
.build()), 3000);
}
});
}
//imageView.setEnabled(true);
//imageView.setBackgroundResource(R.color.mapboxBlue);
return true;
}
private void getRoute(Point origin, Point destination) {
NavigationRoute.builder(this)
.accessToken(Mapbox.getAccessToken())
.origin(origin)
.destination(destination)
.voiceUnits(DirectionsCriteria.METRIC)
.alternatives(true)
.build()
.getRoute(new Callback<DirectionsResponse>() {
#SuppressLint("RestrictedApi")
#Override
public void onResponse(Call<DirectionsResponse> call, Response<DirectionsResponse> response) {
// You can get the generic HTTP info about the response
if (response.isSuccessful()
&& response.body() != null
&& !response.body().routes().isEmpty()) {
List<DirectionsRoute> routes = response.body().routes();
mapRoute.addRoutes(routes);
//routeLoading.setVisibility(View.INVISIBLE);
fabRemoveRoute.setVisibility(View.VISIBLE);
fablocation.setVisibility(View.VISIBLE);
fabstart.setVisibility(View.VISIBLE);
route = response.body().routes().get(0);
routeCalcs();
}
// Once you have the route zoom the camera out to show the route within the bounds of the device
mapboxMap.easeCamera(CameraUpdateFactory.newLatLngBounds(
new LatLngBounds.Builder()
.include(new LatLng(origin.latitude(), origin.longitude()))
.include(new LatLng(destination.latitude(), destination.longitude()))
.build(), 150), 4000);
}
#Override
public void onFailure(Call<DirectionsResponse> call, Throwable throwable) {
Log.e(TAG, "Error: " + throwable.getMessage());
}
});
}
private void removeRouteAndMarkers() {
mapRoute.removeRoute();
toggleLayer();
}
#Override
public void onNewPrimaryRouteSelected(DirectionsRoute directionsRoute) {
route = directionsRoute;
routeCalcs();
}
private void routeCalcs(){
// rounds the kilometer to zero decimals
kmDisplay.setText((int) Math.ceil(route.distance()/1000) + " km");
//Log.d(TAG1,(int) Math.ceil(currentRoute.distance()/1000) + " km");
// This converts to output of duration() in seconds to minutes and hours format
int minutes = (int) (route.duration() / 60);
long hour = TimeUnit.MINUTES.toHours(minutes);
long remainMinute = minutes - TimeUnit.HOURS.toMinutes(hour);
if (hour >= 1) {
timeDisplay.setText(String.format(getString(R.string.hours_textview),hour)
+ String.format(getString(R.string.minutes_textview),remainMinute));
} else {
timeDisplay.setText(String.format(getString(R.string.minutes_textview), remainMinute));
}
}
private void reverseGeocode(Point point) {
if (selectedCarmenFeature == null) {
try {
MapboxGeocoding client = MapboxGeocoding.builder()
.accessToken(getString(R.string.access_token))
.query(Point.fromLngLat(point.longitude(), point.latitude()))
.geocodingTypes(GeocodingCriteria.TYPE_ADDRESS)
.build();
client.enqueueCall(new Callback<GeocodingResponse>() {
#Override
public void onResponse(Call<GeocodingResponse> call, Response<GeocodingResponse> response) {
if (response.body() != null) {
List<CarmenFeature> results = response.body().features();
if (results.size() > 0) {
feature = results.get(0);
// If the geocoder returns a result, we take the first in the list and show a Toast with the place name.
mapboxMap.getStyle(new Style.OnStyleLoaded() {
#Override
public void onStyleLoaded(#NonNull Style style) {
if (style.getLayer("SYMBOL_LAYER_ID") != null) {
search.setText(feature.placeName());
}
}
});
} else {
Toast.makeText(MainActivity.this,
getString(R.string.location_picker_dropped_marker_snippet_no_results), Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onFailure(Call<GeocodingResponse> call, Throwable throwable) {
Timber.e("Geocoding Failure: %s", throwable.getMessage());
}
});
} catch (ServicesException servicesException) {
Timber.e("Error geocoding: %s", servicesException.toString());
servicesException.printStackTrace();
}
}
}
#Override
public void onMapReady(#NonNull MapboxMap mapboxMap) {
this.mapboxMap = mapboxMap;
mapboxMap.setStyle(Style.MAPBOX_STREETS, new Style.OnStyleLoaded() {
#Override
public void onStyleLoaded(#NonNull Style style){
mapRoute = new NavigationMapRoute(null, mapView, mapboxMap);
mapRoute.setOnRouteSelectionChangeListener(MainActivity.this::onNewPrimaryRouteSelected);
mapboxMap.addOnMapLongClickListener(MainActivity.this);
initializeLocationComponent(style);
// Add the symbol layer icon to map for future use
style.addImage(symbolIconId, BitmapFactory.decodeResource(
MainActivity.this.getResources(), R.drawable.mapbox_marker_icon_default));
// Create an empty GeoJSON source using the empty feature collection
setUpSource(style);
// Set up a new symbol layer for displaying the searched location's feature coordinates
setupLayer(style);
fabStyles.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mapboxMap != null) {
mapboxMap.setStyle(styleCycle.getNextStyle());
}
}
});
initSearchFab();
}
});
// This is the code in the docs, but this launches the turn by turn navigation inside this activity
// and this is not what I need
/* fabstart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
boolean simulateRoute = false;
NavigationLauncherOptions options = NavigationLauncherOptions.builder()
.directionsRoute(route)
.shouldSimulateRoute(simulateRoute)
.build();
// Call this method with Context from within an Activity
NavigationLauncher.startNavigation(MainActivity.this, options);
}
});*/
fabstart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, Before_Go.class);
startActivity(intent);
// Here is where I want to go to a new activity, inside this activity have a button to
// launch the "NavigationLauncher.startNavigation"
}
});
}
private static class StyleCycle {
private static final String[] STYLES = new String[] {
Style.MAPBOX_STREETS,
Style.OUTDOORS,
Style.LIGHT,
Style.DARK,
//Style.SATELLITE_STREETS,
Style.TRAFFIC_DAY,
Style.TRAFFIC_NIGHT
};
private int index;
private String getNextStyle() {
index++;
if (index == STYLES.length) {
index = 0;
}
return getStyle();
}
private String getStyle() {
return STYLES[index];
}
}
private void initSearchFab() {
findViewById(R.id.search).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new PlaceAutocomplete.IntentBuilder()
.accessToken(Mapbox.getAccessToken())
.placeOptions(PlaceOptions.builder()
.backgroundColor(Color.parseColor("#EEEEEE"))
.limit(10)
//.addInjectedFeature(home)
//.addInjectedFeature(work)
.build(PlaceOptions.MODE_CARDS))
.build(MainActivity.this);
startActivityForResult(intent, REQUEST_CODE_AUTOCOMPLETE);
}
});
}
#SuppressWarnings( {"MissingPermission"})
private void initializeLocationComponent(#NonNull Style loadedMapStyle) {
// Check if permissions are enabled and if not request
if (PermissionsManager.areLocationPermissionsGranted(this)) {
locationComponent = mapboxMap.getLocationComponent();
// Set the LocationComponent activation options
LocationComponentActivationOptions locationComponentActivationOptions =
LocationComponentActivationOptions.builder(this, loadedMapStyle)
.useDefaultLocationEngine(false)
.build();
// Activate with the LocationComponentActivationOptions object
locationComponent.activateLocationComponent(locationComponentActivationOptions);
locationComponent.setLocationComponentEnabled(true);
locationComponent.setRenderMode(RenderMode.NORMAL);
locationComponent.setCameraMode(CameraMode.TRACKING);
//locationComponent.zoomWhileTracking(10d);
initLocationEngine();
} else {
permissionsManager = new PermissionsManager(this);
permissionsManager.requestLocationPermissions(this);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK && requestCode == REQUEST_CODE_AUTOCOMPLETE) {
// Retrieve selected location's CarmenFeature
selectedCarmenFeature = PlaceAutocomplete.getPlace(data);
search.setText(selectedCarmenFeature.placeName());
// Create a new FeatureCollection and add a new Feature to it using selectedCarmenFeature above.
// Then retrieve and update the source designated for showing a selected location's symbol layer icon
if (mapboxMap != null) {
Style style = mapboxMap.getStyle();
if (style != null) {
GeoJsonSource source = style.getSourceAs(geojsonSourceLayerId);
if (source != null) {
source.setGeoJson(FeatureCollection.fromFeatures(
new Feature[] {Feature.fromJson(selectedCarmenFeature.toJson())}));
}
// Move map camera to the selected location
mapboxMap.animateCamera(CameraUpdateFactory.newCameraPosition(
new CameraPosition.Builder()
.target(new LatLng(((Point) selectedCarmenFeature.geometry()).latitude(),
((Point) selectedCarmenFeature.geometry()).longitude()))
.zoom(14)
.build()), 4000);
}
}
}
}
#SuppressLint("MissingPermission")
private void vibrate() {
Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
if (vibrator == null) {
return;
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
vibrator.vibrate(VibrationEffect.createOneShot(ONE_HUNDRED_MILLISECONDS, VibrationEffect.DEFAULT_AMPLITUDE));
} else {
vibrator.vibrate(ONE_HUNDRED_MILLISECONDS);
}
}
/**
* Set up the LocationEngine and the parameters for querying the device's location
*/
#SuppressLint("MissingPermission")
private void initLocationEngine() {
locationEngine = LocationEngineProvider.getBestLocationEngine(this);
LocationEngineRequest request = new LocationEngineRequest.Builder(DEFAULT_INTERVAL_IN_MILLISECONDS)
.setPriority(LocationEngineRequest.PRIORITY_HIGH_ACCURACY)
.setMaxWaitTime(DEFAULT_MAX_WAIT_TIME).build();
locationEngine.requestLocationUpdates(request, callback, getMainLooper());
locationEngine.getLastLocation(callback);
}
#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) {
if (mapboxMap.getStyle() != null) {
initializeLocationComponent(mapboxMap.getStyle());
}
} else {
Toast.makeText(this, R.string.user_location_permission_not_granted, Toast.LENGTH_LONG).show();
finish();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
permissionsManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
private static class MainActivityLocationCallback
implements LocationEngineCallback<LocationEngineResult> {
private final WeakReference<MainActivity> activityWeakReference;
MainActivityLocationCallback(MainActivity activity) {
this.activityWeakReference = new WeakReference<>(activity);
}
#Override
public void onSuccess(LocationEngineResult result) {
MainActivity activity = activityWeakReference.get();
if (activity != null) {
Location location = result.getLastLocation();
if (location == null) {
return;
}
if (activity.mapboxMap != null && result.getLastLocation() != null) {
activity.mapboxMap.getLocationComponent().forceLocationUpdate(result.getLastLocation());
}
}
}
#Override
public void onFailure(#NonNull Exception exception) {
Timber.d(exception.getLocalizedMessage());
MainActivity activity = activityWeakReference.get();
if (activity != null) {
Toast.makeText(activity, exception.getLocalizedMessage(),
Toast.LENGTH_SHORT).show();
}
}
}
/**
* Adds the GeoJSON source to the map
*/
private void setUpSource(#NonNull Style loadedMapStyle) {
loadedMapStyle.addSource(new GeoJsonSource(geojsonSourceLayerId));
}
/**
* Setup a layer with maki icons, eg. west coast city.
*/
private void setupLayer(#NonNull Style loadedMapStyle) {
loadedMapStyle.addLayer(new SymbolLayer("SYMBOL_LAYER_ID", geojsonSourceLayerId).withProperties(
iconImage(symbolIconId),
iconOffset(new Float[] {0f, -8f})
));
}
// This method will remove the destination icon
private void toggleLayer() {
mapboxMap.getStyle(new Style.OnStyleLoaded() {
#Override
public void onStyleLoaded(#NonNull Style style) {
layer = style.getLayer("SYMBOL_LAYER_ID");
if (layer != null) {
if (VISIBLE.equals(layer.getVisibility().getValue())) {
layer.setProperties(visibility(NONE));
} else {
layer.setProperties(visibility(VISIBLE));
}
}
}
});
}
// Add the mapView lifecycle to the activity's lifecycle methods
#Override
public void onResume() {
super.onResume();
mapView.onResume();
}
#Override
protected void onStart() {
super.onStart();
mapView.onStart();
if (mapRoute != null) {
mapRoute.onStart();
}
}
#Override
protected void onStop() {
super.onStop();
mapView.onStop();
if (mapRoute != null) {
mapRoute.onStop();
}
}
#Override
public void onPause() {
super.onPause();
mapView.onPause();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
#Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
}
Before_Go - this is the activity where i want to click the button and launch the navigationlauncher
public class Before_Go extends AppCompatActivity {
Button btnGo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_before__go);
btnGo=findViewById(R.id.btnGo);
btnGo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent btnGo = new Intent(Before_Go.this, Go.class);
startActivity(btnGo);
}
});
}
}
GoActivity, this is where the navigation launcher needs to launch after the button click in the Before_Go activity
public class Go extends AppCompatActivity implements OnNavigationReadyCallback,
NavigationListener {
private NavigationView navigationView;
private DirectionsRoute route;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
setTheme(R.style.Theme_AppCompat_NoActionBar);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_go);
navigationView = findViewById(R.id.navigationViewB);
navigationView.onCreate(savedInstanceState);
}
/*fabstart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
boolean simulateRoute = false;
NavigationLauncherOptions options = NavigationLauncherOptions.builder()
.directionsRoute(route)
.shouldSimulateRoute(simulateRoute)
.build();
// Call this method with Context from within an Activity
NavigationLauncher.startNavigation(MainActivity.this, options);
}
});*/
#Override
public void onNavigationReady(boolean isRunning) {
MapboxNavigationOptions.Builder navigationOptions = MapboxNavigationOptions.builder();
NavigationViewOptions.Builder options = NavigationViewOptions.builder();
options.navigationListener(this);
extractRoute(options);
extractConfiguration(options);
options.navigationOptions(navigationOptions.build());
//options.navigationOptions(new MapboxNavigationOptions.Builder().build());
launchNavigationWithRoute();
//navigationView.startNavigation(options.build());
navigationView.initialize(this);
/*MapboxNavigationOptions.Builder navigationOptions = MapboxNavigationOptions.builder();
NavigationViewOptions.Builder options = NavigationViewOptions.builder();
options.navigationListener(this);
extractRoute(options);
options.navigationOptions(navigationOptions.build());
//navigationView = NavigationLauncher.startNavigation(options.build());
navigationView.startNavigation(options.build());
initialize();*/
}
#Override
public void onCancelNavigation() {
// Navigation canceled, finish the activity
showCustomCancel();
finishNavigation();
}
#Override
public void onNavigationFinished() {
}
#Override
public void onNavigationRunning() {
}
private void launchNavigationWithRoute() {
if (route != null) {
NavigationLauncher.startNavigation(this, route);
}
}
private void extractRoute(NavigationViewOptions.Builder options) {
route = NavigationLauncher.extractRoute(this);
options.directionsRoute(route);
}
private void extractConfiguration(NavigationViewOptions.Builder options) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
options.shouldSimulateRoute(preferences.getBoolean(NavigationConstants.NAVIGATION_VIEW_SIMULATE_ROUTE, false));
}
private void finishNavigation() {
NavigationLauncher.cleanUpPreferences(this);
finish();
}
private void showCustomCancel(){
ViewGroup viewGroup = findViewById(android.R.id.content);
View dialogView2 = LayoutInflater.from(this).inflate(R.layout.my_dialog_logout, viewGroup, false);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(dialogView2);
AlertDialog alertDialog2 = builder.create();
Button buttonNo = dialogView2.findViewById(R.id.buttonNo);
Button buttonYes = dialogView2.findViewById(R.id.buttonYes);
buttonYes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (alertDialog2 != null && alertDialog2.isShowing()) {
alertDialog2.dismiss();
}
Intent intentCancelTrip_Yes = new Intent(getApplicationContext(),MainActivity.class);
startActivity(intentCancelTrip_Yes);
finish();
navigationView.stopNavigation();
}
});
buttonNo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (alertDialog2 != null && alertDialog2.isShowing()) {
alertDialog2.dismiss();
}
navigationView.onResume();
}
});
alertDialog2.show();
}
/* private void initialize() {
Parcelable position = getIntent().getParcelableExtra(NavigationConstants.NAVIGATION_VIEW_INITIAL_MAP_POSITION);
if (position != null) {
navigationView.initialize(this, (CameraPosition) position);
} else {
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();
}
}
NavigationLauncher class i am using to try initiate the navigation inside the Go activity
public class NavigationLauncher {
public static void startNavigation(Activity activity, DirectionsRoute route) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(activity);
SharedPreferences.Editor editor = preferences.edit();
editor.putString(NavigationConstants.NAVIGATION_VIEW_ROUTE_KEY, new Gson().toJson(route));
//editor.putString(NavigationConstants.NAVIGATION_VIEW_AWS_POOL_ID, awsPoolId);
//editor.putBoolean(NavigationConstants.NAVIGATION_VIEW_SIMULATE_ROUTE, simulateRoute);
editor.apply();
Intent navigationActivity = new Intent(activity, Go.class);
activity.startActivity(navigationActivity);
}
/* public static void startNavigation(Activity activity, NavigationLauncherOptions options){
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(activity);
SharedPreferences.Editor editor = preferences.edit();
storeDirectionsRouteValue(options, editor);
storeConfiguration(options, editor);
editor.apply();
Intent navigationActivity = new Intent(activity, Go.class);
storeInitialMapPosition(options, navigationActivity);
activity.startActivity(navigationActivity);
}*/
private static void storeConfiguration(NavigationLauncherOptions options, SharedPreferences.Editor editor) {
editor.putBoolean(NavigationConstants.NAVIGATION_VIEW_SIMULATE_ROUTE, options.shouldSimulateRoute());
}
private static void storeDirectionsRouteValue(NavigationLauncherOptions options, SharedPreferences.Editor editor) {
editor.putString(NavigationConstants.NAVIGATION_VIEW_ROUTE_KEY, options.directionsRoute().toJson());
/*if (options.directionsRoute() != null) {
storeDirectionsRouteValue(options, editor);
}
else {
throw new RuntimeException("A valid DirectionsRoute or origin and "
+ "destination must be provided in NavigationViewOptions");
}*/
}
static DirectionsRoute extractRoute(Context context) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
String directionsRouteJson = preferences.getString(NavigationConstants.NAVIGATION_VIEW_ROUTE_KEY, "");
return DirectionsRoute.fromJson(directionsRouteJson);
}
static void cleanUpPreferences(Context context) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = preferences.edit();
editor
.remove(NavigationConstants.NAVIGATION_VIEW_ROUTE_KEY)
.remove(NavigationConstants.NAVIGATION_VIEW_SIMULATE_ROUTE)
.apply();
}
private static void storeInitialMapPosition(NavigationLauncherOptions options, Intent navigationActivity) {
if (options.initialMapCameraPosition() != null) {
navigationActivity.putExtra(
NavigationConstants.NAVIGATION_VIEW_INITIAL_MAP_POSITION, options.initialMapCameraPosition()
);
}
}
}
I assume that the application crashes once the activity "Go.java" is launched.
The problem appears to be that you are not instantiating the Mapbox object in this activity. You are doing it correclty in your "mainactivity.java" however you are missing it in "go.java". Make sure to have the line Mapbox.getInstance(this, getString(R.string.access_token)); also in your "go.java" activity before calling setContentView()
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Mapbox.getInstance(this, getString(R.string.access_token));
setContentView(R.layout.activity_main);
I am having a Viewpager where i am loading data of different categories. I want to show a custom dialog popup whenever user stays on a particular category for 5 seconds or more asking the user if he/she wants to share the content. For that i have used a custom dialog and am hiding/showing based on the condition.
But the problem is, that if i want to open the dialog if the user stays on Viewpager item at position let's say 3, the dialog is opening for the Viewpager item at position 4.
I am not sure why it's referencing the wrong Viewpager item.
I am including the code of Adapter class for the reference.
ArticleAdapter.java
public class ArticleAdapter extends PagerAdapter {
public List<Articles> articlesListChild;
private LayoutInflater inflater;
Context context;
View rootView;
View customArticleShareDialog, customImageShareDialog;
public int counter = 0;
int contentType = 0;
int userId;
public ArticleAdapter(Context context, List<Articles> articlesListChild, int userId) {
super();
this.context = context;
this.userId = userId;
this.articlesListChild = articlesListChild;
}
#Override
public int getCount() {
return articlesListChild.size();
}
#Override
public void destroyItem(View collection, int position, Object view) {
((ViewPager) collection).removeView((View) view);
}
private Timer timer;
private TimerTask timerTask;
public void startTimer() {
timer = new Timer();
initializeTimerTask();
timer.schedule(timerTask, 5*1000, 5*1000);
}
private void initializeTimerTask() {
timerTask = new TimerTask() {
public void run() {
switch (contentType) {
case 1:
showShareDialog("articles");
break;
case 2:
showShareDialog("images");
break;
default :
// Do Nothing
}
}
};
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#SuppressLint("ClickableViewAccessibility")
#Override
public Object instantiateItem(ViewGroup container, final int position) {
inflater = LayoutInflater.from(container.getContext());
View viewLayout = inflater.inflate(R.layout.article_single_item, null, false);
final ImageView contentIv, imageContentIv;
final TextView sharingTextTv;
final LinearLayout articleShareBtn, articlesLayout, imagesLayout, customArticleShareDialog, customImageShareDialog;
contentIv = viewLayout.findViewById(R.id.content_iv);
articleShareBtn = viewLayout.findViewById(R.id.article_share_btn);
articlesLayout = viewLayout.findViewById(R.id.articles_layout);
imagesLayout = viewLayout.findViewById(R.id.images_layout);
imageContentIv = viewLayout.findViewById(R.id.image_content_iv);
sharingTextTv = viewLayout.findViewById(R.id.sharing_text_tv);
customArticleShareDialog = viewLayout.findViewById(R.id.articles_share_popup);
customImageShareDialog = viewLayout.findViewById(R.id.images_share_popup);
rootView = viewLayout.findViewById(R.id.post_main_cv);
viewLayout.setTag(rootView);
articleShareBtn.setTag(rootView);
// Images
if (articlesListChild.get(position).getArticleCatId() == 1) {
articlesLayout.setVisibility(GONE);
imagesLayout.setVisibility(View.VISIBLE);
RequestOptions requestOptions = new RequestOptions();
requestOptions.placeholder(R.drawable.placeholder);
Glide.with(context)
.setDefaultRequestOptions(requestOptions)
.load(articlesListChild.get(position).getArticleImage())
.into(imageContentIv);
imageContentIv.setScaleType(ImageView.ScaleType.FIT_XY);
sharingTextTv.setText("Found this image interesting? Share it with your friends.");
counter = 0;
startTimer();
// Articles
} else if (articlesListChild.get(position).getArticleCatId() == 2){
RequestOptions requestOptions = new RequestOptions();
requestOptions.placeholder(R.drawable.placeholder);
articlesLayout.setVisibility(View.VISIBLE);
Glide.with(context)
.setDefaultRequestOptions(requestOptions)
.load(articlesListChild.get(position).getArticleImage())
.into(contentIv);
contentIv.setScaleType(ImageView.ScaleType.FIT_XY);
sharingTextTv.setText("Found this article interesting? Share it with your friends.");
counter = 0;
startTimer();
}
container.addView(viewLayout, 0);
return viewLayout;
}
public void showShareDialog(String categoryType) {
if (categoryType.equalsIgnoreCase("articles")) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
public void run() {
customArticleShareDialog.setVisibility(View.VISIBLE);
}
});
} else if (categoryType.equalsIgnoreCase("images")) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
public void run() {
customImageShareDialog.setVisibility(View.VISIBLE);
}
});
}
}
}
ArticleActivity.java
public class ArticleActivity extends AppCompatActivity {
#BindView(R.id.toolbar)
Toolbar toolbar;
#BindView(R.id.drawer_layout)
DrawerLayout drawer;
#BindView(R.id.articles_view_pager)
ViewPager articlesViewPager;
#BindView(R.id.constraint_head_layout)
CoordinatorLayout constraintHeadLayout;
private ArticleAdapter articleAdapter;
private List<List<Articles>> articlesList = null;
private List<Articles> articlesListChild = new ArrayList<>();
private List<Articles> articlesListChildNew = new ArrayList<>();
SessionManager session;
Utils utils;
final static int MY_PERMISSIONS_WRITE_EXTERNAL_STORAGE = 1;
int userIdLoggedIn;
LsArticlesSharedPreference lsArticlesSharedPreference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
ButterKnife.bind(this);
toolbar.setTitle("");
toolbar.bringToFront();
session = new SessionManager(getApplicationContext());
if (session.isLoggedIn()) {
HashMap<String, String> user = session.getUserDetails();
String userId = user.get(SessionManager.KEY_ID);
userIdLoggedIn = Integer.valueOf(userId);
} else {
userIdLoggedIn = 1000;
}
utils = new Utils(getApplicationContext());
String storedTime = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getString("lastUsedDate", "");
System.out.println("lastUsedDate : " + storedTime);
if (utils.isNetworkAvailable()) {
insertData();
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
toggle.getDrawerArrowDrawable().setColor(getResources().getColor(R.color.colorWhite));
drawer.addDrawerListener(toggle);
if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
MY_PERMISSIONS_WRITE_EXTERNAL_STORAGE);
}
articleAdapter = new ArticleAdapter(getApplicationContext(), articlesListChild, userIdLoggedIn);
toggle.syncState();
clickListeners();
toolbar.setVisibility(View.GONE);
} else {
Intent noInternetIntent = new Intent(getApplicationContext(), NoInternetActivity.class);
startActivity(noInternetIntent);
}
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
finishAffinity();
super.onBackPressed();
}
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onStop() {
super.onStop();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.home, menu);
return true;
}
#Override
public boolean onSupportNavigateUp() {
finish();
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_refresh:
articleAdapter.notifyDataSetChanged();
insertData();
Toast.makeText(this, "Refreshed", Toast.LENGTH_SHORT).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#SuppressLint("ClickableViewAccessibility")
public void clickListeners() {
}
private void insertData() {
Intent intent = new Intent(getBaseContext(), OverlayService.class);
startService(intent);
final SweetAlertDialog pDialog = new SweetAlertDialog(ArticleActivity.this, SweetAlertDialog.PROGRESS_TYPE);
pDialog.getProgressHelper().setBarColor(getResources().getColor(R.color.colorPrimary));
pDialog.setTitleText("Loading");
pDialog.setCancelable(false);
pDialog.show();
Api.getClient().getHomeScreenContents(userIdLoggedIn, new Callback<ArticlesResponse>() {
#Override
public void success(ArticlesResponse articlesResponse, Response response) {
articlesList = articlesResponse.getHomeScreenData();
if (!articlesList.isEmpty()) {
for (int i = 0; i < articlesList.size(); i++) {
articlesListChildNew = articlesList.get(i);
articlesListChild.addAll(articlesListChildNew);
}
articleAdapter = new ArticleAdapter(getApplicationContext(), articlesList, articlesListChild, userIdLoggedIn, toolbar);
articlesViewPager.setAdapter(articleAdapter);
articleAdapter.notifyDataSetChanged();
pDialog.dismiss();
} else {
List<Articles> savedArticles = lsArticlesSharedPreference.getFavorites(getApplicationContext());
if (!savedArticles.isEmpty()) {
articleAdapter = new ArticleAdapter(getApplicationContext(), articlesList, savedArticles, userIdLoggedIn, toolbar);
articlesViewPager.setAdapter(articleAdapter);
articleAdapter.notifyDataSetChanged();
pDialog.dismiss();
} else {
Api.getClient().getAllArticles(new Callback<AllArticlesResponse>() {
#Override
public void success(AllArticlesResponse allArticlesResponse, Response response) {
articlesListChild = allArticlesResponse.getArticles();
articleAdapter = new ArticleAdapter(getApplicationContext(), articlesList, articlesListChild, userIdLoggedIn, toolbar);
articlesViewPager.setAdapter(articleAdapter);
articleAdapter.notifyDataSetChanged();
};
#Override
public void failure(RetrofitError error) {
Log.e("articlesData", error.toString());
}
});
pDialog.dismiss();
}
}
}
#Override
public void failure(RetrofitError error) {
pDialog.dismiss();
Toast.makeText(ArticleActivity.this, "There was some error fetching the data.", Toast.LENGTH_SHORT).show();
}
});
}
}
Issue reason:
You face this issue because the viewpager preload fragments in background. It means that when you see 3rd fragment, the viewpager is instantiating 4th. Due to this workflow your timer for 3rd screen is cancelled and timer for 4th screen is started. Check out this link to understand what is going on.
Solution:
I would do next:
Then set page change listener for your adapter. How to do it
In this listener you can get current page and start timer for this page (and cancel timer for previously visible page).
You don't need to call startTimer() method when you instantiate item in instantiateItem() method.
This is my view binder code. Here the acceptbutton and reject button is not working.
#Layout(R.layout.item)
public class TinderCard implements AsyncTaskCompleteListener {
SessionManager msession;
private static final String LIKE = "1";
private static final String DISLIKE = "2";
private int size,match;
String suggestionid;
private FindMatchesExecute execute;
#View(R.id.profileImageView)
private ImageView profileImageView;
#View(R.id.nameAgeTxt)
private TextView nameAgeTxt;
#View(R.id.acceptBtn)
private ImageView acceptbutton;
#View(R.id.rejectBtn)
private ImageView dislike_button;
private Data mProfile;
private Context mContext;
public int count=0;
#View(R.id.swipeView)
private SwipePlaceHolderView mSwipeView;
Activity activity;
public TinderCard(Context context, Data profile, SwipePlaceHolderView swipeView,FindMatchesExecute execu) {
mContext = context;
mProfile = profile;
mSwipeView = swipeView;
this.execute=execu;
msession=new SessionManager(mContext);
}
#Resolve
private void onResolved(){
Glide.with(mContext).load(mProfile.getPicture()).into(profileImageView);
nameAgeTxt.setText(mProfile.getName() + ", " + mProfile.getAge());
suggestionid=mProfile.getUserid();
profileImageView.setOnClickListener(new android.view.View.OnClickListener() {
#Override
public void onClick(android.view.View v) {
Intent i=new Intent(mContext,UserProfile.class);
i.putExtra("suggestion_id",mProfile.getUserid());
mContext.startActivity(i);
}
});
The listener part of the accept and reject button is not working. What am I missing in my code.
acceptbutton.setOnClickListener(new android.view.View.OnClickListener() {
#Override
public void onClick(android.view.View v) {
mSwipeView.doSwipe(true);
}
});
dislike_button.setOnClickListener(new android.view.View.OnClickListener() {
#Override
public void onClick(android.view.View v) {
mSwipeView.doSwipe(false);
}
});
}
#SwipeOut
private void onSwipedOut(){
Log.d("shan", "onSwipedOut");
HashMap<String, String> map = new HashMap<>();
map.put(Const.URL, Constant.like_dislike);
map.put(Const.Params.TOKEN, msession.getToken());
map.put(Const.Params.ID, msession.getID());
map.put(Const.Params.LIKE_DISLIKE_STATUS, DISLIKE);
map.put(Const.Params.SUGGESTION_ID, suggestionid);
Log.d("shanUpdatePref", "login map" + map);
// new MultiPartRequester(this, map, Const.ServiceCode.UPDATE_DOB, this);
new HttpRequester(mContext, Const.POST, map, Const.ServiceCode.LIKE_DISLIKE, this);
execute.onExecute();
}
#SwipeCancelState
protected void onSwipeCancelState(){
Log.d("EVENT", "onSwipeCancelState");
}
#SwipeIn
private void onSwipeIn()
{
//FindMatchesFragment.size--;
HashMap<String, String> map = new HashMap<>();
map.put(Const.URL, Constant.like_dislike);
map.put(Const.Params.TOKEN, msession.getToken());
map.put(Const.Params.ID, msession.getID());
map.put(Const.Params.LIKE_DISLIKE_STATUS, LIKE);
map.put(Const.Params.SUGGESTION_ID, suggestionid);
Log.d("shanUpdatePref", "login map" + map);
new HttpRequester(mContext, Const.POST, map, Const.ServiceCode.LIKE_DISLIKE, this);
execute.onExecute();
}
#SwipeInState
private void onSwipeInState(){
Log.d("EVENT", "onSwipeInState");
}
#SwipeOutState
private void onSwipeOutState(){
Log.d("EVENT", "onSwipeOutState");
}
#Override
public void onTaskCompleted(String response, int serviceCode) {
JSONObject jsonObject;
switch (serviceCode) {
case Const.ServiceCode.LIKE_DISLIKE:
Log.d("shan", "task1");
Log.d("shanResponse",response);
try {
jsonObject = new JSONObject(response);
if (jsonObject.getString("success").equals("true")) {
JSONObject like= jsonObject.getJSONObject("like");
Log.d("shanStatus",like.optString("status"));
match=like.optInt("match");
if(match==1)
{
String picture=like.optString("picture");
String user_pictre=like.optString("user_image");
String name=like.optString("name");
String userid=like.optString("suggestion_id");
Fragment MatchFoundScreen = new MatchFoundScreen();
Bundle args = new Bundle();
args.putString("name", name);
args.putString("picture",picture);
args.putString("user_image", user_pictre);
args.putString("suggestion_id", userid);
args.putInt("match",match);
MatchFoundScreen.setArguments(args);
FragmentManager fragmentManager =((FragmentActivity) mContext).getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.frame, MatchFoundScreen).commit();
}
} else {
Utility.showShortToast(mContext, jsonObject.getString("error_message"));
}
} catch (JSONException e) {
e.printStackTrace();
}
break;
}
}
}
Someone please guide me to resolve this. Thanks in advance.
This is my fragment class.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
msession = new SessionManager(getActivity());
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.i("Find Match", "oncreateview called");
view = inflater.inflate(R.layout.find_matches, null);
rlayout=(LinearLayout) view.findViewById(R.id.likedislikebuttonlayout);
frame=(FrameLayout)view.findViewById(R.id.frame2);
LocationManager locationManagerresume = (LocationManager) getActivity().getSystemService(LOCATION_SERVICE);
if (!locationManagerresume
.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
showGPSDisabledAlertToUser();
}
cd = new ConnectionDetector(getActivity());
if (!cd.isConnectingToInternet()) {
Toast.makeText(getActivity(), "No Internet", Toast.LENGTH_SHORT)
.show();
}
mSwipeView = (SwipePlaceHolderView)view.findViewById(R.id.swipeView);
rippleBackground = (RippleBackground) view.findViewById(R.id.content);
rippleBackground.startRippleAnimation();
noUsers=(TextView)view.findViewById(R.id.noUsers);
profileimage = (CircleImageView) view.findViewById(R.id.profileimage);
Glide.with(getActivity()).load(msession.getProfileImage())
.into(profileimage);
mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(10 * 1000)
.setFastestInterval(1 * 1000);
al = new ArrayList<>();
mContext = getActivity();
mSwipeView.getBuilder()
.setDisplayViewCount(1)
.setSwipeDecor(new SwipeDecor()
.setPaddingTop(20)
.setRelativeScale(0.01f)
.setSwipeInMsgLayoutId(R.layout.tinder_swipe_in_msg_view)
.setSwipeOutMsgLayoutId(R.layout.tinder_swipe_out_msg_view));
return view;
}
Use ButterKnife.bind(getActivity()) when ever you are in activity use this and for fragments use getActivity().
It's a way of using context in different places for more details
#OnClick(R.id.iv_image)
void ivBack() {
//TODO For Back Action
finish();
}
use latest
compile 'com.jakewharton:butterknife:8.1.0'
apt 'com.jakewharton:butterknife-compiler:8.1.0'
more details about lib
First of all, I am relatively new to android programming.
I am creating a ViewPager application with two Fragments. One of the Fragments requests data from a server and return a result to the main FragmentActivity. My problem is that this request to the server can take sometime, and I have been trying to get a ProgressDialog to appear with AsyncTask while the user waits for the data to be retrieved. Once I create the background thread to retrieve the data, I successfully execute some code in the onPostExecute() method and set some variables. However, the return statement that sends information back to the FragmentActivity is being executed before the background thread actually ends. I can't seem to figure out a way for the main thread to wait on the background thread. Using Asyctask's get() method results in the ProgressDialog from appearing. I have looked through a lot of posts in here, but can't seem to find an answer.
Anything helps.
Code below:
SplashScreen.java
public class SplashScreen extends FragmentActivity {
MainMenu mainMenu;
MapScreen mapScreen;
PagerAdapter pagerAdapter;
ViewPager viewPager;
List<LatLng> geoPoints;
private Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_splash_screen);
context = this;
initializePaging();
}
private void initializePaging()
{
mainMenu = new MainMenu();
mapScreen = new MapScreen();
pagerAdapter = new PagerAdapter(getSupportFragmentManager());
pagerAdapter.addFragment(mainMenu);
pagerAdapter.addFragment(mapScreen);
viewPager = (ViewPager) super.findViewById(R.id.viewPager);
viewPager.setAdapter(pagerAdapter);
viewPager.setOffscreenPageLimit(2);
viewPager.setCurrentItem(0);
viewPager.setOnPageChangeListener(new OnPageChangeListener()
{
#Override
public void onPageScrollStateChanged(int postion){}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2){}
#Override
public void onPageSelected(int position)
{
switch(position){
case 0: findViewById(R.id.first_tab).setVisibility(View.VISIBLE);
findViewById(R.id.second_tab).setVisibility(View.INVISIBLE);
break;
case 1: findViewById(R.id.first_tab).setVisibility(View.INVISIBLE);
findViewById(R.id.second_tab).setVisibility(View.VISIBLE);
break;
}
}
});
}
//Called from onClick in main_mainu.xml
public void getDirections(View view)
{
InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
try
{
geoPoints = mainMenu.getDirections(context);
mapScreen.plotPoints(geoPoints);
}
catch(Exception e)
{
Toast.makeText(getApplicationContext(), "Error! Invalid address entered.", Toast.LENGTH_LONG).show();
mainMenu.clear();
}
}
}
MainMenu.java
public class MainMenu extends Fragment {
String testString;
int testInt;
TextView testTV;
private TextView tvDisplay;
private EditText departure;
private EditText destination;
private Geocoder geocoder;
private List<Address> departAddress;
private List<Address> destinationAddress;
private List<LatLng> geoPoints;
private String departString;
private String destinationString;
private Address departLocation;
private Address destinationLocation;
private LatLng departurePoint;
private LatLng destinationPoint;
private Context contextMain;
private GetData task;
public MainMenu()
{
super();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View root = (View) inflater.inflate(R.layout.main_menu, null);
geoPoints = new ArrayList<LatLng>(2);
return root;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState)
{
departure = (EditText) getView().findViewById(R.id.depart_field);
destination = (EditText) getView().findViewById(R.id.destination_field);
tvDisplay = (TextView) getView().findViewById(R.id.textView1);
}
public List<LatLng> getDirections(Context context)
{
contextMain = context;
geocoder = new Geocoder(getActivity());
departString = departure.getText().toString();
destinationString = destination.getText().toString();
try
{
task = new GetData(new Callback(){
public void run(Object result)
{
//return geoPoints;
}
});
task.execute((Void[])null);
}catch(Exception e)
{
e.printStackTrace();
}
return geoPoints;
}
public void clear()
{
departure.setText("");
destination.setText("");
tvDisplay.setText("Enter departure point, and destination point");
}
private class GetData extends AsyncTask<Void, Void, List<List<Address>>>
{
Callback callback;
private ProgressDialog processing;
public GetData(Callback callback)
{
this.callback = callback;
}
#Override
protected void onPreExecute()
{
processing = new ProgressDialog(contextMain);
processing.setTitle("Processing...");
processing.setMessage("Please wait.");
processing.setCancelable(false);
processing.setIndeterminate(true);
processing.show();
}
#Override
protected List<List<Address>> doInBackground(Void...arg0)
{
List<List<Address>> list = new ArrayList<List<Address>>(2);
try
{
departAddress = geocoder.getFromLocationName(departString, 5, 37.357059, -123.035889, 38.414862, -121.723022);
destinationAddress = geocoder.getFromLocationName(destinationString, 5, 37.357059, -123.035889, 38.414862, -121.723022);
list.add(departAddress);
list.add(destinationAddress);
}catch(IOException e)
{
e.printStackTrace();
}
return list;
}
#Override
protected void onPostExecute(List<List<Address>> list)
{
departLocation = list.get(0).get(0);
destinationLocation = list.get(1).get(0);
departurePoint = new LatLng(departLocation.getLatitude(), departLocation.getLongitude());
destinationPoint = new LatLng(destinationLocation.getLatitude(), destinationLocation.getLongitude());
if(geoPoints.size() >= 2)
{
geoPoints.clear();
}
geoPoints.add(departurePoint);
geoPoints.add(destinationPoint);
callback.run(list);
processing.dismiss();
}
}
}
#Override
protected Object doInBackground(Void...arg0)
{
Object result = null;
try
{
departAddress = geocoder.getFromLocationName(departString, 5, 37.357059, -123.035889, 38.414862, -121.723022);
destinationAddress = geocoder.getFromLocationName(destinationString, 5, 37.357059, -123.035889, 38.414862, -121.723022);
}catch(IOException e)
{
e.printStackTrace();
}
return result;
}
You never set the value of result...
I'm implementing an asyncTask class to load the data from server.
I have the data already and I want to pass it to the UI Thread, but I don't know how.
This is the code:
public class InboxHandler extends FragmentActivity implements OnLineSelectedListener {
static final int GET_CODE = 0;
private TextView textView3, textView2;
private Button button1, button2, button3;
private LinearLayout tab1, tab2, tab3;
private CheckBox cbVerPorCategoria;
private ActionBar actionBar;
private TextView txtTitle;
private Settings settings;
FragmentTransaction fragmentTransaction;
BottomPanel bottomPanel;
public List<OrderRequest> orderRequestArray;
private OrderRequestParser orderRequestParser;
public static int number;
int clickCounter = 0;
private boolean doubleBackToExitPressedOnce = false;
private static Context context;
DataLoader dataLoader;
private MyAsynckTask myAsynckTask;
public InboxHandler(){}
public List<OrderRequest> getOrderRequestArray() {
return orderRequestArray;
}
public void setOrderRequestArray(List<OrderRequest> orderRequestArray) {
this.orderRequestArray = orderRequestArray;
}
public static Context getContext()
{
return context;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_inbox);
context = this.getApplicationContext();
settings = Settings.getInstance();
settings.setPrefs(getSharedPreferences(settings.getPREFERENCES(), Activity.MODE_PRIVATE));
settings.setPrefsEditor(settings.getPrefs().edit());
settings.getPrefsEditor().putBoolean("isLoggedIn", true);
settings.isVistaSimple = true;
actionBar = (ActionBar) findViewById(R.id.actionbar);
initComponents();
prepareActionBar();
}
private void initComponents() {
try {
MyAsynckTask myAsynckTask = new MyAsynckTask(this);
myAsynckTask.execute();
//HERE I USED A SUGGESTION IN A SIMILAR QUESTION. THAT IS: PASS THE ACTIVITY TO THE ASYNCTASK, AND FROM IT, SAVE IN THE ACTIVITY, THE DATA THAT IU WANT FROM THE ASYNCTASK. I DO THAT, BUT IN THE ACTIVITY, THE DATA IS NULL I SUPPOSE DUE TO, I DONT EVEN SEE IN THE LOGCAT, THE FOLLOWING RESULT:
try{
Log.e("e", ""+this.getOrderRequestArray().get(0).getDocNumber());
} catch(Exception e){
e.printStackTrace();
}
//If you see the onPostExecute, I test if the data I want is there. and it is there! I set that to the list of the class InboxHandler, but in the above code, when i try to test if it is there, it´s not. And that code don´t even appear in logcat. The "Log.e("e", ""+this.getOrderRequestArray().get(0).getDocNumber());" nor the "e.printStackTrace();"
bottomPanel =new BottomPanel();
Bundle bundle = new Bundle();
bundle.putSerializable("arrayPedidos", (Serializable) orderRequestArray);
bottomPanel.setArguments(bundle);
//actionBar.setTitle("Inbox");
NotificationFragment notificationFragment = new NotificationFragment(orderRequestArray, actionBar);
Bundle bundleNotificationFragment = new Bundle();
bundleNotificationFragment.putString("title", "Inbox");
notificationFragment.setArguments(bundleNotificationFragment);
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.frame_list_container, notificationFragment);
fragmentTransaction.add(R.id.frame_bottom_panel, bottomPanel);
fragmentTransaction.commit();
}
catch(Exception e)
{
e.printStackTrace();
}
}
private class MyAsynckTask extends AsyncTask {
private String stringMensaje;
public List<OrderRequest> orderRequestArray;
private OrderRequestParser orderRequestParser;
private Request request;
private Settings settings;
private InboxHandler inboxHandler;
public MyAsynckTask(InboxHandler inboxHandler){
this.inboxHandler = inboxHandler;
}
#Override
protected Object doInBackground(Object... params) {
List<OrderRequest> array = this.getOrderRequests();
settings = Settings.getInstance();
if(array != null){
settings.setOrderRequestArray(array);
orderRequestArray = array;
Log.e("orderRequestArray", "Me trajo el orderRequestArray en doInBackground!");
} else {
Log.e("orderRequestArray", "No me trajo el orderRequestArray en doInBackground!");
}
return array;
}
#Override
protected void onPostExecute(Object result) {
super.onPostExecute(result);
List<OrderRequest> array = (List<OrderRequest>) result;
this.setOrderRequestArray(array);
if(orderRequestArray != null){
inboxHandler.setOrderRequestArray(orderRequestArray);
Log.e("orderRequestArray", "is not null en onPostExecute!");
} else {
Log.e("orderRequestArray", "is null en onPostExecute!");
}
if(inboxHandler.getOrderRequestArray() != null){
Log.e("inboxHandler.getOrderRequestArray()", "is not null en onPostExecute!");
}
else {
Log.e("orderRequestArray", "is null en onPostExecute!");
}
}
public List<OrderRequest> getOrderRequests() {
orderRequestParser = new OrderRequestParser();
orderRequestArray = new ArrayList<OrderRequest>();
List<OrderRequest> orderRequestArray = orderRequestParser.listOrderRequest();
Settings.getInstance().setOrderRequestArray(orderRequestArray);
if(orderRequestArray != null){
Log.e("orderRequestArray", "Me trajo el orderRequestArray en getOrderRequestArray!");
} else {
Log.e("orderRequestArray", "No me trajo el orderRequestArray en getOrderRequestArray!");
}
return orderRequestArray;
}
public void setOrderRequestArray(List<OrderRequest> orderRequestArray) {
this.orderRequestArray = orderRequestArray;
}
public List<OrderRequest> getOrderRequestArray() {
return orderRequestArray;
}
}
protected void onPostExecute(Object result)
it is running in GUI thread, you can access GUI elements there.
and only there should be the:
try{
Log.e("e", ""+this.getOrderRequestArray().get(0).getDocNumber());
} catch(Exception e){
e.printStackTrace();
}
and
Bundle bundle = new Bundle();
bundle.putSerializable("arrayPedidos", (Serializable) orderRequestArray);
bottomPanel.setArguments(bundle);
I can't see any reason, why is this question down voted.