Android: How do I get string from resources using its name?

680,922

Solution 1

Verify if your packageName is correct. You have to refer for the root package of your Android application.

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

Solution 2

Not from activities only:

public static String getStringByIdName(Context context, String idName) {
    Resources res = context.getResources();
    return res.getString(res.getIdentifier(idName, "string", context.getPackageName()));
}

Solution 3

getResources().getString(getResources().getIdentifier("propertyName", "string", getPackageName()))

Solution 4

I would add something to the solution of leonvian, so if by any chance the string is not found among the resources (return value 0, that is not a valid resource code), the function might return something :

private String getStringResourceByName(String aString) {
    String packageName = getPackageName();
    int resId = getResources()
            .getIdentifier(aString, "string", packageName);
    if (resId == 0) {
        return aString;
    } else {
        return getString(resId);
    }
}

Solution 5

Best Approach

App.getRes().getString(R.string.some_id)

Will work Everywhere (Utils, Models also).

I have read all the answers, all answers can make your work done.

  • You can use getString(R.string.some_string_id) in both Activity or Fragment.
  • You can use Context.getString(R.string.some_string_id) where you don't have direct access to getString() method. Like Dialog.

Problem

When you don't have Context access, like a method in your Util class.

Assume below method without Context.

public void someMethod(){
    ...
    // can't use getResource() or getString() without Context.
}

Now you will pass Context as a parameter in this method and use getString().

public void someMethod(Context context){
    ...
    context.getString(R.string.some_id);
}

What i do is

public void someMethod(){
    ...
    App.getAppResources().getString(R.string.some_id)
}

What? It is very simple to use anywhere in your app!

So here is a solution by which you can access resources from anywhere like Util class .

import android.app.Application;
import android.content.res.Resources;

public class App extends Application {
    private static Resources resources;

    @Override
    public void onCreate() {
        super.onCreate();

        resources = getResources();
    }

    public static Resources getAppResources() {
        return resources;
    }

}

Add name field to your manifest.xml <application tag.

<application
        android:name=".App"
        ...
        >
        ...
    </application>

Now you are good to go. Use App.getAppResources().getString(R.string.some_id) anywhere in app.

Share:
680,922
Ivan
Author by

Ivan

I am a beginner in Android development, however have 10 years experience in app development (C++, PHP, Lotus Notes)

Updated on November 10, 2021

Comments

  • Ivan
    Ivan over 2 years

    I would like to have 2 languages for the UI and separate string values for them in my resource file res\values\strings.xml:

    <string name="tab_Books_en">Books</string>
    <string name="tab_Quotes_en">Quotes</string>
    <string name="tab_Questions_en">Questions</string>
    <string name="tab_Notes_en">Notes</string>
    <string name="tab_Bookmarks_en">Bookmarks</string>
    
    <string name="tab_Books_ru">Книги</string>
    <string name="tab_Quotes_ru">Цитаты</string>
    <string name="tab_Questions_ru">Вопросы</string>
    <string name="tab_Notes_ru">Заметки</string>
    <string name="tab_Bookmarks_ru">Закладки</string>
    

    Now I need to retrieve these values dynamically in my app:

    spec.setContent(R.id.tabPage1);
    String pack = getPackageName();
    String id = "tab_Books_" + Central.lang;
    int i = Central.Res.getIdentifier(id, "string", pack);
    String str = Central.Res.getString(i);
    

    My problem is that i = 0.

    Why does not it work in my case?

  • Xarvalus
    Xarvalus over 5 years
    +1 simple & clean solution. Notice bad spelling getResourses, the getResources would cause override. Also the singleton pattern seems unnecessary, possibly could be skipped. Any memory leaks problems with this solution?
  • Khemraj Sharma
    Khemraj Sharma over 5 years
    @Xarvalus Does this make memory leak?
  • Xarvalus
    Xarvalus over 5 years
    in my app all fine :) just wondering if anyone had any problem with it. I will let know If I encounter any pitfall.
  • Khemraj Sharma
    Khemraj Sharma over 5 years
    @Xarvalus Memory Leak usually occur at place where an variable is being used even parent class is destroyed. Like in Activities, Fragments. I don't think it will occur in this case.
  • Sourabh
    Sourabh almost 4 years
    This wouldn't work all the time. The String could end up being displayed as the address number.