Android-onOptionsItemSelected método llamado dos veces

He implementado ActionBarSherlock con el SupportMapFragment guiado por la respuesta aceptada de esta pregunta. Todo funciona bien. Pero el único problema es que el método onOptionsItemSelected se llama dos veces. Aquí está el código-

 @Override public boolean onOptionsItemSelected( com.actionbarsherlock.view.MenuItem item) { switch (item.getItemId()) { case R.id.navigation: Log.d("tag","text"); break; } return super.onOptionsItemSelected(item); } 

EDITAR-

Esta es toda mi clase FragmentMaps :

 package com.vishalaksh.technex; import android.database.Cursor; import android.os.Bundle; import android.preference.PreferenceManager; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import com.actionbarsherlock.view.MenuItem; import com.actionbarsherlock.view.SubMenu; import com.google.android.gms.maps.CameraUpdate; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.GoogleMap.CancelableCallback; import com.google.android.gms.maps.UiSettings; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; import com.vishalaksh.technex.db.DatabaseHelper; import com.vishalaksh.technex.db.DbConstants; import com.vishalaksh.technex.utils.Constants; import com.vishalaksh.technex.utils.JSONconstants; import com.vishalaksh.technex.utils.MapConstants; import com.vishalaksh.technex.utils.SherlockMapFragment; public class FragmentMaps extends SherlockMapFragment implements MapConstants, Constants, DbConstants, JSONconstants { private GoogleMap mMap; private static final int VIEW = 0; DatabaseHelper db; public FragmentMaps() { super(); } public static FragmentMaps newInstance() { FragmentMaps frag = new FragmentMaps(); return frag; } @Override public View onCreateView(LayoutInflater arg0, ViewGroup arg1, Bundle arg2) { View v = super.onCreateView(arg0, arg1, arg2); db = new DatabaseHelper(getActivity()); setUpMapIfNeeded(); return v; } public void setUpMapIfNeeded() { // Do a null check to confirm that we have not already instantiated the // map. if (mMap == null) { // Try to obtain the map from the SupportMapFragment. mMap = getMap(); // Check if we were successful in obtaining the map. if (mMap != null) { setUpMap(); } } } private void setUpMap() { UiSettings settings = mMap.getUiSettings(); settings.setAllGesturesEnabled(true); settings.setMyLocationButtonEnabled(true); mMap.setMyLocationEnabled(true); mMap.moveCamera(CameraUpdateFactory.newCameraPosition(BHU_position)); GoToIITBHU(); /* * the following block shifted to onresume() if * (getActivity().getComponentName().getClassName() * .equalsIgnoreCase(Activity_msg_map.class.getName())) { // * Activity_msg_map setupMsgMap(); } else { // activity main * setupMain(); setHasOptionsMenu(true); } */ } @Override public void onResume() { // TODO Auto-generated method stub super.onResume(); if (mMap != null) { if (getActivity().getComponentName().getClassName() .equalsIgnoreCase(Activity_msg_map.class.getName())) { // Activity_msg_map setupMsgMap(); } else { // activity main setupMain(); setHasOptionsMenu(true); } } } private boolean checkReady() { if (mMap == null) { Toast.makeText(getActivity(), R.string.map_not_ready, Toast.LENGTH_SHORT).show(); return false; } return true; } @Override public void onCreateOptionsMenu(com.actionbarsherlock.view.Menu menu, com.actionbarsherlock.view.MenuInflater inflater) { // menu.add(VIEW, VIEW_PLACES_MENU_ITEM, 0, // "View Places").setShowAsAction( // MenuItem.SHOW_AS_ACTION_ALWAYS|MenuItem.SHOW_AS_ACTION_WITH_TEXT); // menu.add(VIEW, VIEW_EVENTS_MENU_ITEM, 0, // "View Events").setShowAsAction( // MenuItem.SHOW_AS_ACTION_ALWAYS|MenuItem.SHOW_AS_ACTION_WITH_TEXT); menu.clear(); SubMenu optionsMenu = menu.addSubMenu("View"); optionsMenu.add(VIEW, VIEW_PLACES_MENU_ITEM, 0, "View Places"); optionsMenu.add(VIEW, VIEW_EVENTS_MENU_ITEM, 1, "View Events"); // TODO import mdpi n other resources MenuItem subMenu1Item = optionsMenu.getItem(); subMenu1Item.setIcon(R.drawable.ic_action_view).setShowAsAction( MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT); super.onCreateOptionsMenu(menu, inflater); } @Override public boolean onOptionsItemSelected( com.actionbarsherlock.view.MenuItem item) { switch (item.getItemId()) { case VIEW_PLACES_MENU_ITEM: Toast.makeText(getActivity(), EXTRA_EVENT_CATEGORY, Toast.LENGTH_SHORT).show();//This toast is displayed two times. // TODO clear markers if any clearmarkers(); // TODO put place markers PreferenceManager.getDefaultSharedPreferences(getActivity()).edit() .putInt(PREF_MAP_VIEW, VIEW_LOC).commit(); putLocationMarkers(); break; case VIEW_EVENTS_MENU_ITEM: // TODO clear markers if any clearmarkers(); // TODO put event markers PreferenceManager.getDefaultSharedPreferences(getActivity()).edit() .putInt(PREF_MAP_VIEW, VIEW_EVENT).commit(); putEventMarkers(); break; } return super.onOptionsItemSelected(item); } private void putEventMarkers() { // get all the locations which have events Cursor cLocation = db.getReadableDatabase().query(tableEventsName, new String[] { colForeignLocationsNameTableEvent }, null, null, colForeignLocationsNameTableEvent, null, null); if (cLocation.getCount() == 0) { Log.d(TAG, "cLocation.getCount()==0"); return; } else { Log.d(TAG, "total " + cLocation.getCount() + " locations found having events..."); } cLocation.moveToFirst(); do { // get each location name String location = cLocation.getString(cLocation .getColumnIndexOrThrow(colForeignLocationsNameTableEvent)); // get the details of this location Cursor cLocationDetails = db.getReadableDatabase().query( tableLocationsName, null, colNameTableLocations + " =? ", new String[] { location }, null, null, null); if (cLocationDetails.getCount() != 1) { Log.w(TAG, "no. of locations in cursor cLocationDetails in FragmentMaps is not 1!, its:" + cLocationDetails.getCount()); } cLocationDetails.moveToFirst(); double lat = cLocationDetails.getDouble(cLocationDetails .getColumnIndexOrThrow(colLatTableLocations)); double lng = cLocationDetails.getDouble(cLocationDetails .getColumnIndexOrThrow(colLongTableLocations)); String title = cLocationDetails.getString(cLocationDetails .getColumnIndexOrThrow(colNameTableLocations)); // get list of events for a particular location Cursor cEvent = db.getReadableDatabase().query(tableEventsName, null, colForeignLocationsNameTableEvent + " =? ", new String[] { location }, null, null, null); if (cEvent.getCount() == 0) { Log.e(TAG, "no events found for the location:" + location); /* * mMap.addMarker(new MarkerOptions().position( new LatLng(lat, * lng)).title(title)); */} else { cEvent.moveToFirst(); StringBuilder sb = new StringBuilder(); do { sb.append(cEvent.getString(cEvent .getColumnIndexOrThrow(colEventNameTableEvent))); sb.append(DELIMITER_SNIPPET); } while (cEvent.moveToNext()); // delete last delimiter sb.delete(sb.lastIndexOf(DELIMITER_SNIPPET), sb.length() - 1); String snippet = sb.toString(); mMap.addMarker(new MarkerOptions() .position(new LatLng(lat, lng)) .title(getCorrectTitle(title)) .snippet(snippet) .icon(BitmapDescriptorFactory .defaultMarker(BitmapDescriptorFactory.HUE_YELLOW))); } } while (cLocation.moveToNext()); } private void putLocationMarkers() { /* * Cursor c = db.getReadableDatabase().query(tableLocationsName, null, * null, null, null, null, null); */ Cursor c = db.getReadableDatabase().rawQuery( "SELECT * FROM " + tableLocationsName + " WHERE " + colTrivialtableLocations + " !=?", new String[] { String.valueOf(TRIVIAL) }); if (c.getCount() == 0) { Log.e(TAG, "cursor doesnt contain locations in FragmentMaps"); return; } c.moveToFirst(); do { double lat = c.getDouble(c .getColumnIndexOrThrow(colLatTableLocations)); double lng = c.getDouble(c .getColumnIndexOrThrow(colLongTableLocations)); String title = c.getString(c .getColumnIndexOrThrow(colNameTableLocations)); String snippet = c.getString(c .getColumnIndexOrThrow(colSnippetTableLocations)); mMap.addMarker(new MarkerOptions() .position(new LatLng(lat, lng)) .title(getCorrectTitle(title)) .snippet(snippet) .icon(BitmapDescriptorFactory .defaultMarker(BitmapDescriptorFactory.HUE_RED))); } while (c.moveToNext()); } @Override public void onDestroy() { if (db != null) { db.close(); } super.onDestroy(); } private void clearmarkers() { mMap.clear(); } private void setupMain() { clearmarkers(); if (PreferenceManager.getDefaultSharedPreferences(getActivity()) .getInt(PREF_MAP_VIEW, VIEW_LOC) == VIEW_LOC) { putLocationMarkers(); } else { putEventMarkers(); } } private void setupMsgMap() { String locname = getActivity().getIntent().getStringExtra( EXTRA_UPDATE_LOC); Log.d(TAG, "the location received by map is:" + locname); /* * Cursor c = db.getReadableDatabase().query(tableLocationsName, null, * colNameTableLocations + "=?", new String[] { locname }, null, null, * null); */ Cursor c = db.getReadableDatabase().rawQuery( "SELECT * FROM " + tableLocationsName + " WHERE " + colNameTableLocations + "=? LIMIT 1", new String[] { locname }); if (c.getCount() != 1) { Log.e(TAG, "cursor doesnt contain single location in FragmentMaps it contains:" + c.getCount()); return; } c.moveToFirst(); double lat = c.getDouble(c.getColumnIndexOrThrow(colLatTableLocations)); double lng = c .getDouble(c.getColumnIndexOrThrow(colLongTableLocations)); String title = c.getString(c .getColumnIndexOrThrow(colNameTableLocations)); mMap.addMarker(new MarkerOptions() .position(new LatLng(lat, lng)) .title(getCorrectTitle(title)) .icon(BitmapDescriptorFactory .defaultMarker(BitmapDescriptorFactory.HUE_YELLOW))); } /** * Called when the Go To Bondi button is clicked. */ void GoToIITBHU() { if (!checkReady()) { return; } changeCamera(CameraUpdateFactory.newCameraPosition(IITBHU)); } private void changeCamera(CameraUpdate update) { changeCamera(update, null); } /** * Change the camera position by moving or animating the camera depending on * the state of the animate toggle button. */ private void changeCamera(CameraUpdate update, CancelableCallback callback) { // boolean animated = ((CompoundButton) // findViewById(R.id.animate)).isChecked(); if (true) { mMap.animateCamera(update, callback); } else { mMap.moveCamera(update); } } private String getCorrectTitle(String title) { if (title.equalsIgnoreCase(SBGround.NAME)) { return "Swatantrata Bhavan Ground"; } else if (title.equalsIgnoreCase(SB.NAME)) { return "Swatantrata Bhavan"; } else { return title; } } 

}

En su método onOptionsItemSelected no llame al método onOptionsItemSelected al final

 return super.onOptionsItemSelected(item); 

En cambio devuelve verdadero.

 @Override public boolean onOptionsItemSelected( com.actionbarsherlock.view.MenuItem item) { switch (item.getItemId()) { case VIEW_PLACES_MENU_ITEM: Toast.makeText(getActivity(), EXTRA_EVENT_CATEGORY, Toast.LENGTH_SHORT).show();//This toast is displayed two times. // TODO clear markers if any clearmarkers(); // TODO put place markers PreferenceManager.getDefaultSharedPreferences(getActivity()).edit() .putInt(PREF_MAP_VIEW, VIEW_LOC).commit(); putLocationMarkers(); break; case VIEW_EVENTS_MENU_ITEM: // TODO clear markers if any clearmarkers(); // TODO put event markers PreferenceManager.getDefaultSharedPreferences(getActivity()).edit() .putInt(PREF_MAP_VIEW, VIEW_EVENT).commit(); putEventMarkers(); break; default: return super.onOptionsItemSelected(item); } return true; } 

Yo tuve el mismo problema. Lo que funcionó para mí:

reemplazar

 return super.onOptionsItemSelected(item); 

con

 return true; 

Y no hacer la llamada súper en onOptionsItemSelected. Espero que esto funcione para usted también.

  • Carga de datos desde la aplicación de Android al programa de escritorio
  • Utilizar Bouncy Castle para extraer información de certificados de android
  • CancelaciónExcepción al utilizar ExecutorService
  • Android.annotation no se puede resolver
  • Error: Error de ejecución para la tarea ': app: transformClassesAndResourcesWithProguardForRelease
  • Cómo establecer varias etiquetas a un botón?
  • ¿Qué clase debo usar para Date's en Android?
  • Agregar un círculo de cuadro redondo en mapa de bits redondeado
  • ¿Cómo puedo depurar eficazmente el código C que está envuelto con JNI en Eclipse? (Android Dev)
  • No se pudo escribir el volcado de núcleo. Minidumps no están habilitados de forma predeterminada en las versiones de cliente de Windows en Eclipse
  • "Flujo no representa una tienda de claves PKCS12" después de almacenar con una nueva contraseña en el dispositivo Android
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.