I have some code (Android 2.3.3).

Pattern p = Pattern.compile(R.string.regexDate + R.string.regexTime + R.string.regexLast); 

The Pattern.compile(String string) method Pattern.compile(String string) requires a parameter as strings, but from string.xml I get an int . Those. I get the identifiers from R.java , but I need strings right away ...

The resources themselves from string.xml

 <string name="regexDate" >^[2][\\d]{3}[0-1]{1}[\\d]{1}[0-3]{1}[\\d][_]</string> <string name="regexTime">[0-2][\\d]([0-5][\\d]){2}[_]</string> <string name="regexLast">[0]{3}[b][\\.][d][b]$</string> 

We read the documentation ...

One option to cast as a string:

 String s = getString(R.string.regexDate); 

The second option:

 Resources res = getResources(); res.getString(R.string.regexDate) 

I can not use these options, because getString(...), getResources() methods Eclipse does not see.

How can I take a string from string.xml right away, not its id ? If possible with an example.

    2 answers 2

    The getResources() or getString() methods are called from the Context , since the context has access to the program's resources.

    A string can not be obtained from string.xml .

    As a variant of the crutch, you can write enum :), but do not do this either, or use the public static final string in the class in which you use the Pattern

    • 2
      I will add the comment that in Java method cannot exist by itself. He belongs to a class. If you call a method without clearly specifying the object for which you want to call it, this is regarded as an attempt to call the method on the object within which you are working. That is, getString() is actually interpreted as this.getString() . And now see if your class has the getString() method inside of you - Vladyslav Matviienko
    • one
      @metalurgus The presence of a method from the class itself and the classes from which it is inherited, if absolutely accurate. - pavlofff

    The methods you use getResources() and getString() are context methods ( Context class) and to get the result, you first need to get the context into your class in any available way , from passing to your class through the constructor from where the context is (for example, calling your class from an activity that inherits from the class Context and contains it) before receiving the context from Application - this class is always available in the application and contains the context.

    After receiving an instance of the context, you can use its methods in your class:

     Resources res = context.getResources(); res.getString(R.string.regexDate); 

    Direct context can be obtained from the classes Application , Activity (and its heirs), Service , Fragment (and its heirs, through the getActivity() method) and others. Total 45 classes (section Known Indirect Subclasses )