mail_xml is this:
EditText android:inputType="numberDecimal|numberSigned`
onTextChanged implemented on this and other edittexts and calls relative methods.
//and one method example:
if (editTextNumber.getText().toString().equals("") ||
editTextNumber.getText().toString().equals("-") ||
editTextNumber.getText().toString().equals(".")) {
//say its bad or reset interface so the user knows;
else {
//do stuff;
}
Should I create a class to do the validation and instantiate it, then use an if/else statement returning a boolean?
It's difficult because a - is valid as the user types, so is a .. But a . and - crashes. I'm thinking a class would be best?
I don't remember a function in java to do this, unless the api has been updated and I haven't seen it yet. I've created the classes i need and can instantiate them call their getter methods no problem. just stuck on the basic validation.
You can simply put the cast in a block try/catch...
This way if the text inserted is not a number, an exception is fired...
For exemple:
if(editTextNumber.getText()!=null && !editTextNumber.getText().toString().equals("")){
try{
// int value
Integer.parseInt(editTextNumber.getText().toString());
// double value
Double.parseDouble(editTextNumber.getText().toString());
}catch(Exception e){
//prints the exception that you got
//if number format exception then your input is not a number
e.printStackTrace();
}
}
Hope it helped...
Related
The Code A is common usage in java.
I havn't understanded completely the key let of Kotin. Which one should I use between Code A and Code B in kotlin? Thanks!
Code A
if (data!=null){
initAndBindAdapter()
mCustomAdapter.setSelectedIndex(data.getIntExtra("index",-1))
}
Code B
data?.let {
initAndBindAdapter()
mCustomAdapter.setSelectedIndex(it.getIntExtra("index",-1))
}
And more, which one should I choose between Code C and Code D in kotlin if the fun do_NoNeed_data_par doesn't need data parameter ?
Code C
if (data!=null){
do_NoNeed_data_par()
}
Code D
data?.let {
do_NoNeed_data_par()
}
I (personal opinion) think it's a good idea to use simple, regular null checks where you can, although the ?.let method has been listed under the main Kotlin Idioms page of the documentation (which is open for the community to contribute) - so basically, this will be up to your personal preferences of which one is more readable.
The more interesting question is what are the differences, and when you can use each: the main difference is that let holds on to the value of the variable as it was when the let call on it started, and any subsequent uses of it within the let block will reference that same value. If you use a simple null check with if, your variable's value might be changed while the body of the if block is being executed.
So for example, this won't compile, because x can be accessed by multiple threads, and it might be non-null when you read its value first for the null check, but it might become null by the time you read it again for the println parameter - this would be unsafe:
class Foo {
var x: Int? = null
fun useX() {
if (x != null) {
println(x + 10) // (...) 'x' is a mutable property that could have been changed by this time
}
}
}
However, a let will work in the same situation, because it will use whatever the initial value of x had all throughout its execution, even if the x property in the class gets reassigned in the meantime:
class Foo {
var x: Int? = null
fun useX() {
x?.let {
println(it + 10)
}
}
}
You can think of the ?.let statement above of basically performing this, creating a temporary copy of your variable:
fun useX() {
val _x = x
if (_x != null) {
println(_x + 10)
}
}
Operating on this copy is safe, because even if the x property changes its value, this _x copy will either stay null for this entire function, or it's non-null and safe to use.
"should" is opinionated. It all depends on your preference.
If you prefer more functional style code then .let is your answer. If you prefer more procedural code then == null is your answer.
Sometimes, using let() can be a concise alternative for if. But you have to use it with sound judgment in order to avoid unreadable “train wrecks”. Nevertheless, I really want you to consider using let().
val order: Order? = findOrder()
if (order != null){
dun(order.customer)
}
With let(), there is no need for an extra variable. So we get along with one expression.
findOrder()?.let { dun(it.customer) }
I am working on my own library for Android and I have two variables that need to be validated. The following variables are declared within one of my library classes.
Boolean Decimals = false;
Boolean Separator = true;
When developers use the library, if they set Decimals = true and Separator = true, I want to throw an error underlying the code lines displaying a message:
Decimals cannot be set as true when Separator is set as true`.
This is a form of validation I need in my library to avoid conflicts in certain functions.
How can I throw a library-level error after validating if these two variables are always set as opposites?
NOTE: Throwing it during runtime is not the desired behaviour. I would like to indicate it during the developer's coding process
Hopefully you are writing the library as an API rather than a set of loose functions.
The user might use it in this way:
LibraryObject lo = new LibraryObject(...);
lo.setDecimal(true);
lo.setSeparator(true);
Then in your setter, you will have some validation like:
setDecimal(boolean decimal) {
if(this.separator == false && decimal == true) this.decimal = true;
else {throw error; }
}
Same for the other case.
Suppose now you have a setter function to update this variable
public void setDecimals(boolean someValue)
{
this.Decimals = someValue;
}
And if you want to validate it you can do it inside the setter
public void setDecimals(boolean someValue) throws Exception
{
if(someConditions){
this.nickname = nick; // here this is the allowed case
}else{
throw new Exception("Decimals cannot be set as true when Separator is set as true");
}
}
I can get a String from the shared preferences by using:
sharedPreferences.getString("key_name","default value");
But how can I check if key_name is actually a String?
What if it is a Boolean key value?
Is there a method we can use like:
if(sharedPreferences.isTypeOf(Boolean,"key_name")) {}
If you know you will get a boolean you can use
sharedPreferences.getBoolean("key_name",true);
Otherwise you can do (not tested, based on doc)
Map<String, ?> all = sharedPreferences.getAll();
if(all.get("key_name") instanceof String) {
//Do something
}
else if(all.get("key_name") instanceof Boolean) {
//Do something else
}
But you are suppose to know what you stored in your SharedPrefrences
What is expected is you ought to know the data type of your SharedPreference values.
All the shared prefrences that you put are inserted into a Map.
A map cannot have duplicate keys that hold different values. When you use the put operation it basically overwrites the value associated with the key if they key already exists in the map.
You can find how a Map "put" method works here - Java Map
So checking the instanceof for two(or multiple) data types as suggested by #Maloubobola, is kind of absurd since the key can only one value and that value can be of only one data type(which you should know :P).
You can do that but it doesn't make sense like #Blackbelt commented.
All the best :)
If you expect a String, you can also use a try/catch clause:
try {
String strValue = sharedPreferences.getString("key_name","default value")
actionIfString();
} catch (ClassCastException e) {
actionIfNotString();
}
I create an app that like dictionary app. When the user types in an Edittext, I call an AsyncTask to compute and update the result to the screen (I put the UI update code in onPostExecute() method ). However, when you type little fast, the eddittext become not responesive (a little latency). I think this promblem occurs because many AsyncTasks are running (each AsynTask for an input letter). So, I think I need to stop the first task before calling new task. Am I right? What should I do in this situation?
You don't need to implement the filter method in an async task. I call filter method on data when first letter has been written in editbox and save the result in an temporary array, then when another letter has been written, I call filter method on the temporary data which technically has less information than the original data. By doing this, the dimmension of data set decreases as you type in editbox. Also, you can use this method to store previous data set so when you press backspace, you don't have to call filter method again, you just go to previous saved temporary data set. For me, it works fine and I don't have to use async task because it is efficient
I suggest you another approach: use only one thread. The searching thread should wait for searching data > do search > and sleep until new data. E.g.:
private static class SearchThread extends Thread{
private Object monitor = new Object();
private String value;
public void search(String value){
this.value = value;
synchronized (monitor){monitor.notify();}
}
#Override
public void run() {
while(true){
try {System.out.println("Wait for search data."); synchronized (monitor){monitor.wait(); }
} catch (InterruptedException e) {e.printStackTrace();}
System.out.println("Searching for " + value);
}
}
}
I've tried null and empty string, any other ideas?
No other possibility.
getText, infact, will never return null. It returns CharSequence whose contents may be empty.
Instead of doing getText().toString().equals("") or vice-versa, it may be faster to do getText().length() == 0
If it's empty, this will work:
if(mEditText.getText().toString().equals("")) {
// stuff to run when it's empty
}
Even if it's empty, getText() will still return an Editable, so if you were trying to do this:
if(mEditText.getText().equals("")) {
// stuff
}
It most certainly wasn't working.
You can use TextUtils.isEmpty( mEditText.getText().toString() ). It will return true if its empty/null.
The best way I found to check it is to stock the value in a var like:
String text = mEditText.getText().toString();
and then to use boolean operator isEmpty like:
if (text.isEmpty){
// stuff
}
After looking at several questions and since it's already possible to get a null I've found the answer to avoid a
method invocation toString may produce NPE
warning all over the place:
String theText = String.valueOf(mEditText.getText());