Print listing name

I am using eclipse + Android SDK on ubuntu.

I would like to type the name of the device type sensor, there is LOT OF THEM , and I want to do this automatically.

If i use

Log.d("SENSORTYPE","Type: " + tempSensor.getType()) 

I type (int), but I would like the name to use an enumeration.

How can i do this?

Thanks in advance.

+7
source share
3 answers

For enumerations, you can easily get an array of all constants and a loop over them using the following code:

 for(YourEnum value: YourEnum.values()){ System.out.println("name="+value.name()); } 

However, the Sensor class you are referring to is not an enumeration, but contains a list of constants. There is no way to program a loop over this list as an enumeration without listing all constant names.

However, you can create a static search that maps ints to the String value that you want to use, for example

 Map<Integer,String> lookup = new HashMap<Integer,String>(); lookup.put(TYPE_ACCELEROMETER,"Accelerometer"); //Code a put for each TYPE, with the string you want to use as the name 

You can use it as follows:

 Log.d("SENSORTYPE","Type: " + lookup.get(tempSensor.getType())); 

This approach means that you still have to write out each constant and update the list if the constants change, but you only need to do this once. It would be nice to wrap the search with some sort of helper method or class depending on how widely you want to reuse it.

+13
source

you can introduce an abstract method and implement it in each enumeration

 enum Colour { Red { @Override String colourName() { return "Red"; } }; abstract String colourName(); } 

This method gives you great flexibility, for example, if you do not want to display its program name

+4
source
 Log.d("SENSORNAME", "NAME: " + tempSensor.name()); 
+3
source

All Articles