I am wondering what is the most effective form of data validation for android. So, when getting a value from an EditText how should the value given be validated before it is used? I currently check to make sure the string returned from getText().toString() is not null or empty using the guava library:
Strings.isNullOrEmpty(editText.getText().toString())
Then, depending on what type of data I am expecting, I create a method to see if the data can be parsed. So if I am expecting a double I will create a method like this:
private boolean isDouble(String string) {
try {
double stringDouble = Double.parseDouble(string);
return true;
} catch (Exception e)
{
return false;
}
}
Is there a simpler way to do this without the need to create a separate method for each type of data I am expecting to receive?
I've used the edittext-validator the last time I needed a quick validation. Works like charm :)
https://github.com/vekexasia/android-edittext-validator
If you are using EditText you should know what purposes it serves. Usually you are expecting to have just a plain string to, for example, send it to server or store in SharedPreferences.
But, if you want a particular data to be filled in, you can use Pattern class for validation. In case of number values you are using android:inputType="number" and when converting it using Integer.valueOf(text)
Related
I'm working in Java and trying to determine something like so:
I have a SqlParameterSource with an array named "ids" in it. I need to determine what type these ids are in, for example numeric or varchar. I specify that earlier in the code with for example:
return con.createArrayOf("varchar")
or
return con.createArrayOf("numeric")
I have tried this:
if (parametersource.getSqlType("ids") == something) {
// do something
}
else {
//do something else
}
I can't figure out how to do this. getSqlType seems to return an int but I don't know what to compare it to to get the correct comparison.
There is another method named getTypeName but I don't get how this works.
I solved it with:
parameterSource.getValue("objtype").toString();
Fetches the value from "objtype" which I set in my ParameterSource alongside my array to make my end goal easier.
Thanks friends, I love you all. :)
If you're talking about Spring SqlParameterSource,try parametersource.getTypeName("ids")which is inherited from AbstractSqlParameterSource
imagine this:
DataTypeForConfigs config
with
String keys, but values of either String, Integer, or Boolean,
in Java, JSON can do that, but I'm making a format That goes along the lines of:
number "coolness" is 9001 means
int coolness = 9001;
It's method is: Read line, read each word, think what to make of it, set it to a Variable within it's reach
Also: what would happen if another thing had its own place to put config? a null would be read? WHY? constructor thinks a file has null on it? Rage face.
Say... should I make a class called SettingVal that when given a getValue() call it would say what it is?
SO:
config["Coolness"].getValue();
return's 9001
WAIT:
How on earth would I make the getValue() method? HOW? RETURN VALUE WONT LIKE THIS!! OH CRAP!
Solution:
Another Data type comes in and checks its 'gender' (String, Bool, Int) and then checks it's value of that 'gender' (strVal, boolVar, intVar)
Return values are a big problem when dealing with this. I need a stress free version, so maybe I can have a void returning method that runs another method based on what data type it is said to hold! Am I right?
I have a temporary solution, setVar works, getVar is get*Var, where * is Str, Bool or Int.
Sadly, I Haven't yet been able to properly read it from a file, the method I made to read from a file is not working. It makes a Map<String,SettingVar>, using a HashMap constructor and returns that map, but seems whenever I try to access a variable from it that variable is null. It is probably because of IOExceptions and FileNotFoundExceptions, FileNotFound? Why? It Shouldn't be running until called. Oh, and also NullPointerExceptions Please Help!
SUBQUESTION: what happens when you MapVariable.put({NAME HERE}, varToPutIn) many times in a for loop? what about MapVariable.put({NAME HERE},new ...)?
My code in links:
https://gist.github.com/anonymous/66c4d1c2d2718a4cc9b9
because I don't have enough reputation
P.S: OK! ive made the config reader work now, and SettingVar, and SettingContainer and im working on ConfigWriter which is good, now working on a prototype for a java command prompt like thing, and soon a WHOLE OS!! wait... java is an os. thats why java virtual machine... oh. Well, how can I close this question and turn the outcome into a revolutionary new thingy for kids who want to learn to code java *cough cough* especialy ones with higher learning ability than social ability... and like to hang around with mature people who dont bully them like all the kids in their school. (Wow, that was specific)
I would use a Plain Old Java Object which you can read from JSON.
class Config {
int coolness = 9001;
String hello = "world";
boolean cool = true;
}
This way you can have fields with a variety of types.
The type you're looking for is Map<String,Object>, but it is not type-safe and you'll have to do a bunch of casting:
Map<String,Object> config = new HashMap<>();
config.put("coolness",9001);
config.put("hello","world");
config.put("cool", true);
boolean cool = (Boolean) config.get("cool");
String hello = (String) config.get("world");
int coolness = (Integer) config.get("coolness");
Generally, I'd recommend creating a dedicated class for holding your configuration (each field = one property), which is strongly typed and doesn't require casting, and then use something like Jackson to serialize/deserialize it from json, yaml, or xml.
This provides structure to your configuration, and will cause any issues with malformed configurations to show up when you start your application/load your configuration, and not in the middle of your application.
SUBQUESTION: what happens when you MapVariable.put(varToPutIn) many times in a for loop?
A Map represents a mapping. If you do this:
Map<String, Object> map = new HashMap<>();
for (int i = 0; i < 10; i++) {
map.put("myKey", Integer.valueOf(i));
}
what happens is that you add a mapping from "myKey" to zero, then update it to one, two, three and so on. When the loop ends, "myKey" will map to nine.
In short, the map entry for "myKey" is behaving like a variable of type Integer that you assign to repeatedly.
I'm afraid your Gists are telling me that you simply didn't take on board what #Darth Android wrote. Rather that hashing through your code, here's a simple way to parse your config file syntax (more or less) and load it into a Map<String, Object>
Note: I have not compiled or tested this code. It is written to be read and understood, rather than borrowed.
Map<String,Object> config = new HashMap<>();
try (Scanner s = new Scanner(new FileReader(someFile))) {
while (s.hasNext()) {
// Syntax is '<type> <name> is <value>'
String[] words = s.nextLine().split("\\s+");
if (words.length != 4 || !words[2].equals("is")) {
throw MySyntaxException("unrecognizable config");
}
String type = words[0];
String name = words[1];
String val = words[3];
switch (type) {
case "number":
map.put(name, Integer.valueOf(val));
break;
case "boolean":
map.put(name, Boolean.valueOf(val));
break;
case "string":
map.put(name, val);
break;
default:
throw MySyntaxException("unknown type");
}
} catch (NumberFormatException ex) {
throw MySyntaxException("invalid number");
}
}
I'm trying to unravel a Webservice work and replicating it's call, but I've been unable to do it.
In this website, if you input, for example, HY6210 a new window appears with data already filled in.
Using Firebug I was able to determine it was calling
this link,
but no matter what I do in terms of parameters, headers, and cookies, I always get either:
throw 'allowScriptTagRemoting is false.';
//#DWR-REPLY
if (window.dwr) dwr.engine._remoteHandleBatchException({ name:'java.lang.SecurityException', message:'Call IDs may only contain Java Identifiers' });
else if (window.parent.dwr) window.parent.dwr.engine._remoteHandleBatchException({ name:'java.lang.SecurityException', message:'Call IDs may only contain Java Identifiers' });
or
throw 'allowScriptTagRemoting is false.';
//#DWR-REPLY
if (window.dwr) dwr.engine._remoteHandleBatchException({name:'org.directwebremoting.extend.ServerException', message:'The specified call count is not a number' });
else if (window.parent.dwr) window.parent.dwr.engine._remoteHandleBatchException({ name:'org.directwebremoting.extend.ServerException', message:'The specified call count is not a number' });
Any ideas on what I'm doing wrong?
Suppose, historyTracking is the class name and getStoppageV3 method then you pass device1 variable in JavaScript and then you forcefully convert this variabal in string then you use device1.toString().
Example:
historyTracking.getStoppageV3(device1.toString()
I am implementing REST through RESTlet. This is an amazing framework to build such a restful web service; it is easy to learn, its syntax is compact. However, usually, I found that when somebody/someprogram want to access some resource, it takes time to print/output the XML, I use JaxbRepresentation. Let's see my code:
#Override
#Get
public Representation toXml() throws IOException {
if (this.requireAuthentication) {
if (!this.app.authenticate(getRequest(), getResponse()))
{
return new EmptyRepresentation();
}
}
//check if the representation already tried to be requested before
//and therefore the data has been in cache
Object dataInCache = this.app.getCachedData().get(getURI);
if (dataInCache != null) {
System.out.println("Representing from Cache");
//this is warning. unless we can check that dataInCache is of type T, we can
//get rid of this warning
this.dataToBeRepresented = (T)dataInCache;
} else {
System.out.println("NOT IN CACHE");
this.dataToBeRepresented = whenDataIsNotInCache();
//automatically add data to cache
this.app.getCachedData().put(getURI, this.dataToBeRepresented, cached_duration);
}
//now represent it (if not previously execute the EmptyRepresentation)
JaxbRepresentation<T> jaxb = new JaxbRepresentation<T>(dataToBeRepresented);
jaxb.setFormattedOutput(true);
return jaxb;
}
AS you can see, and you might asked me; yes I am implementing Cache through Kitty-Cache. So, if some XML that is expensive to produce, and really looks like will never change for 7 decades, then I will use cache... I also use it for likely static data. Maximum time limit for a cache is an hour to remain in memory.
Even when I cache the output, sometimes, output are irresponsive, like hang, printed partially, and takes time before it prints the remaining document. The XML document is accessible through browser and also program, it used GET.
What are actually the problem? I humbly would like to know also the answer from RESTlet developer, if possible. Thanks
I do a Action on Middle ware and if its success i get the Value as
String result = ["RESULT","DELETE","OK"]
And in Case if the Operation is Failed i get the resposne as
String result = ["RESULT","DELETE","ERROR"]
I need to know if the Operation is success Or Fail so for this i have done this
public class Test {
public static void main(String args[]) {
String result = "[\"RESULT\",\"DELETE\",\"ERROR\"]";
if (!result.contains("ERROR")) {
System.out.println("success");
} else {
System.out.println("Failed");
}
}
This is working fine , but not sure if this has any negative impact / or in cases the code may Fail .
Please suggest if there is a better approach .
Your code can fail if, for instance, you get a success message containing ERROR (not likely, but can happen).
You should use a library to parse the result into a List/Array, look here on StackOverflow for a ton of solutions for parsing Json Strings to Objects in Java (Jackson is a library to do this, for instance).
You should also validate against a pre-set number of hypothesis, for instance, creating an enum for the possible result types, and checking if it's one of them.
I would suggest to use object presentation instead of array here:
{
"RESULT": {
"operation": "DELETE",
"status" : "ERROR"
}
}
There is you can find a lot of tools to parse JSON in Java objects:
http://www.json.org/
In other case it will be hard to extend set of codes. E.g.
String result = "[\"RESULT\",\"CREATE\",\"USER\", \"LOGIN\", \"ERROR\", \"SUCCESS\"]";
Was there error? or user with login ERROR was successfully created?
String[] result = {"RESULT","DELETE","OK"};
if(Arrays.asList(result).contains("OK"))
System.out.println("Ok");
Try Arrays.asList() method to check given arrays contains that element or not.