Can't get localized strings from xml files correctly - java

I've been racking my head with this...
I've got a localized strings.xml file in a values-en folder with this example string:
#string/my_string
The string has the following text stored in English: "My String"
When accessing the localized string via a layout, it works fine.
When I try to change it in code, that's where I get problems.
I store the string into an array of strings for later use. The 'context' is passed from my activity to a data class and used with this line of code:
dataStrings = new String[] { (String) context.getResources().getString(R.string.my_string) };
Later, I try to display this string, like so:
buttons[0].setText(dataStrings[0]);
It displays:
#string/my_string
How do I get it to display the string without '#string/', the proper localized string?

You can run getString() directly on the Context object; you don't need to run getResources(). However, this should do the same thing as you're currently doing so I don't think that's the source of your problem.
The first thing to confirm is that what you think is happening is happening. Either use the debugger to check that buttons[0] contains "#string/my_string" or try calling setText() with a hard-coded value to make sure the text is actually being updated on the correct button - e.g. buttons[0].setText("StackOverflow!");

Related

How to make the Java to call a String from a XML file(In Android Studio)

I have this code and I will like to make it multi language app. What I want is to use the Strings from the Strings.xml file. How can i change "Colombian Peso" to String.
placeHolderData.add(new ExchangeListData("COP","Colombian Peso",R.drawable.colombia,time,"1"));
String string = getString(R.string.hello); // change hello to the right identifier
// then use it in your call
placeHolderData.add(new ExchangeListData("COP", string, R.drawable.colombia, time, "1"));
More info: https://developer.android.com/guide/topics/resources/string-resource#java
You can always change the R.string.hello identifier to the right language, i.e. R.string.es_peso, based on the user locale, etc.
Try this
String string = getResources().getString(R.string.hello);
Or
String string = getString(R.string.hello);
to get String from String.xml & add it to your desirable place
placeHolderData.add(new ExchangeListData("COP",string,R.drawable.colombia,time,"1"));

How to change this text to string to pass it to strings translation

I asked someone to developp an android app for me, but forgot to tell him to make the translation for me. I found how on google, by creating multiple string file in the values folder and translate almost all the app.
My problem is some text is written in the java folder. I made string for some but for others I can't. I tried using R.string.txt or #string/txt but it's not working.
If you could help with those codes I would apreciate it.
1- in the first code the text I want to add as string is [débit à passer] & [gouttes/min]
final TextView txt = (TextView) dialogView.findViewById(R.id.text_result);
String dose_qunt="Débit à passer " + "="+dose+" "+"gouttes/min";
2- for the second text: [please enter volume] & [please enter time]
public void onClick(View view) {
hideKeyboard(this);
if(view==btn_min){
if(edt_vol.getText().toString().isEmpty() ){
edt_vol.setError("please enter volume");
}
else if(edt_time.getText().toString().isEmpty()){
edt_time.setError("please enter time");
}
Cordialy
What you have here is a bad practice called "hardcoded strings".
Any strings that are shown to the user really should not be written in the Java source code.
That said, to properly correct such a problem, you need some understanding of Java and Android programming.
I can fix your specific examples with some guesswork, but if there are other such strings in your app, they may need a different solution.
It would really be better for you to ask the person who wrote the app to fix this.
That said, here how it should look:
1. Loading a string with parameters:
<string name="dose">"Débit à passer = %d gouttes/min"</string>
Notice %d is a placeholder for a value supplied when the app runs.
In this example the value can only be an integer. If you need different kind of parameter, like a decimal number, there is a list of placeholders here.
And this is how you load it:
int dose = 10; //just an example
final TextView txt = (TextView) dialogView.findViewById(R.id.text_result);
txt.setText(getString(R.string.dose, dose));
The second case is almost identical, except you do not need a parameter:
please enter volume
And the code will look like this:
if(edt_vol.getText().toString().isEmpty() ){
edt_vol.setError(getString(R.string.volume_error));
}
R.string.nameOfString gives the id of the string.
What you need is to call getString and pass the id:
getString(R.string.some_text);
You have to write this strings in values/string.xml in each language string file:
<string name="debit">Débit à passer </string>
<string name="gouttes">gouttes/min</string>
And later you can use them as:
String dose_qunt=getString(R.string.debit) + "="+dose+" "+getString(R.string.gouttes);
(for example)
If it dosen't works, write:
String dose_qunt= getApplicationContext().getString(R.string.debit) + "="+dose+" "+getApplicationContext().(R.string.gouttes);
And simillar for the second texts.

Replace tags in a word file

I've some tags in a word file which looks like <tag>.
Now I get the content of the Word file with docx4j and loop through every line and search for this tag. When I find one, then i replace it with a String. But this code i tried doesn't work and now i really don't know how i can realise it!
Here's the code i've already tried:
WordprocessingMLPackage wpml = WordprocessingMLPackage.load(new File(path));
MainDocumentPart mdp = wpml.getMainDocumentPart();
List<Object> content = mdp.getContent();
String line;
for (Object object : content) {
line = object.toString();
if (line.contains("<tag>")) {
line.replace("<tag>", "<newTag>");
}
}
Any tips or solutions how i can achieve it?
One of your problems is that you modify String line which has no effect on anything. line.replace("<tag>", "<newTag>"); result of this operation is ignored. you would definitely want to do sth with that, right?
Also, if object in your loop is not an instaneOf String, then line and object are pointing to different objects.
You need to modify contents but not the way you're doing this. Please read getting started
Also there are lots of examples (sample code) in source code download section
If you have any concrete problems after reading the getting started, we'll be happy to help you.
The things in your List will be org.docx4j.wml.P (paragraphs), or Tbl (tables) or other block level content.
Paragraphs contain runs, which in turn contain the actual text.
For the suggested way of doing what you want to do, see the VariableReplace sample.
Better yet, consider content control data binding.
Otherwise, if you want to roll your own approach, see the Getting Started guide for how to traverse, or use JAXB-level XPath.
First you should use replaceAll() instead of replace().
Then you should store this String into an object you can serialize back after modification to the Word file.
Furthermore I think that it would also be good to handle closing tags (if there some) ...
String (line) is immutable, therefore replace("<tag>", "<newTag>") does not modify your line it creates a new modified one.
Your code shoudl do something like this:
for (Object object : content) {
line = object.toString();
if (line.contains("<tag>")) {
line= line.replaceAll("<tag>", "<newTag>");
}
writeLineToNewFile(line);
}
or shorter:
for (Object object : content) {
writeLineToNewFile(object.toString().replace("<tag>", "<newTag>");
}

Java WebDriver Copy text Issue

Good Afternoon,
So I am trying to Copy some text from a field so I can paste it somewhere else in my test.
public static void validateTestCaseCreated(){
driver.findElement(By.xpath("//*[#id='mainForm:testTitle']")).click();
Action builder;
Actions copy = new Actions(driver);
copy.sendKeys(Keys.CONTROL + "a");
copy.sendKeys(Keys.CONTROL + "c");
builder = copy.build();
builder.perform();
The problem when it reaches line 6 it only sends c, it ignores the CONTROL. So my end result is not copying the text but highlighting the text then entering c.
You could just copy the value from the text field into a variable and store it for use later.
Pull it from the page using your code along with the get attribute method.
String valueInField = driver.findElement(By.xpath("//*[#id='mainForm:testTitle']")).getAttribute("value");
That will grab the text from the field and put it into the variable for later use.
I'm not sure if this is doing fully what you are trying to do, seeing as you are trying to do a crtl+c, but this method is how to grab text using webdriver.
If your field is an input element, maybe you can do something like this instead:
driver.findElement(By.xpath("//*[#id='mainForm:testTitle']")).click().get_attribute("value");

Passing Jackjson JSON object from JSP to JavaScript function

I have a JSON String stored in a database. In one of my JSP pages, I retrieve this string, and I want to be able to pass the String or the JSON object into Javascript function. The function is simply this for test purposes
function test(h){
alert(h);
}
Now I can retrieve the JSON string from the database fine, I have printed it out to the screen to ensure that it is getting it, however when I pass it in like this
<input type="button"
name="setFontButton"
value="Set"
class="form_btn_primary"
onclick="test('<%=theJSON%>'); return false;"/>
Nothing happens. I used firebug to check what was wrong, and it says there is invalid character.
So I then tried passing in the JSON object like so
Widget widg = mapper.readValue(testing.get(0), Widget.class);
Then pass in it
onclick="test('<%=widg%>'); return false;"/>
Now this will pass in without an error, and it alerts the object name, however I am unable to parse it. Object comes in like with the package name of where the widget class is stored like so
com.package.mode.Widget#ba8af9
I tried using Stringify, but that doesn't seem to work on this Jackson JSON object.
After all that failed, I tried a last resort of taking the String from the database, and encoding it in base64. However, this too fails if I do this
String test = Base64.encode(theString);
and pass that in. However if I do that, print it out to the screen, then copy what is printed out, and send that through it works, so don't quite understand why that is.
So could someone please tell me what I am doing wrong. I have tried soo many different solutions and nothing is working.
The JSON String is stored in database like this
{
"id":1,
"splits":[
{
"texts":[
{
"value":"Test",
"locationX":3,
"locationY":-153,
"font":{
"type":"Normal",
"size":"Medium",
"bold":false,
"colour":"5a5a5a",
"italics":false
}
}
]
}
]
}
Would be very grateful if someone could point me in the direct direction!!
Edit:
Incase anyone else has same problem do this to pass the JSON from JSP to the JS function
<%=theJSON.replaceAll("\"", "\\\'")%>
That allows you to pass the JSON in,
then to get it back in JavaScript to normal JSON format
theJSON = theJSON.replace(/'/g,'"');
Should work fine
I think the combination of double quotes wrapping the onclick and the ones in your JSON may be messing you up. Think of it as if you entered the JSON manually -- it would look like this:
onclick="test('{ "id":1, "splits":[ { "texts":[ { "value":"Test", "locationX":3, "locationY":-153, "font":{ "type":"Normal", "size":"Medium", "bold":false, "colour":"5a5a5a", "italics":false } } ] } ] }'); return false;"
and the opening double quote before id would actually be closing the double quote following onclick= (You should be able to verify this by looking at the page source). Try specifying the onclick as:
onclick='test(\'<%=theJSON%>\'); return false;'
You can follow the following steps
Fetch the jon string
Using the jackson or any other JSON jar file , convert the json string to json array and print the string using out.println.
Call this jsp which prints the json string
check in the firebug , you will be able to see your json .
If the Json string does not print , there can be some problems in your json format.
this is a good website for json beautification , http://jsbeautifier.org/ , really makes the string simple to read .
Thanks
Abhi

Categories

Resources