error de sentencia switch case: las expresiones case deben ser expresiones constantes


Mi sentencia switch-case funciona perfectamente ayer. Pero cuando ejecuté el código temprano esta mañana eclipse me dio un error subrayando las declaraciones de mayúsculas y minúsculas en color rojo y dice: las expresiones de mayúsculas y minúsculas deben ser expresión constante, es constante No se lo que pasó. Aquí está mi código a continuación:

public void onClick(View src)
    {
        switch(src.getId()) {
        case R.id.playbtn:
            checkwificonnection();
            break;

        case R.id.stopbtn:
            Log.d(TAG, "onClick: stopping srvice");
            Playbutton.setImageResource(R.drawable.playbtn1);
            Playbutton.setVisibility(0); //visible
            Stopbutton.setVisibility(4); //invisible
            stopService(new Intent(RakistaRadio.this,myservice.class));
            clearstatusbar();
            timer.cancel();
            Title.setText(" ");
            Artist.setText(" ");
            break;

        case R.id.btnmenu:
            openOptionsMenu();
            break;
        }
    }

Todos R.id.int están todos subrayados en rojo.

Author: Jav_Rock, 2012-02-01

8 answers

En un proyecto Android normal, las constantes en la clase resource R se declaran así:

public static final int main=0x7f030004;

Sin embargo, a partir de ADT 14, en un proyecto de biblioteca, se declararán así:

public static int main=0x7f030004;

En otras palabras, las constantes no son finales en un proyecto de biblioteca. Por lo tanto, su código no compila.

La solución para esto es simple: Convierta la instrucción switch en un if-else instrucción.

public void onClick(View src)
{
    int id = src.getId();
    if (id == R.id.playbtn){
        checkwificonnection();
    } else if (id == R.id.stopbtn){
        Log.d(TAG, "onClick: stopping srvice");
        Playbutton.setImageResource(R.drawable.playbtn1);
        Playbutton.setVisibility(0); //visible
        Stopbutton.setVisibility(4); //invisible
        stopService(new Intent(RakistaRadio.this,myservice.class));
        clearstatusbar();
        timer.cancel();
        Title.setText(" ");
        Artist.setText(" ");
    } else if (id == R.id.btnmenu){
        openOptionsMenu();
    }
}

Http://tools.android.com/tips/non-constant-fields

Puede convertir rápidamente una instrucción switch en una instrucción if-else usando lo siguiente:

En Eclipse
Mueva el cursor a la palabra clave switch y presione Ctrl + 1 a continuación, seleccione

Convierte 'switch' a 'if-else'.

En Android Studio
Mueva el cursor a la palabra clave switch y presione Alt + Ingrese y luego seleccione

Reemplace 'switch' por 'if'.

 253
Author: Benito Bertoli,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-21 06:35:34

Desmarcar "Is Library" en las propiedades del proyecto funcionó para mí.

 51
Author: rick,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-11-06 12:15:19

La solución se puede hacer de esta manera:

  1. Sólo asignar el valor a Integer
  2. Hacer variable a final

Ejemplo:

public static final int cameraRequestCode = 999;

Espero que esto te ayude.

 9
Author: Hiren Patel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-02-01 09:44:31

R.id.*, ya que ADT 14 no se declaran más como int estática final por lo que no se puede utilizar en la construcción de caso de interruptor. Podrías usar la cláusula if else en su lugar.

 8
Author: Blackbelt,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-02-01 08:20:48

La solución simple para este problema es:

Haga clic en el interruptor y luego presione CTL + 1, Cambiará su interruptor a la instrucción de bloque if-else y resolverá su problema

 8
Author: Pir Fahim Shah,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-03-23 08:14:06

¿Qué tal esta otra solución para mantener el interruptor agradable en lugar de un if-else:

private enum LayoutElement {
    NONE(-1),
    PLAY_BUTTON(R.id.playbtn),
    STOP_BUTTON(R.id.stopbtn),
    MENU_BUTTON(R.id.btnmenu);

    private static class _ {
        static SparseArray<LayoutElement> elements = new SparseArray<LayoutElement>();
    }

    LayoutElement(int id) {
        _.elements.put(id, this);
    }

    public static LayoutElement from(View view) {
        return _.elements.get(view.getId(), NONE);
    }

}

Así que en tu código puedes hacer esto:

public void onClick(View src) {
    switch(LayoutElement.from(src)) {
    case PLAY_BUTTTON:
        checkwificonnection();
        break;

    case STOP_BUTTON:
        Log.d(TAG, "onClick: stopping srvice");
        Playbutton.setImageResource(R.drawable.playbtn1);
        Playbutton.setVisibility(0); //visible
        Stopbutton.setVisibility(4); //invisible
        stopService(new Intent(RakistaRadio.this,myservice.class));
        clearstatusbar();
        timer.cancel();
        Title.setText(" ");
        Artist.setText(" ");
        break;

    case MENU_BUTTON:
        openOptionsMenu();
        break;
    }
}

Los enum son estáticos, por lo que esto tendrá un impacto muy limitado. La única ventana de preocupación sería la doble búsqueda involucrada (primero en el SparseArray interno y más tarde en la tabla de interruptores)

Dicho esto, esta enumeración también se puede utilizar para obtener los elementos de una manera fluida, si es necesario manteniendo una referencia al id... pero eso es una historia para otro momento.

 7
Author: pablisco,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-03-11 11:21:37

Me estaba lanzando este error cuando uso switch en una función con variables declaradas en mi clase:

private void ShowCalendar(final Activity context, Point p, int type) 
{
    switch (type) {
        case type_cat:
            break;

        case type_region:
            break;

        case type_city:
            break;

        default:
            //sth
            break;
    }
}

El problema se resolvió cuando declaré final a las variables al inicio de la clase:

final int type_cat=1, type_region=2, type_city=3;
 3
Author: aimiliano,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-09-10 15:20:57

Me gustaría mencionar que, me encontré con la misma situación cuando intenté agregar una biblioteca a mi proyecto. De repente, todas las instrucciones de switch comenzaron a mostrar errores!

Ahora he intentado eliminar la biblioteca que he añadido, incluso entonces no funcionó. cómo siempre " cuando limpié el proyecto " todos los errores simplemente se disparó !

 2
Author: Muhammad Riyaz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-06-18 18:36:26