Error comparing values in Android (if)

1

I have the following Activity which starts a service type service on android for it within my class Activity I have the following

Intent i_service = new Intent(getApplicationContext(), MyService.class);
        i_service.putExtra("nombre_clase", "Mapas");
        startService(i_service);

and in my MyService.class class I have the following:

 public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(var,"servicio stratcomand");
        String nombre_clase = intent.getStringExtra("nombre_clase");
        Log.d("bbbbbbbbbb", "valor: "+nombre_clase);
        if(nombre_clase == "Mapas"){
            Log.d("aaaaaaaaaaa", "valor: "+nombre_clase);
        }else{
            Log.d("aaaaaaaaaaa", "noo error ");
        }
        return super.onStartCommand(intent, flags, startId);
    }

Before entering the condition I print the variable name_class which does not present any error, but when I want to print the value of the same variable within the condition I always get the message "no error", since the value "Maps" if it exists.

What I want to know is how to solve this problem, in advance I thank you

    
asked by Dimoreno 05.05.2017 в 08:21
source

2 answers

4

The problem is that you are not comparing objects of type String correctly.

You must use the equals method, otherwise what you are comparing are objects and not their content and, therefore, they will always be different.

This would be the correct code:

   public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(var,"servicio stratcomand");
        String nombre_clase = intent.getStringExtra("nombre_clase");
        Log.d("bbbbbbbbbb", "valor: "+nombre_clase);
        if("Mapas".equals(nombre_clase)){
            Log.d("aaaaaaaaaaa", "valor: "+nombre_clase);
        }else{
            Log.d("aaaaaaaaaaa", "noo error ");
        }
        return super.onStartCommand(intent, flags, startId);
    }

I have set "Mapas".equals(nombre_clase) instead of nombre_clase.equals("Mapas") to avoid possible NullPointerException since you do not explicitly check if the value is null.

    
answered by 05.05.2017 / 08:27
source
0
  

In the language Java the function equals() is used to compare    Strings , NEVER use the operator == .

   // if(nombre_clase == "Mapas"){
    if(nombre_clase.equals("Mapas")){
        Log.d("aaaaaaaaaaa", "valor: "+nombre_clase);
    }else{
        Log.d("aaaaaaaaaaa", "noo error ");
    }

You could also use equalsIgnoreCase() , which makes a comparison not importing uppercase or lowercase, for example:

If nombre_clase has the value of "maps":

nombre_clase = "mapas"

This comparison would have a value false :

nombre_clase.equals("Mapas")

instead if you use equalsIgnoreCase() , it would have a value true :

nombre_clase.equalsIgnoreCase("Mapas")
    
answered by 05.05.2017 в 16:33