I have the following Activity which starts a service of type service in android for it inside my Activity class I have the following
Intent i_service = new Intent(getApplicationContext(), MyService.class);
i_service.putExtra("nombre_clase", "Mapas");
startService(i_service);
and in my class MyService.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 class_name variable which does not present any error, but when I want it 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 do I solve this problem, in advance I thank you
The problem is that you are not comparing type objects
String
correctly.You must use the method
equals
, otherwise what you are comparing are objects and not their content and, therefore, they will always be different.This would be the correct code:
I've put
"Mapas".equals(nombre_clase)
instead ofnombre_clase.equals("Mapas")
to avoid possiblesNullPointerException
since you don't explicitly check if the value is null.You could also use
equalsIgnoreCase()
, which performs a case-insensitive comparison, for example:If you
nombre_clase
have the value of "maps":This comparison would have a value
false
:instead if you use
equalsIgnoreCase()
, it would have a valuetrue
: