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.........

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

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??
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?
I have an text field which only accepts one among these 5 strings provided. Initially i have used ENUM but trying to avoid ENUMS.
I tried it, but in case of multi language support it wont be applicable

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.