Handle soft labels in Android - android

I am building an application and use labels in the following areas.
1. Component Names (TextView, Buttons etc)
2. Buttons in alert boxes
3. Parameters to AsyncTask
4. Key names in Intent extras
5. Log tags
I have got strings.xml files to store and use labels. I am using using it for category 1. What do you think is the best option for others?
res/strings.xml or
Constants class ?

I'll suggest to you what I normally do:
For everything that the user will read on the screen or be referenced in anyway from a XML layout, use strings.xml. I reckon that includes your 1 and 2. But remember that for AlertDialogues you can also use android.R.string.ok or android.R.string.cancel, etc; that will vary from use to use.
Also for project config values, or API keys, you could have a config.xml with String, Integers, etc. Something that makes easy to later on change those values without diving into the code.
For AsyncTask, it varies a lot of what work it is doing, but usually a network, DB or disk operation, and I try to include private static final String URL_PT1 = "http://..."; etc, in the classes themselves, as they are the only interested in knowing that address (or DB columns, or file prefix)
For key names (both in Intent and Fragment arguments) I use private static final String KEY_VALUE = "renjith.Key.MyClassName.VALUE"; and then create a public static Bundle getIntentExtras(String value) inside that class that will properly allocate the value in the extra. That's because only that one class needs to know about it's KEY values, there's no reason to make those public accessible, that will just create errors for outside classes doing it wrong.
For Logs (5), create on every class a private static final String TAG = "Renjith.ThisClassName"; (and for Fragments make the TAG public to be used in transactions). That way you can create a filter in LogCat Renjith.* and you can easily identify from where this log is coming from
edit:
For sharedpreferences it depends:
for GlobalSharedPreferences I would create one class to handle them with static set/get methods that must receive Context and all keys private static inside that class.
For local shared preferences (that only one class is interested in saving/retrieving) I would handle in a SharedPreferences file with the same name as that class and all the keys as private static inside that one class.
Again, same philosophy, only the classes that really need to know about those details will know about them, and abstracting to the rest of the classes with direct method calls.

Related

A refernce sheet for android project

I have a NFC tag and I have to read from it a text, and save this text some where to use the parameters in it in many activities and fragments.
this parameters I should be able to delete or overwrite it when a user decide to exit the program or to read another tag.
I didn't like the idea to transfer this parameters over the activities since they are constant in the whole session for example the ID number of the tag and the manufacturer of it.
I thought also to creat a file in Assets and read it every time, but I thought there should be better way to solve this problem.
There are several ways to how you make the values accessible throughout the project.
Using Shared Preferences:
You can use shared preferences, where you can create variables for your fixed values such as TAG_ID and MANUFACTURER_ID. Every time you tap a new card you can update them, or anytime you expect them to be changed.
Using a Model Class:
You can also create a Model Class (May be Singleton as well) which holds the TAG_ID and MANUFACTURER_ID. Initialize the object of this model class every time there is new Tag tapped. You can also access/change them anytime using getters and setters.
Using Static variables:
You can define static variables to store your desired values and you can simply access them wherever and whenever you want to. This will workout only with less numbers of variables. Increased static variables could affect the performance.

How should I store common strings?

I can store them in res/strings
<resources>
<string name="str1">app</string>
</resources>
And I can store them in static const
public static final string str1 = "app"
Which one is better?
I mean that which one will use more memory and which one will make package larger.
If you have to change some text in your app's view, then you don't have to find where you have written that text. You simply go to the strings.xml in res folder and can change the string. For that reason, the first option will always be the better option.
If you want a string that will be used as a key in your app then you can store it in a static constant variable. Like: If you want to pass data through intent or in any other way, at that time you have to pass a key. That key will be a string and can be stored in a static constant variable.
it's really depend if you treat strings as constants or not.
If you string are constants (e.g. string that will be sent as key of intent) then you can either create some Constants class or define it as a constant in your activity/fragment class. If those string are texts that will be displayed on your application UI then they should be defined as resources in your application.
BTW all the resources string can be localized to different languages
If you need more info or examples please let me know.
The package size:
I believe that "Ran Hassid"'s comment describes well about the package size.
Memory usage:
Just create an android apk file with some static final strings and then decompile it. You will see that the variable has no initial value in the compiled version and the value is replaced in all references!
For example check this sample from my decompiled apk which is also obfusicated by proguard:
public static String f10850f;
...
...
...
hashMap.put(C1554f.m14687a("\u0014]SCVQ^V"), str);
here is the actual code I have written:
public static String packageName="\u0014]SCVQ^V";
...
...
...
hashMap.put(EncryptorClass.decrypt(packageName), str);
In this case, the static final String variable in my written code has value of "\u0014]SCVQ^V" but it is not used in run-time and just copy/pasted in related pieces of code.
So using static final String variables needs no memory because variable has no initial value.
Have a look at android docs about using static final variables
Also take a look at this post regarding memory of variables with no value
Overally, I use static final variables and string resources for different purposes like code encryption, language support and whether I want to access the variable using a Context or not.

How to create a string resource programatically

I am using WebTrends analytics in my app.
(Ref-http://help.webtrends.com/en/android/)
The WebTrends APIs are written in such a way that the initialization happens ONLY from resources file. They provide webtrends.xml with the sdk and all the parameters are set from the values from this xml file.
Now the problem is I have to set a couple of values dynamically based on our server feed.
Here I have only two choices:
(1) Set WebTrends initialization values in the code which looks impossible from WebTrends SDK. Neither the member variables are exposed outside the library nor there are any setters/methods to set the initialization params.
(2) Create resources from webtrends.xml dynamically or at least set the values for resources dynamically which also seems impossible.
Can anyone please suggest the way out of this deadlock?
You cannot do that. When you add a string resource an automatic entry is made for the resource in R.java file at compile time.
Example:
public static final class string
{
public static final int app_name=0x7f040000;
}
where app_name is the name of the string resource. So, it is not possible.

How to set application independent parameters like server addedress in android

I need a solution for the really common but important issue that i am thinking of.
I have created application in which i have hard coded my server address in /res/values/strings.xml file. Suppose if my server address changes run-time due to some reasons, then i have to make changes in the file and then i have to recompile it.
So is there any way that i put my server address out of my application.. So we do not have to recomplie the application. Instead of it, it will read new server address from out side and resume its normal work...
Any type of related suggestions,links,blogs appreciated..
While I am making apps in Android , I mostly create a Utility class e.g. Constants.java , Utils.java etc. In these classes, I put all the constant numerical and String values like this:
public static String ip="74.117.153.111";
public static final String LOGIN_TOKEN_URL = "http://"+ ip + "/api/getLoginToken";
public static final String USERNAME_PARAM = "username";
public static final String PASSWORD_FIELD_EMPTY_ERROR = "Please enter password";
public static final int GRID_ICON_COUNT = 4;
public static final String FACEBOOK_KEY = "16411636362877862";
These are some type of constants which we generally use here and there. So I put them into a different dedicated class. So now when I need their value somewhere, I get it like this:
params.put(Constants.USERNAME_PARAM, username);
fbRocket = new FBRocket(this, Constants.APP_NAME,Constants.FACEBOOK_KEY);
The benefit of this approach is that if I have to change a value later on which is being used at lot of places , then I don't have to change it everywhere. I will just change the value in Constants.java and this change will replicate in the whole app.
Utils.showErrorMessage(this, Constants.PASSWORD_FIELD_EMPTY_ERROR, Constants.TOAST_VISIBLE_SHORT);
I got the answer by reading this blog.
Which says you should use shard preferences with the activity extending PreferenceActivity.
Here you can set your server address and all the dynamic stuff that will change by the time. So that you will not have to recompile the apk. Just change the settings in shared preferences.
Read this important bog that all app developer wants to know it..

How can I initialize the Sender ID for Android C2DM without using a hard-coded value in a static variable?

I'm adding Android C2DM to a Android library project. I started with the com.google.android.c2dm package that is included with JumpNote and Chrome To Phone. In order to use this package, you have to subclass the C2DMBaseReceiver service which takes the Sender Id as an argument to it's constructor. In JumpNote, this argument is initialized using a hard-coded static variable in a config class. However, in an Android library project, which may be used by multiple concurrently running apps I don't think I can use a hard-coded static variable (that is, I believe it could lead to problems when/if multiple apps are trying to access/modify the static variable).
I tried to think of a way to initialize the Sender Id without using a static variable and am stumped so far.
The obvious solution would be to use the Manifest or a Resource string or a combination of the 2. For example, in strings.xml I might have a "ac2dmSender" string, which is accessed in a meta-data child of the C2DMReceiver service declaration in the manifest. However, it seems that you cannot get a reference to the PackageManager or ResourceManager from a static context, so there is no way for me to then retrieve the meta data in such a way as to pass it in to the constructor of C2DMBaseReceiver.
Please let me know that I'm missing something! Thanks in advance.
We had same problem.
We solved it by using properties file under the assets folder.
Can load the properties staticly by using static configuration helper class.
On the first time the application is loaded can get the properties file using the Application context.
for example:
1. init the static configuration
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myConfig = new WLConfig(getApplication());
}
Then use in the configuration class:
myProperties.load(context.getAssets().open("myclient.properties"));
And get the sender email:
return myProperties.getProperty(WL_C2DM_SENDER)
However, in an Android library project, which may be used by multiple concurrently running apps I don't think I can use a hard-coded static variable (that is, I believe it could lead to problems when/if multiple apps are trying to access/modify the static variable).
"Multiple concurrently running apps" each have their own copy of the static variable, since each runs in its own process.

Categories

Resources