[JAVA] [Android 9.0 Pie] Example of how to call strings.xml other than Activity and Fragment

at first

Strings.xml is useful for managing constants, but make a note of how to call it in a class that does not inherit Activity or Fragment.

Implementation method

I created a context in a class that inherited the Application class, and created a function for getting constants so that the calling code could be cut as much as possible.

Model.java


public class Model extends Application {
    private static Context context;

    @Override
    public void onCreate() {
        super.onCreate();
        context = this;
    }

    /**
     *Constant acquisition function
     * strings.You can get the constants defined in xml from anywhere
     * @param resId R.string.resId
     * @return String constant
     */
    public static String getConst(int resId) {
        return context.getResources().getString(resId);
    }
}

strings.xml


<string name="chat_list_delete_button_label">DELETE</string>

The caller can call with the following description

Model.getConst(R.string.chat_list_delete_button_label);

that's all.

I hope it will be helpful to anyone.

Recommended Posts

[Android 9.0 Pie] Example of how to call strings.xml other than Activity and Fragment
How to call classes and methods
[Android] How to make Dialog Fragment
JDBC promises and examples of how to write
How to write offline real time Implementation example by ruby and C99 of F04
How to use UsageStatsManager in Android Studio (How to check the startup time of other apps)
[Java] Types of comments and how to write them
[Android] How to get the setting language of the terminal
How to prevent editTextPreference of android PreferenceFragmentCompat from breaking
How to give Spring Security authenticated user information other than userId and password and how to refer to it
How to call AmazonSQSAsync
How to use OpenCV 4 on Android and view camera live view
How to call and use API in Java (Spring Boot)
How to implement one-line display of TextView in Android development
Procedures for passing RealmObject to Fragment and how to use Parceler
How to check the extension and size of uploaded files
How to deal with different versions of rbenv and Ruby