I'm sure there's a better way to do this but I'm rather new to programming altogether so I apologize in advance for my noobiness.
Here's my problem:
I have an ArrayList filled with the name parameters of my strings in strings.xml, what I'm attempting to do is fill a TextView with .setText() utilizing a resource ID that is dynamically created from a part of my array. For example...
ArrayList<String> options = new ArrayList<String>();
options.add("bacon");
options.add("ham");
//R.id.option1 is in my layout and R.string.bacon is in my strings.xml
TextView option1 = (TextView)findViewById(R.id.option1);
option1.setText(R.string.(options.get(0)));
This isn't my complete code obviously. It's just a example faced by the same problem.
Any ideas?
Thanks in advance!
As an idea, instead of a String array of names, you could have an int array of resource ids:
ArrayList<Integer> options = new ArrayList<Integer>();
options.add(R.string.bacon);
options.add(R.string.ham);
//R.id.option1 is in my layout and R.string.bacon is in my strings.xml
TextView option1 = (TextView)findViewById(R.id.option1);
option1.setText(options.get(0));
It sounds like you want to look-up the resource id by name so you can use it in calls that expect the integer id (e.g. in findViewById()):
Resources.getIdentifier()
public int getIdentifier (String name, String defType, String defPackage)
Since: API Level 1
Return a resource identifier for the given resource name. A fully qualified resource name is of the form "package:type/entry". The first two components (package and type) are optional if defType and defPackage, respectively, are specified here.
Note: use of this function is discouraged. It is much more efficient to retrieve resources by identifier than by name.
Examples:
String name = "bacon";
int id = resources.getIdentifier(name, "string", "com.package");
if (id == 0) {
Log.e(TAG, "Lookup id for resource '"+name+"' failed";
// graceful error handling code here
}
or
String fullyQualifiedResourceName = "com.package:string/bacon";
int id = resources.getIdentifier(title, null, null);
if (id == 0) {
Log.e(TAG, "Lookup id for resource '"+fullyQualifiedResourceName+"' failed";
// graceful error handling code here
}
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;
}
I have this piece of data (this is just one part of one line of the whole file):
000000055555444444******4444 YY
I implemented this CSV config file to be able to read each part of the data and parse it:
128-12,140-22,YY
The first pair (128-12) represent at what position in the line to start reading and then the amount of characters to read, that first pair is for the account number.
The second pair if for the card number.
And the thir parameter is for the registry name.
Anyways, what I do is String.split(","), and then assign the array[0] as the account number and so on.
But I want to change that CSV config file to a Property file, but I'm not sure of how to implement that solution, if I use a Properties file I'd have to add a bunch of if/then in order to properly map my values, here's what I'm thinking of doing:
Property cfg = new Property();
cfg.put("fieldName", "accountNumber");
cfg.put("startPosition", "128");
cfg.put("length", "12");
But I'd have to say if("fieldName".equals("accountNumber")) then assign accountNumber; is there a way to implement this in such a way that I could avoid implementing all this decisions? right now with my solution I don't have to use ifs, I only say accountNumber = array[0]; and that's it, but I don't think that's a good solution and I think that using Property would be more elegant or efficient
EDIT:
This probably needs some more clarification, this data I'm showing is part of a parsing program that I'm currently doing for a client; the data holds information for many many of their customers and I have to parse a huge mess of data that I receive from them, into something more readable in order to convert it to a PDF file, so far the program is under production but I'm trying to refactor it a little bit. All the customer's information is saved into different Registry classes, each class having it's own set of fields with unique information, lets say that this is what RegistryYY would look like:
class RegistryYY extends Registry{
String name;
String lastName;
PhysicalAddress address;
public RegistryYY(String dataFromFile) {
}
}
I want to implement the Property solution, because in that way, I could make the Property for parsing the file, or interpreting the data correctly to be owned by each Registry class, I mean, a Registry should know what data it needs from the data received from the file right?, I think that if I do it that way, I could make each Registry an Observer and they would decide if the current line read from the file belongs to them by checking the registry name stored in the current line and then they'd return an initialized Registry to the calling object which only cares about receiving and storing a Registry class.
EDIT 2:
I created this function to return the value stored in each line's position:
public static String getField(String fieldParams, String rawData){
// splits the field
String[] fields = fieldParams.split("-");
int fieldStart = Integer.parseInt(fields[0]); // get initial position of the field
int fieldLen = Integer.parseInt(fields[1]); // get length of field
// gets field value
String fieldValue = FieldParser.getStringValue(rawData, fieldStart, fieldLen);
return fieldValue;
}
Which works with the CSV file, I'd like to change the implementation to work with the Property file instead.
Is there any reason why you need to have the record layout exposed to the outside world ? does it need to be configurable ?
I think your proposed approached of using the Property file is better than your current approach of using the CSV file since it is more descriptive and meaningful. I would just add a "type" attribute to your Property definition as well to enforce your conversion i.e. for Numeric/String/Date/Boolean.
I wouldnt use an "if" statement to process your property file. You can load all the properties into an Array at the beginning and then iterate around the array for each line of your data file and process that section accordingly something like pseudo code below,
for each loop of data-file{
SomeClass myClass = myClassBuilder(data-file-line)
}
myClassBuilder SomeClass (String data-file-line){
Map<column, value> result = new HashMap<>
for each attribute of property-file-list{
switch attribute_type {
Integer:
result.put(fieldname, makeInteger(data-file-line, property_attribute)
Date:
result.put(fieldname, makeDate(data-file-line, property_attribute)
Boolean :
result.put(fieldname, makeBoolean(data-file-line, property_attribute)
String :
result.put(fieldname, makeBoolean(data-file-line, property_attribute)
------- etc
}
}
return new SomeClass(result)
}
}
If your record layout doesnt need to be configurable then you could do all the conversion inside your Java application only and not even use a Property file.
If you could get your data in XML format then you could use the JAXB framework and simply have your data definition in an XML file.
First of all, thanks to the guys who helped me, #robbie70, #RC. and #VinceEmigh.
I used YAML to parse a file called "test.yml" with the following information in it:
statement:
- fieldName: accountNumber
startPosition: 128
length: 12
- fieldName: cardNumber
startPosition: 140
length: 22
- fieldName: registryName
startPosition: 162
length: 2
This is what I made:
// Start of main
String fileValue = "0222000000002222F 00000000000111110001000000099999444444******4444 YY";
YamlReader reader = new YamlReader(new FileReader("test.yml"));
Object object = reader.read();
System.out.println(object);
Map map = (Map) object;
List list = (List) map.get("statement");
for(int i = 0; i < list.size(); i++) {
Map map2 = (Map) list.get(i);
System.out.println("Value: " + foo(map2, fileValue));
}
}
// End of main
public static String foo(Map map, String source) {
int startPos = Integer.parseInt((String) map.get("startPosition"));
int length = Integer.parseInt((String) map.get("length"));
return getField(startPos, length, source);
}
public static String getField(int start, int length, String source) {
return source.substring(start, start+length);
}
It correctly displays the output:
Value: 000000099999
Value: 444444******4444
Value: YY
I know that maybe the config file has some lists and other unnecessary values and what nots, and that maybe the program needs a little improvement, but I think that I can take it from here and implement what I had in mind.
EDIT:
I made this other one, using Apache Commons, this is what I have in the configuration property file:
#properties defining the statement file
#properties for account number
statement.accountNumber.startPosition = 128
statement.accountNumber.length = 12
statement.account.rules = ${statement.accountNumber.startPosition} ${statement.accountNumber.length}
#properties for card number
statement.cardNumber.startPosition = 140
statement.cardNumber.length = 22
statement.card.rules = ${statement.cardNumber.startPosition} ${statement.cardNumber.length}
#properties for registry name
statement.registryName.startPosition = 162
statement.registryName.length = 2
statement.registry.rules = ${statement.registryName.startPosition} ${statement.registryName.length}
And this is how I read it:
// Inside Main
String valorLeido = "0713000000007451D 00000000000111110001000000099999444444******4444 YY";
Parameters params = new Parameters();
FileBasedConfigurationBuilder<FileBasedConfiguration> builder =
new FileBasedConfigurationBuilder<FileBasedConfiguration>(PropertiesConfiguration.class)
.configure(params.properties()
.setFileName("config.properties"));
try {
Configuration config = builder.getConfiguration();
Iterator<String> keys = config.getKeys();
String account = getValue(getRules(config, "statement.account.rules"), valorLeido);
String cardNumber = getValue(getRules(config, "statement.card.rules"), valorLeido);
String registryName = getValue(getRules(config, "statement.registry.rules"), valorLeido);
} catch (org.apache.commons.configuration2.ex.ConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// End of Main
public static String getRules(Configuration config, String rules) {
return config.getString(rules);
}
public static String getValue(String rules, String source) {
String[] tokens = rules.split(" ");
int startPos = Integer.parseInt(tokens[0]);
int length = Integer.parseInt(tokens[1]);
return getField(startPos, length, source);
}
I'm not entirely sure, I think that with the YAML file it looks simpler, but I really like the control I get with the Apache Commons Config, since I can pass around the Configuration object to each registry, and the registry knows what "rules" it wants to get, let's say that the Registry class only cares about "statement.registry.rules" and that's it, with the YAML option I'm not entirely sure of how to do that yet, maybe I'll need to experiment with both options a little bit more, but I like where this is going.
PS:
That weird value I used in fileValue is what I'm dealing with, now add nearly 1,000 characters to the length of the line and you'll understand why I want to have a config file for parsing it (don't ask why....clients be crazy)
I am trying to get the file names of all the audio files but I am getting same file names for multiple songs
1.I cannot use DISTINCT key word as I am getting the file names from DATA .
2.I am using the Mediastore.Files So the select it takes MEDIA_TYPE so this way is also not possible .
3 .I want to get the Parent value as distinct not the repeating value .
So the only way is by doing in java .I followed the method given here but I am not able to set
Here is a piece of my code
if (audioCursor.moveToFirst()) {
do {
int filetitle = audioCursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.TITLE);
int file_id = audioCursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns._ID);
int fileparent = audioCursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.PARENT);
int filedata = audioCursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.DATA);
Mediafileinfo info = new Mediafileinfo();
info.setData(new File(new File(audioCursor.getString(filedata)).getParent()).getName());
info.setTitle(audioCursor.getString(filetitle));
info.set_id(audioCursor.getString(file_id));
info.setParent(audioCursor.getString(fileparent));
audioList.add(info);
} while (audioCursor.moveToNext());
}
How I can get the non repeating elements?? For more info mediastore.file
I am adding the data in Mediafileinfo class which contain getter and setter.
I want to get the Parent value as distinct not the repeating value .
Alright, you could use a HashSet<String> to maintain a list of seen MediaStore.Files.FileColumns.PARENT values.
Not sure what was wrong with the SQL approach, though.
HashSet<String> seenParents = new HashSet<String>();
if (audioCursor.moveToFirst()) {
final int fileparent = audioCursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.PARENT);
do {
String parent = audioCursor.getString(fileparent);
Mediafileinfo info = new Mediafileinfo();
// bla...
info.setParent(parent);
if (!seenParents.contains(parent)) { // prevents dups
seenParents.add(parent);
audioList.add(info);
}
// end loop
I'm creating an app and I wanted to get the value of an item in strings.xml but without using the R.string method.
Is this possible?
Edit:
I'll explain what the app does.
Basically, there's a word, let's call it "Rose", Rose can mean "Flower" or "First name", since it has two meanings, when the users chooses one of the two meanings, the app displays an explanation for the selected meaning.
I can't use R.string.stringName because I made a db that stores the relation between the name and the meaning and the correct explanation.
I'm sorry if it's not clear enough, I really don't know how to explain it.
The only reason why you would do that is if you are developing a library and don't have direct access to R class of the end app. In that case you should use something like this
private String getSomeString() {
try {
return getContext().getResources().getString(getContext().getResources().getIdentifier("some_string_identifier", "string", getContext().getPackageName()));
} catch (Exception e) {
// Not found, use a default
return "1234567";
}
}
If i understood you correctly, you can just simply use :
private String getStringResourceByName(String aString) {
String packageName = getPackageName();
int resId = getResources().getIdentifier(aString, "string", packageName);
return getString(resId);
}
To get string by it's name, and not R.string
private int info = 1;
public void nextStep(View view)
{
TextView textInfo = (TextView) findViewById(R.id.textInfo);
textInfo.setText(R.string.info1);
info++;
}
When one button is clicked, method nextStep is called. And every time a button clicked, I want to show different info, first time it's info1 string, next time it's info2 string and etc. from strings.xml. I would like to do something like that:
private int info = 1;
public void nextStep(View view)
{
TextView textInfo = (TextView) findViewById(R.id.textInfo);
textInfo.setText(R.string.info + info);
info++;
}
Of course, it's not possible. What should I do? I really don't want to write a big if/else or switch statement. Thanks.
Of course, it's not possible.
Actually, it is. You can use getIdentifier to do this:
private int info = 1;
public void nextStep(View view)
{
TextView textInfo = (TextView) findViewById(R.id.textInfo);
int myStrId = textInfo.getContext().getResources().getIdentifier("info"+info, "string", textInfo.getContext().getPackageName());
textInfo.setText(myStrId);
info++;
}
getIdentifer() is a way to fetch resource IDs that are stored in R if you don't know the exact name. While it isn't the most efficient method in the world, it suffices in situations where referencing R (such as your situation) is not possible.
The method returns the same ID that R would; that is, getIdentifier("info1", "id", ...); is the same as R.id.info1, since R is just a compiled version of it. This method also works in the event that you are unsure if an ID exists (such as from an external library) but need to reference it anyway.
Use an array of String or better a List<String> such as an ArrayList<String> and fill it with the Strings from the XML. Then you can use the get(int index) method to get the ith String in the list.
If you are using JAXB to unmarshall your XML, you can have it set up to create your List for you without much fuss.