0

Is there a way i can create code build code by using Concatenation in Android studio/eclipse?

In other words i have 2 sets of strings one for each country i am dealing with ZA and KE. They have 2 different EULA's.

So i would like to pull the string related to the respective country.

String message = mContext.getString(R.string.eula_string_za);

above is an example of the output code. is there someway i can go about "creating" that based on If statements?

String str = "mContext.getString(R.string.eula_string_";
if (something = "ZA") {
    str += "za);";
} else {
    str += "ke);";
}

so if the country selected is ZA then the output code should be

mContext.getString(R.string.eula_string_za);

and if its KE it should be

mContext.getString(R.string.eula_string_ke);

and then the result will then pull the correct string from strings.xml?

Ori Lentz
  • 3,668
  • 6
  • 22
  • 28
Stillie
  • 2,647
  • 6
  • 28
  • 50

2 Answers2

5

Java is a compiled code, not an executed one,you can't write code this way like in an interpreted language.

The best way to manage different languages in android is to use a string.xml file for each language. Take a look at this tutorial, it will help you a lot :

Supporting different languages in android

hkN
  • 135
  • 4
2

If you want to go this route you could try to use reflection. Have a look at Class.getField(…) if you want to use reflection.

Instead of first building a code string using a if statement you can also use the same if statement to find the correct string:

String str;
if (something.equals("ZA")) {
    str = mContext.getString(R.string.eula_string_za);
} else {
    str = mContext.getString(R.string.eula_string_ke);
}

Note that your condition something = "ZA" does not do what you think it does: It assigns something the string "ZA" and then evaluates itself to "ZA", so this would not even compile. The correct way would be something == "ZA", but even this does not work in the general case. You need to use String.equals(…). Some even argue you should use it the other way around (i.e. "ZA".equals(something)) to avoid a NullPointerException

Another possibility would be to first build a Map from county to the corresponding string ID for all the EULAs you have and then asking the Map to return the correct one.

But probably the cleanest solution would be to use Androids built in mechanism, as hkN suggests.

Community
  • 1
  • 1
siegi
  • 5,646
  • 2
  • 30
  • 42
  • thanks, its not based on languages, its based on the countries "policies" that the terms and conditions are different(dont know the legality of it, i just make the app lol) – Stillie Apr 30 '15 at 11:23