I need to store a few values that are going to be use in several activities. I know could easily create a Constants class , a Interface or extend the Application class and put those constants there.
But not wanting to reinvent the wheel, I want to ask you if Android have something like appSettings in Asp.net or the Application Descriptor that we had in the old Java Me.
Thanks in advance.
Since you are using constants, there are two solutions:
Create an interface or class with public static final fields.
Create a XML resource file. See Resource Types for details about the resource types.
Personally I prefer 1 for constants that are used in my Java code because 2 requires a Context object and calls to getResources(). This just makes for more code than is really necessary.
Note that I don't give SharedPreference as a possible solution. This is because SharedPreferences should be used to store calculated or user data rather than constant values.
You could use SharedPreferences
Complete Docs
Related
I am wondering if you should use strings.xml instead of global constants. I learned that global variables should be avoided but then again strings.xml are probably not ment to be used like this?
Are there any advantages / disadvantages using one or the other?
I am pretty sure that hardcoded strings like the following is not a good way.
putExtra("extraKey", extra);
With strings.xml or Constants you have a spellcheck and autocompletion.
A typical line with R.string could look like this.
intent.putExtra(getString(R.string.first_player_for_intent), firstPlayer);
in comparison to the
intent.putExtra(MyClass.first_player_for_intent), firstPlayer);
If you should use constants, in what class should they be located?
I wouldn't use res/strings.xml to store constants. You might want to access their value even though you don't have a context. Also, your keys don't need to be localized. Regarding the place where you should store it, it is up to you, and imo, it is just a matter of taste. I usually avoid having a dedicated class just for constants, but I declare it where it imo belongs. For instance, if you have a class called Player, I would put all the constants Player related there.
strings.xml is there for a purpose and primary purpose of it is to support localization.
you should not be overloading this system with constants which are not relevant for localization.
As Blackbelt correctly said you may need to access your constants even without context so that's another reason.
why Google calls variables with the prefix "m" for example:
private int mSectionResourceId;
private int mTextResourceId;
I see it in all examples. But i not understand why they do it?
And now i have some example where it practic very good. If a called variabels without prefix i need write
public SimpleSectionedRecyclerViewAdapter(Context context, int sectionResourceId, int textResourceId,
RecyclerView.Adapter baseAdapter) {
this.sectionResourceId = sectionResourceId;
this.textResourceId = textResourceId;
but if i use prefix i can write
public SimpleSectionedRecyclerViewAdapter(Context context, int sectionResourceId, int textResourceId,
RecyclerView.Adapter baseAdapter) {
mSectionResourceId = sectionResourceId;
mTextResourceId = textResourceId;
I think it more readable. Who can explain to me the pros and cons of a prefix?
The variables starting with m are telling you they are variables in the scope of your class. Member of the class.
Link to Android Code Style Guide
The m just stands for 'Member'. It is simply declared that your Variable is a Class-Member.
It is more readable Code, because you know where Class Members got declared, so you can find it pretty fast. You don't need to write this, even if you don't prefix your Variables with an m.
In your Example, this only makes it more readable when there is no prefix-m. Another developer knows that it is a instance variable (member variable) and so declared on top or bottom of the class.
It is a prefix for class member variables. It's just a naming convention.
Mostly sure, taken from Hungarian Notation where similar prefix: m_ stands for exactly the same).
Referring to pros & cons:
Pros:
it allows to type fewer chars during programming,
programmers that are used to use Hungarian Notation may found it easier to follow the code.
Cons:
as the code changes very often, it is easy to forget about changing prefixes every time, when variable changes it's purpose (especially during prototyping),
it makes the code starts to smell bad,
Generally, it is some kind of reinventing the wheel. Java has this keyword that should be more than enough for accessing proper variable. If it's not, the code requires refactoring, maybe because of naming glitches or using too wide variable scopes.
Personally, I do not recommend to use Hungarian Notation (even the part of Android Code Style). We have great IDEs that increases the readability of the code.
There is an exception. The code, where Hungarian Notation (or more general, specific code style) was already been used. It is a matter of consistency.
The m is just a member variable. A class member if you will. Useable with constructors like WebView M WebView then later on you would use something like mWebView.loadurl("example.com"); it's just a placeholder for the variable you created. You don't have to add the member class variable as an m but it's more organized if you do
I just curious. There are 3 method:
1. getPreferenceManager().setSharedPreferencesName(String PrefName);
2. PreferenceManager.getDefaultSharedPreferences(Context context)
3. Context.getSharedPreferences (String name, int mode)
As I know, the third method is only used when the first method is used, right?
But with 3 method we also use addPreferencesFromResource(int resID);
so, what is the difference? When can we use one of these method?
Thanks!
Let's go one step at a time:
setSharedPreferencesName() is method that allows to set the name of the preference group for later use. This is helpful for example when using the helper class of
PreferencesActivity before loading a preferences from XML resource file by calling addPreferencesFromResource(). It is therefore not as common as the other 2 methods you mentioned above.
getDefaultSharedPreferences() uses a default name, usually stored as /data/data/com.package.name/shared_prefs/com.package.name_preferences.xml.
It is commonly used. Note that this default is set per application.
The alternative method - getSharedPreferences() requires to indicate a specific preference (file) name and an operation mode.
As appears also in another answer about shared preferences,
getDefaultSharedPreferences() in fact uses Context.getSharedPreferences, so the result is the same, but without the flexbility to split to multiple preference files, that is offered by getSharedPreferences(). Sharing the preferences between apps using
a MODE_WORLD_READABLE operation indicator is also something possible using getSharedPreferences(), but is rarely used.
IMHO, getDefaultSharedPreferences() can be safely used without going into the confusion of multiple preference file names that are prone to typos and confusion.
If someone knows of a good reason to use getSharedPreferences() and not getDefaultSharedPreferences(), please let me know by commenting here.
getDefaultSharedPreferences() uses a default preference-file name like "com.example.something_preferences". This default is set per application, so all activities in the same app context can access it easily as in the following example:
SharedPreferences spref = PreferenceManager.getDefaultSharedPreferences(this);
if (spref.contains("email")) {
String sEmailAddr = spref.getString("email", "");
}
The preferences are usually stored at /data/data/com.package.name/shared_prefs/com.package.name_preferences.xml
getSharedPreference is the best way because using getDefaultSharedPreferences has some flaws
Actualy getDefaultSharedPreferences doesn't work correct on some
devices when build with targer api 13
Starting app from shortcut and from menu gives me different
DefaultSharedPreferences. After removing DefaultSharedPreferences
from my code - it works perfect. I can't just say: people dont make
shrotcuts, so I had to change code
This link may also help
What is better approach of the following in designing an Android app
To place all the String constants in res/values/Strings.xml
or
Create a class like Constant.java where all Strings are public static final?
Choosing which one of them is more efficient?
I imagine a constants class would be more efficient.
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.
If I know a variable's pattern such as R.id.edit_x where x (1..N), how can I get a reference to a given EditText, like findViewByID(R.id.edit_1). Is there something like an "eval" function in Dalvik ? Thanks.
Try Java reflection. Discussion on retrieving static final fields via reflection is here - Accessing Java static final ivar value through reflection
hoha's answer is good. Another thing you can do is create a look-up table that maps 1..N to the resource IDs. (Presumably you know all the resource IDs ahead of time.)
maybe, you can check roboguice. it is a ioc framework for android and it's realy easy to use. i copy some code from the sample from the project to show how to use it:
public class AstroboyMasterConsole extends RoboActivity {
#InjectView(R.id.self_destruct) Button selfDestructButton;
#InjectView(R.id.say_text) EditText sayText;
#InjectView(R.id.brush_teeth) Button brushTeethButton;
#InjectView(tag="fightevil") Button fightEvilButton; // we can also use tags if we want
}
then you can you these injected variables in your code!