How to set a value programatically from resources string? - java

Lets say we have something like this in strings.xml:
<string name=“hello”>Hello world</string>
Now I want to set a value to a TextView using this string. Should I do it in java class like this:
TextView msgTextView = (TextView) findViewById(R.id.msg);
msgTextView.setText(R.string.hello);
or in xml file like below?
android:text="#string/hello"
Which approach is better? Or when it is better to use the first way and when the second one?

You should do neither. There is relatively new approach , called databinding (it was demo in 2015) and now this library is officially supported by Google. It is a manifestation of MVVM pattern and you should use it, because it limplifies your code and makes it more maintainable in long term. See https://developer.android.com/topic/libraries/data-binding/index.html . In few words- you create Java class with fields and accessirs and set its fields as xml attributes. By doing so, AndroidStudio will generate all .findViewbyId() boilerplate for you. you just create model and set it to that particular binding.

Regarding performance, it won't make any difference. I personally prefer to do it in XML, since it doesn't clutter your activity code.

Both approach is correct. If you want to internationalize your variable that time (change languages) both will be work. In reference of memory or speed dynamically change is correct(means using getResource() or R.string.hello).

at first you should set it in xml.(or leave it empty.) but if you want to change it when something else happens (for example when user click a button or anything else.) you should set it in java.

First method is generally used when you want your textview to be fixed and final .
Second method is recommended as the textview's value may change during the course of operation of app .Initially in second method , a value is shown by textview which shows its purpose or type . For e.g second one may be used in displaying progress of background task .

Related

Why strings should be hardcoded when using sharedPreferences?

I have heard that using editor.putString("Message","Hello"); is bad practice, and you should instead do editor.putString(getString(R.string.messagestring),"Hello");. But why? It is longer and has the same result, and looks more messy imo. Is it because it's harder to make a typo?
Here is an example from Signal:
Source
if (params[0] < SCREENSHOTS) {
boolean screenSecurity = PreferenceManager.getDefaultSharedPreferences(context).getBoolean(TextSecurePreferences.SCREEN_SECURITY_PREF, true);
TextSecurePreferences.setScreenSecurityEnabled(getApplicationContext(), screenSecurity);
}
String values in code for human readable text are bad.
Doing so makes localization impossible.
Values from R.string. on the other hand automagically use the right language (given that you use values, values-es, values-fr, ... and put translations)
Note: You should probably not translate the key of a SharedPreference but the value ("Hello") part since that's presumably the human readable thing.
editor.putString("message", getString(R.string.messagestring));
The key could change if the user changes device language which means the old stored value will no longer be found under the new key. If you want keys in a central place it's a good idea to have them defined as static final constants in code.
editor.putString(MyPrefConstants.PREF_MESSAGE, getString(R.string.messagestring));
I would actually consider using keys that come from R.string a very questionable design decision. This applies to anything that is intended to be machine-consumed rather than visible text to the user. There are a few exceptions but they are rare.
It's Not Necessary but Good Practice.
eg.
editor.putString("Message","Hello");
here the key -> "Message"
it is possible that sometimes you make a TYPING ERROR or SPELLING MISTAKE of writing "Message" to "Massage" or something else.
to avoid these type of situations, we should write in this way
editor.putString(getString(R.string.messagestring),"Hello");
It's all about maintenance, reusability, cleanness and if needed easier localization. Take for example "Message".
How many times would you use this string in your code if it is the key for Preferences? More than 1, right? Imagine that you write over and over "Message". Isn't it possible to misspell it at least once? Well you can't misspell a string resource, because the compiler won't let you.
Another thing: you know where all your UI strings are so you know where to look when you need to change 1 of them and once you do it is changed throughout the app.
Finally if you want your up to be multilingual this is the only way with the Editor provided by AS.
Edit: As for the question if strings like keys for Preferences should be in the Resources my answer is yes. It's up to the programmer to give proper ids to the string resources so to distinguish the UI items from the in-app items.

How to assign a value to a variable in Android studio

I'm trying to do a simple text game where the player has a weapon.
I want that, when clicking a certain option, the value that holds the weapon name "knife" gets updated to "sword".
I made a resources string that holds the "knife" value but can't seem to find a syntax that will update it.i already read that maybe you can't change resource values. Is this true?
If it is. How do I solve this?
Thanks.
It seems like you really need to go back and start with the basics of Android and Internationalization. It is not possible to update a resource at runtime, as you have correctly discovered, so it is your approach that needs to change.
Here is an example:
TextView text;
String value = getString(R.string.knife);
text.setText(value);
It seems that onClick you try to do something like:
setString(R.string.knife, "sword");
Which is impossible. Instead, you need to have the two strings as separate resources and then switch your value to the new resource when needed. So simply:
value = getString(R.string.sword);
text.setText(value); //and reset the display
For reference, if anyone stumbles upon the same problems, I found a good solution with Shared Preferences. It allows saving variable values in the device's memory.

XML string resources vs Java Constant Strings?

I have a String is like String data="apps";
i know loading String in Android in two ways..
First one is
so it is a constant i defined it as
public static final String data="apps";
And another type is defing it in res/vslues/strings.xml file like..
<string name="data">apps</string>
<string name="hello_world">Hello world!</string>
if i want to use it..
for the first way ClassName.data
for second way context.getResources().getString(resourceid)
Question:
so now my question is I want to use same String in 30 times in different classes.And I have more number of variables.so which will load faster and take lesser memory in the above methods..
However, speed shouldn't really be an issue in either case. I would recommend organizing based on what makes sense.
Constants class
Put strings constants that will be used internally, like database column names or other keys.
strings.xml
Put strings that are displayed for the user. This way you can take advantage of localization, etc.
As per requirement you should be prefer second approach means XML
based.
The XML string values are meant to be display strings that can be overridden based on locale. This way you can refer to a translatable display value by a constant key.
You should consider using XML strings as a way to display something to the user and change it depending on locale.
Never the less, public static final String data="apps"; should be used in order to hide some not-for-user data like db connections, log messages etc.
I'd suggest that you leverage the Android resource system.
To quote the book Android In Practice:
Resources in Android are efficient and fast. XML resources are compiled into a binary format. This makes them friendly at development time, without being slow at Runtime.
I think the speed and memory usage would be the same. The constant in a class is just like a constant in the string.xml which is stored once and referenced whenever you need it elsewhere.
However, the advantage of storing in string.xml over the other would be the extra import lines of code which would be avoided. Meanwhile, you have to remember that with string.xml storage you can only use it where the context of an activity is accessible.

How to set tags in android?

I'm trying to set a tag for a textView in android, but I cant seem to figure out how to set the tag, I tried using the following code, and it didn't have any errors but then I cant figure out how to use findViewByTag to do something with the textView later, any help would be appreciated!
playerCounter.setTag("playercounter"+counter);
I don't know of any built-in findViewByTag() function, are you confusing it with findViewById()?
Unlike IDs, tags are not used to identify views. Tags are essentially an extra piece of information that can be associated with a view. They are most often used as a convenience to store data related to views in the views themselves rather than by putting them in a separate structure.
From the Developer Documentation

Switching xml string files

I am working on a bilingual app menu. I am currently at a dilemma on how I would be able to switch the languages easy. At first I thought I could use String.xml file to store the data passed out in English then later on Chinese and just switch xml string file for a chinese menu but the String.xml can only use a unique name ID.
Is there any other way of doing this? In which I can create another string array and call it instantly like String.xml?
Any suggestions would be greatly appreciated, I am always willing to listen and get better if what I put down was no appropriate.
If I understand correctly you are looking for localization. Here is tutorial on how to implement this in Android.
Personally, I might make 2 (or more for more languages) apps that have the same function except for the fact that they are in different languages.

Categories

Resources