1

I have a stringDef/ TypeDef class as follows

public class Codes {
      public static final String Code_1 = "Code1";
      public static final String Code_2 = "Code2";
      public static final String Code_3 = "Code3";


      @Retention(RetentionPolicy.SOURCE) @StringDef({
            Code_1, Code_2, Code_3 })

      public @interface CodesMessageDef {
      }
}

I would like to set values of Code_1,2,3 from R.String.code_1 rather than manually entering.

Is there any way to achieve this usecase.

Thanks in advance.........

0x52616A657368
  • 388
  • 3
  • 24

1 Answers1

1

You can read this answer for how to get application context from a static method. Note that using this to get the context is not a memory leak because you are using an application context.

Now you can do:

public static final String Code_1 = MyApplication.getAppContext().getString(R.id.code1);
public static final String Code_2 = MyApplication.getAppContext().getString(R.id.code2);
public static final String Code_3 = MyApplication.getAppContext().getString(R.id.code3);

I guess it should work.

Community
  • 1
  • 1
Nicolas
  • 6,611
  • 3
  • 29
  • 73
  • Actually i'm able to get context but the issue is at @Retention(RetentionPolicy.SOURCE) @StringDef({ Code_1, Code_2, Code_3 }) It only accepts constants, but by using resouces the value cant be constant, Is there any possibility to overcome this?? – 0x52616A657368 May 04 '17 at 15:07
  • Just read a bit about that and turns out you can't do that sorry. But why did you want to do it maybe there's another solution? – Nicolas May 05 '17 at 21:20
  • I have an text field which only accepts one among these 5 strings provided. Initially i have used ENUM but trying to avoid ENUMS. – 0x52616A657368 May 06 '17 at 17:39
  • I tried it, but in case of multi language support it wont be applicable – 0x52616A657368 May 07 '17 at 03:26