Yanshof Yanshof - 4 months ago 7
Android Question

why i fail to have string from enum?

I define a enum on my code:

public enum TimeType
{
One("1"),
Two("2"),
Three("3");

private String _friendlyName;

TimeType(String friendlyName) {
this._friendlyName = friendlyName;
}


@Override
public String toString() {
return _friendlyName;
}
}


Now, On some place i trying to convert the enum to a string:

TimeType t1 = TimeType.One;


I try to do it using in more then one way .. but i getting an exception

String str1 = t1.toString(); // fail
String str2 = TimeType.values()[t2].toString(); // fail
String str3 = t1.name(); // fail

Answer

The problem is you forgot add ; when you declare the enum

public enum TimeType{
     One("1"),
     Two("2"),
     Three("3"); // add ;

     private String _friendlyName;

     TimeType(String friendlyName) {
         this._friendlyName = friendlyName;
     }

     @Override
     public String toString() {
         return _friendlyName;
     }
 }

Here is the test in Java goo.gl/evcKMq
Here is the test in Android

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toast.makeText(this,TimeType.Two.toString(),Toast.LENGTH_SHORT).show();

        TimeType t1 = TimeType.One;
        String str1 = t1.toString();

        Log.e("TAG","str1 === "+str1);
    }

    public enum TimeType
    {
        One("1"),
        Two("2"),
        Three("3"); // add ;

        private String _friendlyName;
        TimeType(String friendlyName) {
            this._friendlyName = friendlyName;
        }
        @Override
        public String toString() {
            return _friendlyName;
        }
    }
}

The Toast display 2 and the Logcat print

07-12 00:05:42.892 2975-2975/com.example.newuser.testenum E/TAG: str1 === 1