Is is possible to create an new local variable from value of another?
e.g. if value of var1 = "button1" can I construct a new local variable like button1type, ie.using the value of var1 to make part of the new variable
Like this?
String foo = "ohai_" + var1; // Would be "ohai_button1"
If you mean name the variable based on the value in var1? No, but you don't need to.
If you need to associate data based on a string (or other) value, consider using a map.
Related
I have declared a string in my strings.xml file , and using it in my activity as R.string.compose_title. (setting it as title i.e. setTitle(R.id.compose_title)). Now in some case I want to edit the string and then use it to set the title . How can I do this ?
P.S. I need to change value of a single string only , So declaring a new strings.xml for each case(which are variable depending upon the user) using localization seems to be a lil inefficient .
One thing what you have to understand here is that, when you provide a data as a Resource, it can't be modified during run time. For example, the drawables what you have in your drawable folder can't be modified at run time. To be precise, the "res" folder can't be modified programatically.
This applies to Strings.xml also, i.e "Values" folder. If at all you want a String which has to be modified at runtime, create a separate class and have your strings placed in this Class and access during run time. This is the best solution what I have found.
example howto:
how? by changing one variable reference to other reference
usage:
setRColor(pl.mylib.R.class,"endColor",pl.myapp.R.color.startColor);
// override app_name in lib R class
setRString(pl.mylib.R.class,"app_name",pl.myapp.R.string.app_name);
base methods:
public static void setRColor(Class rClass, String rFieldName, Object newValue) {
setR(rClass, "color", rFieldName, newValue);
}
public static void setRString(Class rClass, String rFieldName, Object newValue) {
setR(rClass, "string", rFieldName, newValue);
}
// AsciiStrings.STRING_DOLAR = "$";
public static void setR(Class rClass, String innerClassName, String rFieldName, Object newValue) {
setStatic(rClass.getName() + AsciiStrings.STRING_DOLAR + innerClassName, rFieldName, newValue);
}
helper methods :
public static boolean setStatic(String aClassName, String staticFieldName, Object toSet) {
try {
return setStatic(Class.forName(aClassName), staticFieldName, toSet);
} catch (ClassNotFoundException e) {
e.printStackTrace();
return false;
}
}
public static boolean setStatic(Class<?> aClass, String staticFieldName, Object toSet) {
try {
Field declaredField = aClass.getDeclaredField(staticFieldName);
declaredField.setAccessible(true);
declaredField.set(null, toSet);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
#bradenV2 My app is supporting many languages , so I wanted to take a
string from my strings.xml that's currently in use and change that ,
and then use that one – atuljangra Mar 12 '12 at 22:04
ps the above solution is good for example when u want to inject some data in already compiled lib/jar. But if u want localize strings just make folder under res per LANG CODE like values-CC where cc is lang code (values-de,values-cs) etc
then u have 2 choices:
"build in" system dependent language selection - based on device selected lang
via create resources for configuration - you decide which lang show
like this:
configuration = new Configuration(resources.getConfiguration());
configuration.setLocale(targetLocale);
String localized = Context.createConfigurationContext(configuration)
.getResources()
.getString(resourceId);
I don't think you can programmatically customize the R class as it is built by ADT automatically.
I had a situation like this, where one of my strings.xml values had some dynamic piece of it. I set up the strings.xml with a "replacement text" (something like %%REPLACEMENT_EMAIL%%), and when I wanted to use that string programatically, I retrieved the string value of the resource, and replaced instances of that replacement text with the dynamic value (e.g. input by the user).
To be honest, my app has not been localized yet, but I'm still attempting to follow best practices w.r.t. not hardcoding any strings.
Use SharedPreferences instead of a Java class. It will give you more versatility if you decide to take values from the outside (web). Filling Java class in runtime can be useless offline. In case of SharedPreferences you have to ensure they are loaded only once, during app's first start, and then updated only by manual request, as previous import will be used.
myActivity.getSharedPreferences("com.example.imported",0)
.edit()
.putString("The news",getTheNews())
.apply();
Maybe you want to "modify" the string.xml so when it is required by the activity again it uses the new value, for example to keep a new dynamic title after screen rotation.
First, you can't modify the resource. It's already compiled. You can't modify the R class (what for?) all it's atributes are "final".
So, for the example above you can use onSaveInstanceState() and onRestoreInstanceState() for those properties you wanna keep on display.
According to my knowledge, you can't change resource value(R class value) while app running. why don't try to store on shared preference? I recommend you to use shared preference
I used below method to get the key-value pairs from the API and storing it in HashMap globally. If the key value is not found in HashMap then I will search that key in strings.xml file. It will achieve the purpose of dynamically changing the value of key.
public String getAppropriateLangText(String key) {
String value = "";
try {
HashMap<String, String> HashMapLanguageData HashMapLanguageData = gv.getHashMapLanguageData();
value = HashMapLanguageData.get(key);//Fetching the value of key from API
if (value == null || value.length() == 0) { //If Key value not found, search in strings.xml file
String packageName = getPackageName();
int resId = getResources().getIdentifier(key, "string", packageName);
value = getString(resId);
}
} catch (Exception e) {
value = "";
}
return value;
}
String compBut1 = "D0", compBut2 = "D0", compBut3 = "D0", playaBut1 = "D0", playaBut2 = "D0", playaBut3 = "D0";
public void changeOver()
{
String[] set = {playaBut2, playaBut3, playaBut1};
int butPos = Arrays.asList(set).indexOf(positions[posOld]);
set[butPos] = positions[posNew];
}
What must i do to ensure that whenever the value of variables in the array set are changed the global variable also get changed. I can see in the debugger that when I am inside the method the value get changed but as soon as i go out the change is discarded.
String[] set = {playaBut2, playaBut3, playaBut1};
You think the above stores references to the respective strings so that whenever any of these strings is changed, the referenced string changes.
However, what it actually does is copies the values to new instances of String and makes an array of them. Java doesn't allow you to store references (pointers a la C/C++) for safety reasons.
What you should do is: make an array of the globally declared strings and change them directly inside your function.
String[] compBut={"D0","D0","D0"};
String[] playaBut={"D0","D0","D0"};
public void changeOver(){
int butPos = Arrays.asList(playaBut).indexOf(positions[posOld]);
playaBut[butPos] = positions[posNew];
}
I'm trying to create my own Preference in which I want to give the user the choice to select the new value or to reset to default.
Therefore I need to "store" two values in one preference.
I mean, I want to access the stored value and the default value (defined in XML) at the same time.
<my.custom.preference
myCustomAttribute="R.color.someColor"
android:defaultValue="#color/someColor"
android:key="myPref"
/>
In my code, I read the value like this:
String value = attrs.getAttributeValue(null, "myCustomAttribute");
The return value is "R.color.someColor".
So, I tried to get the R-reference of this string, but this is the point where I'm failing.
int neededValue = ???
At the moment, I use a really bad workaround.
I search the selected Preference by key and set neededValue programmatically like this:
switch(getKey()) {
case "firstCustomPreference":
neededColor = R.color.firstColor;
break;
case "secondCustomPreference":
neededColor = R.color.secondColor;
break;
}
This does work, but I really hope there is a cleaner way of doing this.
So my question is: Is there a way to get the int value from the string "R.color.someColor"? Alternatively, is it possible to access the default value?
"Is there a way to get the int value from the String "R.color.someColor"?"
int resourceId = getResources().getIdentifier("someColor", "color", getPackageName());
int color = getResources().getColor(resourceId);
I'm creating an app with Corona structured in Class and I have a problem when I want pass an array objects for create an object.
I have this:
main.lua
local SurpriseBoxClass = require("SurpriseBox")
local BoxClass = require("Box")
local box1 = BoxClass.new('palo', 'images/chestClose.gif', 'OPEN')
local box2 = BoxClass.new('moneda', 'images/chestClose.gif', 'OPEN')
boxes = { box1, box2 }
local game = SurpriseBoxClass.new(boxes)
SurpriseBox.lua
local SurpriseBox = {}
local SurpriseBox_mt = { __index = SurpriseBox }
function SurpriseBox.new(boxesAux)
local object = {
boxes = boxesAux
}
return setmetatable( object, SurpriseBox_mt )
end
The problem is when I want to print the content of array in a method of SurpriseBox, and the program said me that the array is nil if for example I do this:
print(boxes[0])
What can I do?
Thanks!
Lua tables are 1-based.
Try print(boxes[1], boxes[2]).
It will print the table id. If you need to print the contents of the table, you must iterate over its fields, or use a custom printer that does it for you (see "Print a table recursively").
Look at the function SupriseBox.new(boxesAux) (where I gather you desire to do the printing):
In object, you are associating the key "boxes" with the table boxesAux. This to access the contents of boxesAux via object you must go through the following process:
object["boxes"] or object.boxes will get you to boxesAux, to go into that you need the superscripting i.e [1]
print(object["boxes"][1]) --etc..
print(object.boxes[1]) --etc..
Note that, this will now give you box1. If you want to print a meaningful display of it's content (that is if the class isn't overloaded) you should use a pretty printing library.
I have a string where I have a value: 2,6. How can I change "," on "." I use x.replace(",", "."); but doesn't work. This is any other method to do that?
Try using:
x = x.replace(",",".");
In Java, Strings are immutable, so you will always get a new String from the operations. You have to store this new String, or your changes are lost. replace() returns a new String object, so you need to keep a reference to this new object. Your older String is not modified.
String is immutable it create the new object again after modifying in string. So You need to assign the result.
Do like this.
x= x.replace(",", ".");
Correct way is:
x = x.replace(",", ".");
String is immutable, it can't be changed. x.replace creates a new string