I can not create buttons for possible answers android studio - android
I have an issue with a small project in android studio where on animal drawings guess things etc. But guess I have to write the name to accept a button and image lights up and goes to the next , what I want you to show me an answer with buttons say 3 button 1 is the correct answer and the other two false I took a long time with this and even I can not do it if I would appreciate any help
Here the code of the class where the shadows and images run
public class Categoria extends Activity {
public static String[] nombre_cosa={"cerdo","ave","caballo","conejo","elefante","gallina","gato",
"rana","perro","pato","oveja","leon","jirafa",
"raton","vaca","autobus","automovil","avion","bicicleta","camioneta",
"casa","celular","guitarra","motocicleta","silla","television","durazno","fresa","mango",
"uvas","sandia","platano","coco","pera","naranja","manzana",
"bart","batman","cerebro","chavo","goku","homero","marge",
"patricio","pepa","phineas","quico","spiderman","thor","superman"};
public static String[] sombra_cosa={"s_cerdo","s_ave","s_caballo","s_conejo","s_elefante","s_gallina","s_gato",
"s_rana","s_perro","s_pato","s_oveja","s_leon","s_jirafa",
"s_raton","s_vaca","s_autobus","s_automovil","s_avion","s_bicicleta","s_camioneta",
"s_casa","s_celular","s_guitarra","s_motocicleta","s_silla","s_television","s_durazno","s_fresa","s_mango",
"s_uvas","s_sandia","s_platano","s_coco","s_pera","s_naranja","s_manzana",
"s_bart","s_batman","s_cerebro","s_chavo","s_goku","s_homero","s_marge",
"s_patricio","s_pepa","s_phineas","s_quico","s_spiderman","s_thor","s_superman"};
public static boolean[] estado={false,false,false,false,false,false,
false,false,false,false,false,false,
false,false,false,false,false,false,false,
false,false,false,false,false,false,false,false,
false,false,false,false,false,false,false,
false,false,false,false,false,false,false,false,false,false,
false,false,false,false,false,false};
public static int cosas_adivinadas=0;
private int intentos=3;
private Button aceptar;
private TextView mensaje_intentos,mensaje_cuenta;
private EditText usuario_cosa;
private int numero_generado=0;
private ImageView miimagen;
private MediaPlayer reproductor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.activity_categoria);
aceptar=(Button) findViewById(R.id.btnaceptar);
mensaje_intentos=(TextView) findViewById(R.id.lblintentos);
mensaje_cuenta=(TextView) findViewById(R.id.lblcuenta);
usuario_cosa=(EditText) findViewById(R.id.txtcosa);
miimagen=(ImageView) findViewById(R.id.imgcosa);
CargarPreferencias();
new MiTarea().execute();
reproductor= MediaPlayer.create(this,R.raw.yansha);
reproductor.setLooping(true);
reproductor.start();
mensaje_intentos.setText("Tiene " + intentos + " intentos");
aceptar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String nombre=usuario_cosa.getText().toString().toLowerCase();
if(nombre.equals(nombre_cosa[numero_generado]))
{
establecer_cosa(numero_generado);
estado[numero_generado]=true;
cosas_adivinadas++;
esperar();
}
else
{
Toast.makeText(getApplicationContext(), "Incorrecto", Toast.LENGTH_SHORT).show();
intentos=intentos-1;
mensaje_intentos.setText("Tiene " + intentos + " intentos");
}
if (intentos==0)
{
removerPreferencias();
Intent i = new Intent(Categoria.this,Perder.class);
startActivity(i);
finish();
}
}
});
}
#Override
protected void onResume() {
super.onResume();
reproductor.start();
}
public void esperar()
{
new CountDownTimer(5000,1000)
{
#Override
public void onTick(long millisUntilFinished) {
mensaje_cuenta.setText("Generando en " + (millisUntilFinished/1000));
}
#Override
public void onFinish() {
if (cosas_adivinadas==nombre_cosa.length)
{
finish();
}
else
{
new MiTarea().execute();
mensaje_cuenta.setText("");
usuario_cosa.setText("");
}
}
}.start();
}
public void CargarPreferencias()
{
SharedPreferences mispreferencias = getSharedPreferences("PreferenciaCosa", Context.MODE_PRIVATE);
intentos=mispreferencias.getInt("intentos",3);
cosas_adivinadas=mispreferencias.getInt("adivinados",0);
for (int i=0;i<nombre_cosa.length;i++)
{
estado[i]=mispreferencias.getBoolean(nombre_cosa[i],false);
}
}
public void GuardarPreferencias()
{
SharedPreferences mispreferencias = getSharedPreferences("PreferenciaCosa", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = mispreferencias.edit();
editor.putInt("intentos",intentos);
editor.putInt("adivinados",cosas_adivinadas);
for (int i=0;i<nombre_cosa.length;i++)
{
editor.putBoolean(nombre_cosa[i], estado[i]);
}
editor.commit();
}
private void establecer_cosa(int numero)
{
int resId = getResources().getIdentifier(nombre_cosa[numero], "drawable", getPackageName());
miimagen.setImageResource(resId);
}
private void establecer_sombra(int numero)
{
int resId = getResources().getIdentifier(sombra_cosa[numero], "drawable", getPackageName());
miimagen.setImageResource(resId);
}
private void removerPreferencias()
{
SharedPreferences settings = getSharedPreferences("PreferenciaCosa", Context.MODE_PRIVATE);
settings.edit().clear().commit();
}
#Override
protected void onStop() {
if (intentos==0)
{
removerPreferencias();
}
else
{
GuardarPreferencias();
}
reproductor.pause();
super.onStop();
}
#Override
protected void onDestroy() {
if (reproductor.isPlaying())
{
reproductor.stop();
reproductor.release();
}
super.onDestroy();
}
private class MiTarea extends AsyncTask<Void, Void, Void> {
private int valor_generado;
#Override
protected Void doInBackground(Void... params) {
do {
valor_generado=((int)(Math.random()*nombre_cosa.length));
}while(estado[valor_generado]);
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
numero_generado = valor_generado;
establecer_sombra(valor_generado);
super.onPostExecute(aVoid);
}
}
}
Create a variable like this:
boolean isTextCorrect = false;
In default, the button is invisible.
Implement a listener. If the text in the textfield changed and its correct switch isTextCorrect to true and make the button visible (clickable).
if(isTextCorrect){
button.setVisible(View.VISIBLE);
}
Related
How do i start the turn by turn NavigationLauncher from another activity
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);
Restoring RecyclerView scroll position
I have this code. It displays two recycler views and wants to store their scroll positions for the rotation purpose. So here is my code. public class DetailActivity extends AppCompatActivity implements DetailViewInteface, TrailersAdapter.TrailersAdapterOnClickHandler { public static final String IMAGE_URL = "http://image.tmdb.org/t/p/"; public static final String IMAGE_SIZE_185 = "w185"; private static final String TAG = "DetailActivity"; private static final String TRAILERS_LAYOUT = "DetailsActivity.trailer.layout"; private static final String REVIEWS_LAYOUT = "DetailsActivity.review.layout"; private Parcelable listState1; private Parcelable listState2; #BindView(R.id.movie_image) ImageView movieImageTv; String mImage; #BindView(R.id.movie_title) TextView movieTitleTv; String mTitle; #BindView(R.id.movie_rating) TextView movieRatingTv; double mRating; #BindView(R.id.movie_date) TextView movieDateTv; String mReleaseDate; #BindView(R.id.movie_overview) TextView movieOverviewTv; String mMovieOverview; #BindView(R.id.recyclerview_trailers) RecyclerView trailersRecyclerView; TrailersAdapter trailersAdapter; #BindView(R.id.recyclerview_reviews) RecyclerView reviewsRecyclerView; ReviewAdapter reviewAdapter; int recyclerViewOrientation = LinearLayoutManager.VERTICAL; private Parcelable mLayoutManagerSavedState; DetailPresenter detailPresenter; #Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_detail); ButterKnife.bind(this); setMVP(); setUpViews(); detailPresenter.getMovieDetails(); detailPresenter.getMovieTrailers(); detailPresenter.getMovieReviews(); } public void setMVP(){ detailPresenter = new DetailPresenter(this,this); } public void setUpViews(){ trailersRecyclerView.setLayoutManager(new LinearLayoutManager(this)); trailersRecyclerView.addItemDecoration(new MyDividerItemDecoration(this,recyclerViewOrientation,16)); reviewsRecyclerView.setLayoutManager(new LinearLayoutManager(this)); reviewsRecyclerView.addItemDecoration(new MyDividerItemDecoration(this,recyclerViewOrientation,16)); } #Override public void dipsplayMovieDetails(Movie movie) { //movieTitleTv.setText(movieTitle); //movieDescriptionTv.setText(movieDesc); mImage = movie.getPosterPath(); Picasso.with(this).load(IMAGE_URL + IMAGE_SIZE_185 + mImage).into(movieImageTv); mTitle = movie.getTitle(); movieTitleTv.setText(mTitle); mRating = movie.getVoteAverage(); movieRatingTv.setText("Rating: " + mRating); mReleaseDate = movie.getReleaseDate(); movieDateTv.setText("Date: " + mReleaseDate); mMovieOverview = movie.getOverview(); movieOverviewTv.setText(mMovieOverview); } #Override public void dipsplayMovieTrailers(TrailersResponse trailersResponse) { Log.d(TAG, "Trailers size: " + String.valueOf(trailersResponse.getTrailers().size())); trailersAdapter = new TrailersAdapter(trailersResponse.getTrailers(),DetailActivity.this,this); trailersRecyclerView.setAdapter(trailersAdapter); } #Override public void displayMovieReviews(ReviewsResponse reviewsResponse) { if(reviewsResponse != null) { Log.d(TAG, String.valueOf("Reviews size: " + reviewsResponse.getReviews().size())); reviewAdapter = new ReviewAdapter(reviewsResponse.getReviews()); reviewsRecyclerView.setAdapter(reviewAdapter); }else{ Toast.makeText(DetailActivity.this,"No reviews found!",Toast.LENGTH_LONG).show(); } } #Override public void displayError(String s) { showToast(s); } #Override public void showToast(String s) { Toast.makeText(DetailActivity.this,s,Toast.LENGTH_LONG).show(); } #Override public void onClick(String trailerKey) { Intent appIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("vnd.youtube:" + trailerKey)); Intent webIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.youtube.com/watch?v=" + trailerKey)); try { startActivity(appIntent); } catch (ActivityNotFoundException ex) { startActivity(webIntent); } } #Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putParcelable(REVIEWS_LAYOUT,reviewsRecyclerView.getLayoutManager().onSaveInstanceState()); outState.putParcelable(TRAILERS_LAYOUT,trailersRecyclerView.getLayoutManager().onSaveInstanceState()); } } I use the onSaveInstanceState method. But now I need to restore in the scroll positions of recyclerviews. I am using the onRestoreInstanceState as below but nothing happens. The rotation gets me to the top of the screen. #Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); savedInstanceState.getParcelable(REVIEWS_LAYOUT); savedInstanceState.getParcelable(TRAILERS_LAYOUT); } So how can I fix that bug? Thanks, Theo.
void addOnScrollListener (RecyclerView.OnScrollListener listener) This is a listener that will be notified of any changes in scroll state or position for a recycler view. Refer to this answer for an example implementation. For more on how to use it correctly.
Using options in ActionSheet to change Button text
I am trying to develop an UI actionsheet in android. Using dependency: compile 'com.baoyz.actionsheet:library:1.1.6' I have developed an actionsheet in android which look like this: ActionSheet in Android I am trying to change the button text whenever any option is selected from the actionSheet. The index in the javafile below contains the string position just like array but i am unable to get the string value from that index. Here is my javafile: public class billBookInfo extends AppCompatActivity implements ActionSheet.ActionSheetListener{ private Button change; private String setValue; private Button vtype; private Button zone; Button next; Button previous; #Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_bill_book_info); getSupportActionBar().hide(); vtype = (Button) findViewById(R.id.info_billbook_bt_vtype); zone = (Button)findViewById(R.id.info_billbook_bt_zone); } } public void onClick(View v){ switch (v.getId()) { case R.id.info_billbook_bt_vtype: setTheme(R.style.ActionSheetStyleiOS7); change = vtype; showActionSheet1(); break; case R.id.info_billbook_bt_zone: setTheme(R.style.ActionSheetStyleiOS7); showActionSheet2(); change = zone; break; } } private void showActionSheet1() { ActionSheet.createBuilder(this,getSupportFragmentManager()) .setCancelButtonTitle("Cancel") .setOtherButtonTitles("Motorcycle","Scooter","Car","Van") .setCancelableOnTouchOutside(true).setListener(this).show(); } private void showActionSheet2() { ActionSheet.createBuilder(this,getSupportFragmentManager()) .setCancelButtonTitle("Cancel") .setOtherButtonTitles("Me", "Ko", "Sa", "Ja") .setCancelableOnTouchOutside(true).setListener(this).show(); } #Override public void onDismiss(ActionSheet actionSheet, boolean isCancel) { } #Override public void onOtherButtonClick(ActionSheet actionSheet, int index) { int i = 0; if ( i == index){ setValue = "".concat(getString(index)); change.setText(setValue); } } }
Why don't you use a variable to store those values. String vArr[] = new String[]{"Motorcycle","Scooter","Car","Van"}; String dArr[] = new String[]{"Me", "Ko", "Sa", "Ja"}; ActionSheet vSheet, dSheet; private void showActionSheet1() { vSheet = ActionSheet.createBuilder(this,getSupportFragmentManager()) .setCancelButtonTitle("Cancel") .setOtherButtonTitles(vArr[0],vArr[1],vArr[2],vArr[3]) .setCancelableOnTouchOutside(true).setListener(this).show(); } private void showActionSheet2() { dSheet = ActionSheet.createBuilder(this,getSupportFragmentManager()) .setCancelButtonTitle("Cancel") .setOtherButtonTitles(dArr[0],dArr[1],dArr[2],dArr[3]) .setCancelableOnTouchOutside(true).setListener(this).show(); } #Override public void onDismiss(ActionSheet actionSheet, boolean isCancel) { } #Override public void onOtherButtonClick(ActionSheet actionSheet, int index) { if ( actionSheet == vSheet){ change.setText(vArr[index]); } else{ change.setText(dArr[index]); } }
How to update a textview in a dialog fragment from an activity?
It may be a silly question but I didn't find a good way to update a dialogfragment's textview from an activity in my android app. What I'd like to do is to update the textview every second with a counter value and once the time elapsed, a Runnable closes the dialog fragment. The dialog is closed once the time is elapsed, no problem but I cannot update the textview I want. Here's my code for the dialog: public class AlertDialog extends DialogFragment { private String message = null; private String title = null; private ImageView imgV = null; private TextView msgTv = null; private TextView counterTv = null; private Button okBtn = null; private int imageId = 0; public static int AUTOMATIC_CLOSE = 100001; private AlertDialogListener mDialogListener; public void setImage(int i){ imageId = i; } public void setContent(String ttl, String msg){ message = msg; title = ttl; } public boolean hasContent(){ return message != null && title != null; } public AlertDialog(){ } public void performClick(){ okBtn.performClick(); } public void updateField(String text){ counterTv.setText(text); } #Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.dialog, container); msgTv = (TextView)v.findViewById(R.id.textDialog); imgV = (ImageView)v.findViewById(R.id.imageDialog); counterTv = (TextView)v.findViewById(R.id.timeCounterDialog); if(imageId != 0) imgV.setImageResource(imageId); else imgV.setImageResource(R.drawable.error_icon); if(hasContent()){ msgTv.setText(message); getDialog().setTitle(title); } else{ getDialog().setTitle("ERROR"); msgTv.setText("An unexcepted error occured"); } okBtn = (Button)v.findViewById(R.id.validateButton); okBtn.setOnClickListener(new View.OnClickListener() { #Override public void onClick(View v) { if(mDialogListener != null){ mDialogListener.onFinishedDialog(); } } }); return v; } #Override public void onStart() { mDialogListener.onStartedDialog(); super.onStart(); } #Override public void onAttach(Activity activity) { mDialogListener = (AlertDialogListener) activity; super.onAttach(activity); } #Override public void onDetach() { mDialogListener = null; super.onDetach(); } public interface AlertDialogListener{ void onStartedDialog(); void onFinishedDialog(); } } And this is how I launch it: class myActivity extends Activity implements AlertDialogListener{ protected void onCreate(Bundle savedInstanceState){ """some init stuff""" button.setOnClickListener(new View.OnClickListener() { showAlertDialog(); } } #Override public void onStartedDialog() { AutoCloseRunnable mAutoClose = new AutoCloseRunnable(); mHandler.postDelayed(mAutoClose, 1000); } #Override public void onFinishedDialog() { this.finish(); } private void showAlertDialog(){ FragmentManager fm = getFragmentManager(); mAlertDialog = new AlertDialog(); mAlertDialog.setContent("No Connection available", "Please enable your internet connection."); mAlertDialog.setImage(R.drawable.error_icon); mAlertDialog.show(fm, "fragment_alert"); } private void updateAlertDialog(String text){ mAlertDialog.updateField(text); } private void autoCloseAlertDialog(){ mAlertDialog.performClick(); } public class AutoCloseRunnable implements Runnable{ #Override public void run() { int closeCpt = 10; while(closeCpt >= 0){ try { Thread.sleep(1000); updateAlertDialog("Will close automatically in " + closeCpt + " seconds."); closeCpt--; } catch (InterruptedException e) { e.printStackTrace(); } } autoCloseAlertDialog(); } } } Does anyone know how to proceed?
I solved it, simply use asynctask it's easier to handle UI updates like this.
The value of the variable has been suddenly set to 0
I'm doing an activity to measure how long it takes a person to do an exercise, but it has a bug that I couldn't resolve yet... The TrainingFragment shows a list of exercises that the user can click and then my ExerciseActivity is launched and runs until the variable "remainingsSets" is setted to 0. When I click in the first time at any exercise, everything works fine, the ExerciseActivity works correctly end return to the TrainingFragment. But then, if I try to click in another exercise, the ExerciseActivity is just closed. In my debug, I could see that the variable "remainingSets" comes with it's right value (remainingSets = getIntent().getIntExtra("remaining_sets", 3)), but when the startButton is clicked, I don't know why the variable "remainingSets" is setted to 0 and then the activity is closed because this condition: if (remainingSets > 0){...}. Here is my TrainingFragment: public class TrainingFragment extends Fragment { private final static int START_EXERCISE = 1; private Training training; private String lastItemClicked; private String[] values; #Override public void onAttach(Activity activity) { super.onAttach(activity); Bundle bundle = getArguments(); if (bundle != null) { training = bundle.getParcelable("training"); } } #Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return (ScrollView) inflater.inflate(R.layout.template_exercises, container, false); } #Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); LinearLayout exercisesContainer = (LinearLayout) getView().findViewById(R.id.exercises); LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE); List<Exercise> exercises = training.getExercises(); values = new String[exercises.size()]; if (savedInstanceState != null) { values = savedInstanceState.getStringArray("values"); } for (int i = 0; i < exercises.size(); i++) { final View exerciseView = inflater.inflate(R.layout.template_exercise, null); exerciseView.setTag(String.valueOf(i)); TextView remainingSets = (TextView) exerciseView.findViewById(R.id.remaining_sets); if (savedInstanceState != null) { remainingSets.setText(values[i]); } else { String sets = exercises.get(i).getSets(); remainingSets.setText(sets); values[i] = sets; } exerciseView.setOnClickListener(new OnClickListener() { #Override public void onClick(View v) { Intent intent = new Intent(getActivity(), ExerciseActivity.class); intent.putExtra("remaining_sets", Integer.valueOf(((TextView) v.findViewById(R.id.remaining_sets)).getText().toString())); lastItemClicked = v.getTag().toString(); startActivityForResult(intent, START_EXERCISE); } }); exercisesContainer.addView(exerciseView); } } #Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putStringArray("values", values); } #Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); View view = ((LinearLayout) getView().findViewById(R.id.exercises)).findViewWithTag(lastItemClicked); if (requestCode == START_EXERCISE) { if (resultCode == Activity.RESULT_OK) { // the exercise had been // finished. ((TextView) view.findViewById(R.id.remaining_sets)).setText("0"); view.setClickable(false); values[Integer.valueOf(lastItemClicked)] = "0"; } else if (resultCode == Activity.RESULT_CANCELED) { String remainingSets = data.getStringExtra("remaining_sets"); ((TextView) view.findViewById(R.id.remaining_sets)).setText(remainingSets); values[Integer.valueOf(lastItemClicked)] = remainingSets; } } } } My ExerciseActivity: public class ExerciseActivity extends Activity { private Chronometer chronometer; private TextView timer; private Button startButton; private Button endButton; private int remainingSets; #Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_exercise); ExerciseEvents.addExerciseListener(new PopupExerciseListener()); chronometer = (Chronometer) findViewById(R.id.exercise_doing_timer); timer = (TextView) findViewById(R.id.timer); startButton = (Button) findViewById(R.id.start_exercise); startButton.setOnClickListener(new OnClickListener() { #Override public void onClick(View v) { ExerciseEvents.onExerciseBegin(); } }); endButton = (Button) findViewById(R.id.end_exercise); endButton.setOnClickListener(new OnClickListener() { #Override public void onClick(View v) { ExerciseEvents.onExerciseRest(); } }); } #Override public void onBackPressed() { Intent intent = new Intent(); intent.putExtra("remaining_sets", String.valueOf(remainingSets)); setResult(RESULT_CANCELED, intent); super.onBackPressed(); } public class PopupExerciseListener implements ExerciseListener { public PopupExerciseListener() { remainingSets = getIntent().getIntExtra("remaining_sets", 3); } #Override public void onExerciseBegin() { if (remainingSets > 0) { chronometer.setVisibility(View.VISIBLE); timer.setVisibility(View.GONE); chronometer.setBase(SystemClock.elapsedRealtime()); chronometer.start(); startButton.setVisibility(View.GONE); endButton.setVisibility(View.VISIBLE); } else { ExerciseEvents.onExerciseFinish(); } } #Override public void onExerciseFinish() { setResult(RESULT_OK); finish(); } #Override public void onExerciseRest() { chronometer.setVisibility(View.GONE); endButton.setVisibility(View.GONE); timer.setVisibility(View.VISIBLE); long restTime = getIntent().getLongExtra("time_to_rest", 60) * 1000; new CountDownTimer(restTime, 1000) { #Override public void onTick(long millisUntilFinished) { timer.setText(String.valueOf(millisUntilFinished / 1000)); } #Override public void onFinish() { ExerciseEvents.onExerciseBegin(); } }.start(); remainingSets--; } } } And my ExerciseEvents: public class ExerciseEvents { private static LinkedList<ExerciseListener> mExerciseListeners = new LinkedList<ExerciseListener>(); public static void addExerciseListener(ExerciseListener listener) { mExerciseListeners.add(listener); } public static void removeExerciseListener(String listener) { mExerciseListeners.remove(listener); } public static void onExerciseBegin() { for (ExerciseListener l : mExerciseListeners) { l.onExerciseBegin(); } } public static void onExerciseRest() { for (ExerciseListener l : mExerciseListeners) { l.onExerciseRest(); } } public static void onExerciseFinish() { for (ExerciseListener l : mExerciseListeners) { l.onExerciseFinish(); } } public static interface ExerciseListener { public void onExerciseBegin(); public void onExerciseRest(); public void onExerciseFinish(); } } Could anyone give me any help?
After you updated your code, I see you have a big memory leak in your code: #Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_exercise); ExerciseEvents.addExerciseListener(new PopupExerciseListener()); .... } The call ExerciseEvents.addExerciseListener(new PopupExerciseListener()) adds a new PopupExerciseListener to a static/global list: ExcerciseEvents.mExerciseListeners. Since the class PopupExerciseListener is an inner-class, it implicitly holds a reference to its enclosing ExcerciseActivity. This mean your code is holding on to each instance of ExcerciseActivity forever. Not good. This may also explain the weird behavior you see. When one of the onExcersizeXXX() methods is called, it will call all ExcerciseListeners in the linked-list, the ones from previous screens and the current one. Try this in your ExcerciseActivity.java: .... ExerciseListener mExerciseListener; .... #Override protected void onCreate(Bundle savedInstanceState) { .... .... mExerciseListener = new PopupExerciseListener() ExerciseEvents.addExerciseListener(mExerciseListener); .... .... } #Override protected void onDestroy() { ExerciseEvents.removeExerciseListener(mExerciseListener); super.onDestroy(); } .... In onDestroy, you deregister your listener, preventing a memory leak and preventing odd multiple callbacks to PopupExerciseListeners that are attached to activities that no longer exist.