how to read value from string.xml in android? - android

I have written the line:
String Mess = R.string.mess_1 ;
to get string value, but instead of returning string, it is giving me id of type integer. How can I get its string value? I mentioned the string value in the string.xml file.

Try this
String mess = getResources().getString(R.string.mess_1);
UPDATE
String string = getString(R.string.hello);
You can use either getString(int) or getText(int) to retrieve a string. getText(int) will retain any rich text styling applied to the string.
Reference: https://developer.android.com/guide/topics/resources/string-resource.html

In Activity:
this.getString(R.string.resource_name)
If not in activity but have access to context:
context.getString(R.string.resource_name)
application.getString(R.string.resource_name)

I'm using this:
String URL = Resources.getSystem().getString(R.string.mess_1);

By the way, it is also possible to create string arrays in the strings.xml like so:
<string-array name="tabs_names">
<item>My Tab 1</item>
<item>My Tab 2</item>
</string-array>
And then from your Activity you can get the reference like so:
String[] tab_names = getResources().getStringArray(R.array.tab_names);
String tabname1=tab_names[0];//"My Tab 1"

Only for future references.
In the String resources documentation it says:
You can use either getString(int) or getText(int) to retrieve a string. getText(int) will >retain any rich text styling applied to the string.

Solution 1
Context context;
String mess = context.getString(R.string.mess_1)
Solution 2
String mess = getString(R.string.mess_1)

In fragments, you can use
getActivity().getString(R.id.whatever);

If you want to add the string value to a button for example, simple use
android:text="#string/NameOfTheString"
The defined text in strings.xml looks like this:
<string name="NameOfTheString">Test string</string>

Details
Android Studio 3.1.4
Kotlin version: 1.2.60
Task
single line use
minimum code
use suggestions from the compiler
Step 1. Application()
Get link to the context of you application
class MY_APPLICATION_NAME: Application() {
companion object {
private lateinit var instance: MY_APPLICATION_NAME
fun getAppContext(): Context = instance.applicationContext
}
override fun onCreate() {
instance = this
super.onCreate()
}
}
Step 2. Add int extension
inline fun Int.toLocalizedString(): String = MY_APPLICATION_NAME.getAppContext().resources.getString(this)
Usage
strings.xml
<resources>
<!-- ....... -->
<string name="no_internet_connection">No internet connection</string>
<!-- ....... -->
</resources>
Get string value:
val errorMessage = R.string.no_internet_connection.toLocalizedString()
Results

You must reference Context name before using getResources() in Android.
String user=getApplicationContext().getResources().getString(R.string.muser);
OR
Context mcontext=getApplicationContext();
String user=mcontext.getResources().getString(R.string.muser);

You can read directly the value defined into strings.xml:
<resources>
<string name="hello">Hello StackOverflow!</string>
</resources>
and set into a variable:
String mymessage = getString(R.string.hello);
but we can define the string into the view:
<TextView
android:id="#+id/myTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello"/>

You can use this code:
getText(R.string.mess_1);
Basically, you need to pass the resource id as a parameter to the getText() method.

If you are in an activity you can use
getResources().getString(R.string.whatever_string_youWant);
If you are not in an Activity
use this :
getApplicationContext.getResource().getString(R.String.Whatever_String_you_want)

while u write R. you are referring to the R.java class created by eclipse, use getResources().getString() and pass the id of the resource from which you are trying to read inside the getString() method.
Example : String[] yourStringArray = getResources().getStringArray(R.array.Your_array);

**
I hope this code is beneficial
**
String user = getResources().getString(R.string.muser);

Update
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 is where 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.getRes().getString(R.string.some_id)
}
What? It is very simple to use anywhere in your app!
So here is a Bonus unique 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 App mInstance;
private static Resources res;
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
res = getResources();
}
public static App getInstance() {
return mInstance;
}
public static Resources getResourses() {
return res;
}
}
Add name field to your manifest.xml <application tag.
<application
android:name=".App"
...
>
...
</application>
Now you are good to go.

getString(R.string.your_string) get the result

String myString = getResources().getString(R.string.here_your_string_name);
Now your string is copied into myString. I hope it will work for you.

If you are using Jetpack Compose, you can use
stringResource(R.string.yourstring)

Related

(Android Xamarin) Get Resource string value instead of int

Im just starting to create a simple android app with the use of Xamarin using VS2012.
I know there is a type of Resource just for strings.
In my resource folder, i have an xml file like this:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="RecordsTable">records</string>
<string name="ProjectTable">projects</string>
<string name="ActivitiesTable">activities</string>
</resources>
In my code, I want to use the values of those resources like:
string recordTable = Resource.String.RecordsTable; //error, data type incompatibility
I know that Resource.String.<key> returns an integer so I cant use the code above.
I am hoping that recordTable variable will have a value of records.
Is there a way I can use the value of those resource string for my code's string variables?
try it as using Resources.GetString for getting string from string Resources
Context context = this;
// Get the Resources object from our context
Android.Content.Res.Resources res = context.Resources;
// Get the string resource, like above.
string recordTable = res.GetString(Resource.String.RecordsTable);
It's worth noting that you do not need to create an instance of Resources to access the resource table. This works equally well:
using Android.App;
public class MainActivity : Activity
{
void SomeMethod()
{
string str = GetString(Resource.String.your_resource_id);
}
}
GetString(), used this way, is a method defined on the abstract Context class. You can also use this version:
using Android.App;
public class MainActivity : Activity
{
void SomeMethod()
{
string str = Resources.GetString(Resource.String.your_resource_id);
}
}
Resources, used this way, is a read-only property on the ContextWrapper class, which Activity inherits from the ContextThemeWrapper class.
If you're not in an activity or another context, you should get the context and use it to get the Resources and PackageName, as the following example:
int resID = context.Resources.GetIdentifier(listEntryContact.DetailImage.ImageName, "drawable", context.PackageName);
imageView.SetImageResource(resID);
int int_recordTable = Resource.String.RecordsTable;
String recordTable = (String.valueOf(int_recordTable)); //no more errors
Get theint, then change it to a String

How can I convert the android resources int to a string. eg.: android.R.string.cancel?

How can I obtain the string value "cancel" from this resource int: android.R.string.cancel ?
thank you
Simply use Context#getString():
String string = getString(android.R.string.cancel);
I've already tried this approach but with no success... I've a class: public class MyDialogFragment extends DialogFragment {
A DialogFragment is not a subclass of Context, so you need to get access to a valid one (like your Activity's). Use this:
String string = getActivity().getString(android.R.string.cancel);
Or as your discovered you can use the Activity passed in onAttach(), but understand you can do this anywhere inside a Fragment as long as you have a valid Context to work with.
As indicated here: http://developer.android.com/reference/android/content/Context.html#getString(int)
String s = context.getString(android.R.string.cancel);
context can be the current activity, or any object inheriting the Context abstract class.
This will convert any Android resource into a string.
In this example I’ve used an ‘R.color.myColor’ but it will work with any Android resource type.
colors.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="btnDialBgColor">#00BFA5</color>
<color name="btnDialBgColorActive">#C51162</color>
</resources>
TypedValue typedValueActive = new TypedValue();
TypedValue typedValue = new TypedValue();
getResources().getValue(R.color.btnDialBgColorActive, typedValueActive, true);
getResources().getValue(R.color.btnDialBgColor, typedValue, true);
Hope this helps.
I know that's an old question, but it might help more people. What you can do is to call getIdentifier(). For that, you'll need to call it inserting after what value you want for a this variable, to make the string that you want for your resource ID. For exemple:
Your resources file:
R.string.cancel
In java:
int resourceId = getResources().getIdentifier("cancel", "string", this.getPackageName())
println(getResources().getString(resourceId));
Then, in your rescourceId variable, you'll have an equivalent to: R.string.cancel. And, in println, you'll have the value correspondent of your resources string.
In Kotlin:
val resourceId = this.resources.getIdentifier("cancel", "string", this.packageName)
println(resources.getString(resourceId))
With the same explanation that I said before.

call getString(R.strings....) from class?

Is there a way to use the getString method from a seperate class?
I have a string stored in my strings xml, I'd like to use that string in an object... but the method isn't even available in the object...
any tips?
getString() is a method of the Context class¹. If you need it inside a seperate class (that does not extend Context), it's usually best to provide it as a seperate argument to the method that needs it.
Example:
public void logString(Context c, int stringId) {
Log.d("TAG", c.getString(stringId));
}
One thing is important: Never store the context inside the separate class.
Provide an argument. Otherwise you will leak memory and disrupt the whole android lifecycle if the object that stores the context lives longer than the object where the context originally belongs to (e.g. an activity).
¹ getString() can also be used from the Resources class - which you can get via Context.getResources()
the solution here is to make sure your object has a reference to the application context
Class Swag{
private Context ctx;
public Swag(Context ctx){
this.ctx = ctx;
}
public void doSomething(){
String something = ctx.getResources().getString(R.string.somestring);
...
}
// or like this
public void makeUpperCase(Context appContext){
appContext.getResources().getString(R.string.super_string_swag_yolo);
}
}
obviously you'd have to supply the context when creating an object or when caling the method
resouce file: values/strings.xml
<resources>
<string name="app_name">App name</string>
<resources>
java
import android.content.res.Resources;
Resources.getSystem().getString(R.string.app_name);//result : App name
edit:
The below will NOT work. I read this on another site and assumed it worked, but I just tried it in my app and kept getting an error. Problem is, it will compile but you will get a runtime exception.
This will work from any java class:
import android.content.res.Resources
Resources.getSystem().getString(R.string.blah);
if you cannot pass a context as parameter, create another class, where you put all your static data.
example :
public class StaticData {
public static String BASE_URL = "https://stackoverflowrocks.com";
}
and get that string from your other class by calling directly
StaticData.BASE_URL
nice and clean.
This works, but for SYSTEM resources only:
import android.content.res.Resources
Resources.getSystem().getString(R.string.blah);
Reference: https://stackoverflow.com/a/40917607/8994882
Try this in your java file:
String myString = getResources().getString(R.string.MY_STRING)
Now use this string object.

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

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?
The link you are referring to seems to work with strings generated at runtime. The strings from strings.xml are not created at runtime.
You can get them via
String mystring = getResources().getString(R.string.mystring);
getResources() is a method of the Context class. If you are inside a Activity or a Service (which extend Context) you can use it like in this snippet.
Also note that the whole language dependency can be taken care of by the android framework.
Simply create different folders for each language. If english is your default language, just put the english strings into res/values/strings.xml. Then create a new folder values-ru and put the russian strings with identical names into res/values-ru/strings.xml. From this point on android selects the correct one depending on the device locale for you, either when you call getString() or when referencing strings in XML via #string/mystring.
The ones from res/values/strings.xml are the fallback ones, if you don't have a folder covering the users locale, this one will be used as default values.
See Localization and Providing Resources for more information.
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);
}
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()));
}
getResources().getString(getResources().getIdentifier("propertyName", "string", getPackageName()))
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);
}
}
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.
Easier way is to use the getString() function within the activity.
String myString = getString(R.string.mystring);
Reference: http://developer.android.com/guide/topics/resources/string-resource.html
I think this feature is added in a recent Android version, anyone who knows the history can comment on this.
getResources() works only when you're in Activity or Fragment class.
to get access to strings resource everywhere,
use:
Resources.getSystem().getString(android.R.string.somecommonstuff)
In case you are using Kotlin, you can define an extension function as follows:
fun Context.getStringResourceByName(stringName: String): String? {
val resId = resources.getIdentifier(stringName, "string", packageName)
return getString(resId)
}
And then simply use it. For example, in a Puzzles app I set the Activity title according to the image file name:
val stringName = "${folderName}_${assetName.substringBefore(".")}"
title = getStringResourceByName(stringName)
In this example I am reading string resources based on dynamic names.
If you don't have an Activity reference, you can use your context in this way:
getContext().getString(R.string.your_string_name);
In Kotlin, Leverage Extension functions 😎
fun Context.getStringByName(name: String): String {
return getString(resources.getIdentifier(name, "string", packageName))
}
There is also a set of predefined Android strings such as "Ok", "Cancel" and many others - so you don't have to declare all. They're available simply by:
getString(android.R.string.ok)
(In this case, "Ok" string). BTW there are also other Android resources available like for example icons images etc.
If you wannt get it inside an activity or fragmnet, then:
getContext().getResources().getString(R.string.string_name);
If you want to get it from a class outside of activity or fragment where you don't have the activity context then use application context:
getApplicationContext().getResources().getString(R.string.string_name);
String myString = getString(R.string.mystring);
easy way
You can try this in an Activity:
getResources().getString(R.string.your string name);
In other situations like fragments,... use
getContext().getResources().getString(R.string.your string name);
To safe, you should add:
mContext.getResources().getString(R.string.your_string);
mContext can be: context in onAttach() of Fragment or this of Activity.
R.string.<string_name>
Use that line directly in your java file. Keep it simple.

How to get a value of a string resource in constants file?

i am working on an application where i have to get a value of string resource to a constant. how can i do that? any ideas please.
The String is placed in
Application/res/values/strings.xml
and the name of the resource is let say app_version. now i want to get this app version to a constant string in another file. Any help is appreciated.
Try context.getResources().getString(R.string.app_version) where 'context' is your Activity or Application instance.
If your question is really about getting the version name of your application there is a better way:
String versionName = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
This way you retrieve the info directly from the AndroidManifest and you don't have to maintain it twice.
In Java: R.string.string_name
In XML:#string/string_name
R.string.app_version or #string/app_version taken from strings.xml is your constant and will always represent the value you entered into that XML file.
http://developer.android.com/guide/topics/resources/string-resource.html
All responses here aren't up to date. This is the right way to do it.
Better to use
#StringRes
public class AndroidClass{
...
#StringRes
private static final int[] TAB_TITLES = new int[]{R.string.tab1, R.string.tab2, R.string.tab_2};
private final Context mContext;
...
public CharSequence getString(int position) {
return mContext.getResources().getString(TAB_TITLES[position]);
}
}
I wanted to do this as well, but upon reflection, I'm not sure this is possible. We are trying to set a value at compile time that is not available until run time.
Constants are set at compile time. Now, the resource ID is available then, but the value, which Android can change by locale, is not. Therefore, the string value is not available until runtime.
My workaround was to make a public static value, and assign it if it is null, to the string value at create time. I probably should've just used a plain old instance variable, but this works.
Although, you can overwrite the value.
public class MyFragment
...
public static String SHOW_FOO;
...
public View onCreateView(...
if (SHOW_FOO == null) {
SHOW_FOO = getResources().getString(R.string.settings_foo_key);
}
....

Categories

Resources