Last active
December 8, 2016 15:02
-
-
Save justintuchek/3baaac3ea07a4de72481d45993e14586 to your computer and use it in GitHub Desktop.
A safer way to loosely obtain Android String resources by name (instead of id.)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.botlink.stringresourceresolver; | |
import android.content.Context; | |
public final class StringResolver { | |
/** | |
* Value returned from {@link android.content.res.Resources#getIdentifier(String, String, String)} | |
* when resource name does not yield a valid resource id. | |
*/ | |
private static final int KEY_NOT_FOUND = 0; | |
public static String getValue(Context context, String name) { | |
final int key = context.getResources().getIdentifier(name, "string", context.getPackageName()); | |
final String value; | |
if(KEY_NOT_FOUND == key) { | |
/** | |
* Not found behavior open for modification: | |
* Fail fast during testing/debug builds. | |
* OR | |
* Log KEY_NOT_FOUND events to reporting system. | |
**/ | |
value = String.format("Identifier `%s` not found in package", name); | |
} else { | |
value = context.getResources().getString(key); | |
} | |
return value; | |
} | |
private StringResolver() { | |
throw new IllegalStateException("not designed for instantiation."); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment