I have some messages being passed back from my server through php. The problem is that the messages are in English and if the user is using another language they will still get the message in English.
So I had an idea that maybe instead of passing back the message I would instead pass the String resource Id from the android app, that way the app will get the correct string id for their language. I will use this in a number of apps so I just want to know if the string id is guaranteed to be the same across different android projects?
No.
The string resource IDs are likely not even guaranteed to be the same between re-compilations of the same application (e.g. differences between versions of aapt).
Christopher is right, but you can pass a parameter to your server like http://example.com/script.php?lang=en or lang=fr ....
This way the php scripts can use this parameter to return messages in the relevant locale.
You can get the resource ID from a string:
int resID = getResources().getIdentifier("org.my.package:strings/my_string", null, null);
// or
int resID = getResources().getIdentifier("my_string", "strings", "org.my.package");
Related
I am developing a cross platform game for which I needs to generate unique identifier (User ID) for each user. I known some platform (Android or iOS) specific approaches to get device related identifiers but I am looking for a solution independent of the device identifiers.
User ID Requirements:
Independent of the device's platform
Offline implementation (no communication with any servers)
Without sign-up process
I have implemented one approach to create User IDs where I store the system time when the game was launched for the first time on the device.
I have following questions:
Are there any other approaches to generate User IDs (which will meet the above requirements)?
What are the common approaches to create unique identifiers with taking any information from the user?
Are there any third party plug-ins to implement User IDs?
I would appreciate any suggestions and thoughts on this topic.
EDIT:
There are lot of responses to use UUID/GUID. Generally, this approach looks fine but I am looking for a solution which can generate same User ID even if the user reinstall the game.
Have you looked at UUID from Java?
https://docs.oracle.com/javase/7/docs/api/java/util/UUID.html
EDIT: The following links might help using UUID for unique identifiers.
Best practices for permissions & Identifiers
Instance ID
When you say user id, are you talking about a public id such as an username, or a database id?
If you are talking about a database id, go for a GUID/UUID. T-sql for example have the NEWID() method that will return a GUID that doesn't exist in the database yet. I am sure that whichever database you go for you will find some way to use a GUID.
https://learn.microsoft.com/en-us/sql/t-sql/functions/newid-transact-sql
As per my opinion your System current time is the best method for generating Unique User Id.
For Android :
System.currentTimeMillis() returns you the unique 13 digit number which can be used as User Id.
But When you get current time in iOS then it is 10 digit number which generates. So you can multiply it by 1000 to make User Id platform Independent.
Happy Coding...
Assuming that your usernames are unique, you could simply takje the md5 hash of your usernames to get an unique ID (string). e.g. in php:
$userID = md5($username);
because m5 hash functions exist in nearly every programming language you should be able to use this ID on all possible plattforms.
And if you arer looking for a numeric ID, you even can calculate a qunique number from md5.
See represent md5-hash as an integer - stack question for more details
Just generate a long string of random characters. For example, generates a 10 long string of alphanumerics ...
private String GetId(){
String[] chars = {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","0","1","2","3","4","5","6","7","8","9"};
StringBuilder s = new StringBuilder(10);
for(int i = 0;i<10;i++){
int pos = (int) (Math.random() * 62);
String c = "";
if (pos > chars.length-1){
pos = pos - chars.length;
c = chars[pos].toUpperCase();
}else{
c = chars[pos];
}
s.append(c);
}
return s.toString();
}
In my app i want to be able to store resource id of some icons in database. I suppose it is not save to do, cause in the later stages (application upgrades) i may want to add new icons to the app, so all id's may change? What is the best practice to store resource in case i do not want to store icons as blobs?
As an example, let's say i have a game 1.0, where i let user to choose an avatar for his character from a list of avatars. I want to store this avatars id in DB and be sure that if i add more avatars in game 1.1 - user will still see his choice.
The best way (in my opinion) is to store the resource entry name.
String iconName = getResources().getResourceEntryName(R.drawable.your_icon);
So your SQLite database column where you want to store the icon will have type TEXT. You're right that storing resource IDs is a bad practice because they're recreated when you compile the app, so you can't rely on them not changing (I learned this the hard way, all my app's icons got messed up).
To get the resource ID from the String when you need it, call
int resID = getResources().getIdentifier(iconName, "drawable", getPackageName());
Note that both getResources() and getPackageName() are methods from Context, so you need to have reference to your application/activity Context to be able to call these methods.
I have 100 images in my application of different cities and I want to divide these pictures in different groups, lets say in evening, morning, sunny, raining etc…
We know that when we call an image from layout folder by calling R.layout.image_1, android generates integer number for each image
For example:
R.layout.image_1 (223344), R.layout.image_2 (556677),
R.layout.image_3 (778899),
I can create one table having evening, morning fields and I can assign group of pictures to each of them with integer IDs which are (223344,556677) and I can call evening or morning group and i can display all images related to these group.
My question is: Does Android generate same number every time. Are these numbers are fixed? When ever the application runs.
If its true then upper idea will work for me. If this idea is incorrect then kindly guide me what is the decent approach to handle hundreds of PNGs in application.
Those numbers are not fixed. R will be regenerated and can have completely different numbers if you change something. That is why when comparing ids, you compare by the name instead.
Eg instead of
if (i == 223344)
do
if (i == R.layout.image_1)
Since R.layout.image_1 references the integer id, the name won't change (unless you change the layout xml name.
If you want to get a resource id dynamically (by a string representing the name), you should have a look at this method - Resources#getIdentifier().
First of all we generally put images in the drawable folder.
Does Android generate same number every time?
No.
Are these numbers fixed whenever the application runs?
Yes.
In fact, once your project is built, the ids will remain the same for that same build.
In other words for a certain generated APK file, the ids won't change.
So how can you take advantage of that to group your resources?
You could have a static int array that holds the ids:
public static final int[] IMAGES_MORNING = {R.drawable.morning0, R.drawable.morning1, etc};
public static final int[] IMAGES_EVENING = {R.drawable.evening0, R.drawable.evening1, etc};
Although a more structured method would be to store them in a database on your app's first launch.
Or you could use what A--C suggests:
For example to get all the ids of morning images
for(int i = 0; i < numberOfMorningImages ; i++){
int id = getResources().getIdentifier("morning" + i, "drawable", getPackageName());
// do something with the id
}
No, there's no guarantee that integers will be the same every time, so the solution you've described won't work. Unfortunately, there's no proper way to group drawables inside the res/drawable folder. As a workaround, you can store them inside the assets folder, where you can group them as you like. However, Android won't be able to handle different resolutions this way. The choice is up to you. Hope this helps.
Why does this code trigger a force close in Android?
`score.setText(Integer.parseInt((String) score.getText())+1);`
score is a TextView, and I am simply increasing the number by 1. I have predefined a String resource to be the initial number in the score TextView.
I am quite frustrated.
First off you should try breaking down your code so you can actually see what is going on with it.
Instead of
score.setText(Integer.parseInt((String) score.getText())+1);
try
String tmp = score.getText().toString();
int score;
score = Integer.parseInt(tmp) + 1;
score.setText(String.valueOf(score));
EDIT: Upon further reading of the documentation, setText has several overloads, one of which DOES take an int, but it takes the int of a resource ID. My guess is that your score is not a valid resource ID, thus crashing your application.
public final void setText (int resid)
Oh and as far as the frequent FC's when beginning Android Dev, it happens to the best of us. The key is to learn WHY the FC's happen, and have a LOT of patience.
mostly u need to do this
score.setText(Integer.parseInt(score.getText().toString())+1);
coz.. getText() returns a Editable Object which cannot be parsed to Integer. So it give NumberFormat Exception.
AndMake sure to set TextView,s Text to an integer initially..
try this way
score.setText(String.valueOf(Integer.parseInt(score.getText().toString())+1));
as you can pass the integer value that's why getting force the application
TextEdit.setText takes a CharSequence as input.
You are supplying an integer through Integer.parseInt((String) score.getText())+1
See, if converting it back to string and using it in setText helps.
You can convert an integer to string using Integer.toString.
PS: I am new to java myself.
The compiler should have ideally caught this error.
It's possible java uses some implicit type conversions from string to int.
When changing the custom locale the label of the phone types change to the appropriate language. Does anybody know how to get the localized label of the phone types?
I pick a contact in my app to get its phone number and if there is more then one number I use an AlertDialog to let the user select the currect one. In this pick list, I want to show the label of the type, so it's easier for the user to select. Since they labels are somewhere in the Android system, it must be possible to get the localized label. Unfortunately, the Phone.LABEL is null when reading the phone number.
I know this is a bit old, but this:
Phone.getTypeLabel(this.getResources(), cursor.getInt(typeIdx), "");
worked for me
Yes, you can get localized phone type string with the code:
int phoneNumberType = (int)pCur.getInt(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
ContactsContract.CommonDataKinds.Phone.getTypeLabel(context.getResources(), phoneNumberType , "")
but for custom phone types you should cosider phone label, not only phone type:
String phoneLabel = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.LABEL));
Inferno's answer is a valid answer, and I was happy to find this answer because it was similar to what I was looking for. However, if you're dealing with phones installed with API Level 5 (Android 2.0) or newer, there is one small problem with this: android.R.array.phoneTypes only returns the list of phone types that were present prior to when ContactsContract class replaced the Contacts interface as of API Level 5. I verified the labels listed when creating a new contact on emulators running these Android versions (API Levels): 1.6 (4), 2.1-update 1 (7), and 2.2 (8).
When printed out, android.R.array.phoneTypes contains these valid phone types:
Home, Mobile, Work, Work Fax, Home Fax, Pager, Other, Custom
These are the valid phone types, present for phones with Android 2.0+ installed, that are missing from that same Array:
Callback, Car, Company Main, ISDN, Main, Other Fax, Radio, Telex, TTY TDD, Work Mobile, Work Pager, Assistant, MMS
Unfortunately, I have not been able to find something like android.R.array.phoneTypes that'll list all of these valid phone types for phones Android 2.0+. Has anyone come across such yet?
References
android.R.array.phoneTypes defined: http://developer.android.com/reference/android/R.array.html#phoneTypes
Note: I'm posting my other two reference links in separate answers, as I can't seem to post more than one hyperlink per post at this time.
i am using this piece of code
public void getPhoneType(){
int res;
for(int i=0;i<=20;i++){
res = ContactsContract.CommonDataKinds.Phone.getTypeLabelResource(i);
Log.d(TAG,"i: "+ i +" type: " + context.getString(res));
}
}
didn't found any place to get the actual count of valid types but http://developer.android.com/reference/android/provider/ContactsContract.CommonDataKinds.Phone.html#getTypeLabelResource%28int%29 says it will always give a valid res so, you can iterate until it start giving repeated values... to me after 20 gives me the custom res.