Search code examples
javaandroidandroid-resources

How to lookup for a string translation on android?


I need to translate error codes that i receive from one of owner servers.

So, instead of having a string id i have a string, the error code, and i need to check the resources for possible translation.

How can i perform a lookup?


Solution

  • Turns out that there is a function for that, getIdentifier.

    private String getStringResourceByName(Resources res, String aString) {
        String packageName =   App.getInstance().getPackageName();
        int resId =  App.getInstance().getResources().getIdentifier(aString, "string", packageName);
        return res.getString(resId);
    }
    

    Trying on a simple test:

    @Test
    public void test(){
    
        Resources res = serviceFactory.getApplicationContext().getResources();
    
        Log.d(TAG, "default language: "+ getStringResourceByName(res,"LG")); //will print the default definition.
    
        Configuration conf = res.getConfiguration();
        conf.locale = Locale.FRENCH; //for instance
        res.updateConfiguration(conf, null); //
    
        Log.d(TAG, "French: "+ getStringResourceByName( res,"LG"));//will print definition of LG in french resource file
    
    }