android getInputType in JAVA code - java

I defined a EditText in XML with attribute android:inputType="numberSigned", so, when I try to get it in Java Code like:
int type = mEditText.getInputType();
switch(type){
case InputType.TYPE_NUMBER_FLAG_SIGNED:
//do when I get EditText defined with 'numberSinged'
//do something
break;
}
But, It doesn't work for me. So I try to check Android source code, TYPE_NUMBER_FLAG_SIGNED=4096. When I try to print println(mEditText.getInputType()),it turns to be 4098. And I can't find any variable equals 4098.
Can anybody tell me the reason?
I'm not good at English, may you can understand me! Thanks!

there can be multiple flags assigned to inputType. To find out if a flag is set or not, use the bitwise AND (&) operator:
int type = mEditText.getInputType();
if((type & InputType.TYPE_NUMBER_FLAG_SIGNED) > 0)
{
// your stuff here
}
I guess, the usage of switch case is not possible here.

TYPE_NUMBER_FLAG_SIGNED Constant Value: 4096 (0x00001000) .
get more information here

Related

get char of VK_ key

In a method i'm receiving vk_key's as just a int, nothing more is provided.
I need to forward this, which looks like:
parent.postEvent(new KeyEvent(null, parent.millis(), KeyEvent.TYPE, modiefiers, c_key, vk_key));
The problem is there are also things like VK_UP, VK_DOWN etc.
Where normally I need to do a cast: char c_key = (char)vk_key;, this is incorrect for VK_UP etc. cause the cast will make the up key a '&' for example.
For those cases the c_key should be set to KeyEvent.CHAR_UNDEFINED.
What I do now is this:
switch (vk_key) {
case VK_UP:
case VK_LEFT:
case VK_RIGHT:
case VK_DOWN:
c_key = CHAR_UNDEFINED;
break;
}
But this does not feel like the right way to do it.
Ideally there would have been a static method like static public char getCharForKey(int vk_key), which would return CHAR_UNDEFINED where required. But as always oracle makes things way harder then they should be.
So is there any easy way to figure out if something should be CHAR_UNDEFINED or not?

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.

Possible without String?

I can’t solve this task without a string (don’t know yet) :
"My program asks the user if he wants to see a smiley. If he answers with 'Y' he gets a ":)", other input will be a ":(". Use a conditional operator."
My solution (with a string):
System.out.println("Do you want to see a smiley");
answer=scan.findWithinHorizon(".",0).charAt(0);
string=(answer=='Y')?: ":)" : ":("; //works like that but I need it without string
System.out.println(string);
btw: is the conditional operator often used?
Thanks for your help
And if there are any further advices tell me please.
I don't know if i understan you but you can try:
if(answer=='Y'){
System.out.println(":)");
}
else{
System.out.println(":(");
}
And yes conditional operator for example: if/else is one of the basic things in programing.
Do you mean without String variables? Then here is the nasty oneliner:
System.out.println("Do you want to see a smiley");
System.out.println(scan.findWithinHorizon(".",0).charAt(0)=='Y' ? ":)" : ":(" );
If you mean without using any kind of string (not even ""), you cold print each char individually. This would not require a String but is really annoying and unnecessary.
Edit: because requested, here is this version:
System.out.print('D');
System.out.print('o');
....
System.out.print('y');
System.out.print('\n');
if (scan.findWithinHorizon(".",0) == 'Y') {
System.out.print(':');
System.out.print(')');
System.out.print('\n');
} else {
....
}

How to use an array value as field in Java? a1.section[2] = 1;

New to Java, and can't figure out what I hope to be a simple thing.
I keep "sections" in an array:
//Section.java
public static final String[] TOP = {
"Top News",
"http://www.mysite.com/RSS/myfeed.csp",
"top"
};
I'd like to do something like this:
Article a1 = new Article();
a1.["s_" + section[2]] = 1; //should resolve to a1.s_top = 1;
But it won't let me, as it doesn't know what "section" is. (I'm sure seasoned Java people will cringe at this attempt... but my searches have come up empty on how to do this)
Clarification:
My article mysqlite table has fields for the "section" of the article:
s_top
s_sports
...etc
When doing my import from an XML file, I'd like to set that field to a 1 if it's in that category. I could have switch statement:
//whatever the Java version of this is
switch(section[2]) {
case "top": a1.s_top = 1; break;
case "sports": a1.s_sports = 1; break;
//...
}
But I thought it'd be a lot easier to just write it as a single line:
a1["s_"+section[2]] = 1;
In Java, it's a pain to do what you want to do in the way that you're trying to do it.
If you don't want to use the switch/case statement, you could use reflection to pull up the member attribute you're trying to set:
Class articleClass = a1.getClass();
Field field = articleClass.getField("s_top");
field.set(a1, 1);
It'll work, but it may be slow and it's an atypical approach to this problem.
Alternately, you could store either a Map<String> or a Map<String,Boolean> inside of your Article class, and have a public function within Article called putSection(String section), and as you iterate, you would put the various section strings (or string/value mappings) into the map for each Article. So, instead of statically defining which sections may exist and giving each Article a yes or no, you'd allow the list of possible sections to be dynamic and based on your xml import.
Java variables are not "dynamic", unlink actionscript for exemple. You cannot call or assign a variable without knowing it at compile time (well, with reflection you could but it's far to complex)
So yes, the solution is to have a switch case (only possible on strings with java 1.7), or using an hashmap or equivalent
Or, if it's about importing XML, maybe you should take a look on JAXB
If you are trying to get an attribute from an object, you need to make sure that you have "getters" and "setters" in your object. You also have to make sure you define Section in your article class.
Something like:
class Article{
String section;
//constructor
public Article(){
};
//set section
public void setSection(Section section){
this.section = section;
}
//get section
public String getSection(){
return this.section;
}

Can I strictly evaluate a boolean expression stored as a string in Java?

I would like to be able to evaluate an boolean expression stored as a string, like the following:
"hello" == "goodbye" && 100 < 101
I know that there are tons of questions like this on SO already, but I'm asking this one because I've tried the most common answer to this question, BeanShell, and it allows for the evaluation of statements like this one
"hello" == 100
with no trouble at all. Does anyone know of a FOSS parser that throws errors for things like operand mismatch? Or is there a setting in BeanShell that will help me out? I've already tried Interpreter.setStrictJava(true).
For completeness sake, here's the code that I'm using currently:
Interpreter interpreter = new Interpreter();
interpreter.setStrictJava(true);
String testableCondition = "100 == \"hello\"";
try {
interpreter.eval("boolean result = ("+ testableCondition + ")");
System.out.println("result: "+interpreter.get("result"));
if(interpreter.get("result") == null){
throw new ValidationFailure("Result was null");
}
} catch (EvalError e) {
e.printStackTrace();
throw new ValidationFailure("Eval error while parsing the condition");
}
Edit:
The code I have currently returns this output
result: false
without error. What I would like it to do is throw an EvalError or something letting me know that there were mismatched operands.
In Java 6, you can dynamically invoke the compiler, as explained in this article:
http://www.ibm.com/developerworks/java/library/j-jcomp/index.html
You could use this to dynamically compile your expression into a Java class, which will throw type errors if you try to compare a string to a number.
Try the eval project
Use Janino! http://docs.codehaus.org/display/JANINO/Home
Its like eval for java
MVEL would also be useful
http://mvel.codehaus.org/
one line of code to do the evaluation in most cases:
Object result = MVEL.eval(expression, rootObj);
"rootObj" could be null, but if it's supplied you can refer to properties and methods on it without qualificiation. ie. "id" or "calculateSomething()".
You can try with http://groovy.codehaus.org/api/groovy/util/Eval.html if groovy is an option.

Categories

Resources