What is the best way to test if string is empty?
I know it is possible to use if/else condition but is there possibility to use while loop?
I used both variants but in my case (see on picture) the while loop do not work and still get the empty string error. And is there some more elegant way to evaluate more fields in one while loop?
What is the best way to test if string is empty?
use the is empty block
but is there possibility to use while loop?
to use a while loop to do some data validation does not make sense, because as you already found out, a while loop will block your device and will result in a runtime error. See also The model of event processing in App Inventor by Lyn
is there some more elegant way to evaluate more fields in one while
loop?
instead of using a while loop, use an if - then - elseif - elseif - ... - else statement, see also the documentation
Related
Good Afternoon, I have a question please have look at this.
I am using Retrofit beta 2 for retrieving data from api. I have an EditText in which I want to search some names from server. I got the output also, but for example consider there are some names:
ABC,XYZ,PQR,STU,ETC. These are the names stored in the server and I am retrieving this names using Retrofit beta2.
When I searched for ABC or abc it will display the results and when I removed the string from the EditText then nothing is displayed.
Till here I Have done.
My question is when I type names fast then the result is something else.
So, can anyone tell me how to avoid this.
Thank You.
The Call object has a couple of utility methods you can use namely isExecuted and cancel to control your request.
http://square.github.io/retrofit/2.x/retrofit/retrofit2/Call.html
I am assuming you are using TextWatcher. Pseudo-code as follows:
public void afterTextChanged (Editable s) {
// Cancel the request first before sending it again; this way you won't have two separate calls
if(call != null && call.isExecuted()) {
call.cancel();
}
// reinitialize call and execute it again
}
Generally speaking, it is ill-advised to listen for immediate input from user to spawn an action: you should rethink your approach; it's better to put a "submit" or button to execute the API call; otherwise you'll be spamming the server with several HTTP requests per input.
Remember the search text e.g. "AB" on the search result. Before displaying the result, check if the currently entered text still matches the text of the search result and only use the result, if it does.
Searched for "AB", current text "ABC" -> don't show the result.
Searched for "ABC", current text "ABC" -> show the result.
Like this it won't even matter in what order the two requests return, it will always display only the correct result.
I think it is not safe to start a new thread for every character
This is How I did in my App:
You can use a Queue to store every string that user input. Every time the edittext changed, a new string will be inserted to the queue
At the same time, you can send the query async by retrofit. but if the retrofit is on its way querying, you do not send immediately, only put the string into the queue. when your callback function is called by retrofit, you can remove all strings from queues except the latest one, then use retrofit to query this newest query.
Too much thread, will affect the performance of any device, because it the overhead involve will consume lot of resource.
starting a new thread for each character is by no means advisable, to answer your question each thread should continually check for a change in characters, when you type fast, it mean tend to skip some result but will eventually display the result of the last string correctly.
I am trying to use contains for strings coinciding with the search symbols. However, seems like contains does not have an ignore case unlike equals. Is there any way to go around ?
The following line of code is where I am using the same (I have heard of pattern, but how do I use the same in my case? )
searchSymbol.contains(mSearchView.getText().toString()
Thanks!
Justin
You can just convert them both to lower case and use contains() as normal:
searchSymbol.toLowerCase().contains(mSearchView.getText().toString().toLowerCase())
You could write your own function to do this if you want to keep it clean:
public static boolean containsIgnoreCase(String haystack, String needle){
return haystack.toLowerCase().contains(needle.toLowerCase());
}
You could use the function from StringUtils:
org.apache.commons.lang3.StringUtils.containsIgnoreCase("testString", "stSt");
In any case, you're going to want to watch out for unicode characters. They don't play by the normal rules of "case" in most circumstances.
I have a test case for my app which fills in the TextViews in an Activity and then simulates clicking the Save button which commits the data to a database. I repeat this several times with different data, call Instrumentation.waitForIdleSync(), and then check that the data inserted is in fact in the database. I recently ran this test three times in a row without changing or recompiling my code. The result each time was different: one test run passed and the other two test runs reported different data items missing from the database. What could cause this kind of behavior? Is it possibly due to some race condition between competing threads? How do I debug this when the outcome differs each time I run it?
Looks like a race condition.
remember in the world of threading there is no way to ensure runtime order.
I'm not an android dev so I'm only speculating but UI is only on one event thread generally so when you call the method from another thread (your test) you're probably breaking that as you're outside of the event thread.
You could try using a semaphore or more likely a lock on the resource.
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/locks/Lock.html
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/Semaphore.html
I (finally!) found a solution to this problem. I now call finish() on the tested Activity to make sure that all of its connections to the database are closed. This seems to ensure consistency in the data when I run the assertions.
I would suggest making a probe for the database data rather than a straight assert on it. By this I mean make a piece of code that will keep checking the database for up to a certain amount of time for a condition rather than waiting for x seconds (or idle time) then check, I am not on a proper computer so the following is only pseudo code
public static void assertDatabaseHasData(String message, String dataExpected, long maxTimeToWaitFor){
long timeToWaitUntil = System.getCurrentTimeMillis() + maxTimeToWaitFor;
boolean expectationMatched = false;
do {
if(databaseCheck() == dataExpected){
expecttionMatched == true;
}
}while(!expectationMatched && System.getCurrentTimeMillis() < timeToWaituntil);
assertTrue(message, expectationMatched);
}
When i get to a computer i will try to relook into the above and make it better (I would actually of used hamcrest rather than asserts but that is personal preference)
I need help with using an if statement in java, here is my code :
if(ans==1)
{
txtans.setText("This is a Prime Number");
}
else
{
txtans.setText("This is NOT a Prime Number");
}
if I remove the setText methods in both statements my program works, but when I leave them there and the program finds ans, then it quits, I'm wondering whats wrong with the statements? or is it not possible to use the setText method within if statements..if so how do I overcome this? What I want to do is print a string to the TextView layout when the ans = 1, any suggestions?
Yes, you can run txtans.setText() in an if statement just as well as you could run it if it wasn't in an if statement. You likely just don't have txtans initialised properly.
A quick google search brought up this as a way to print text to a textview.
Check your code, this erros usually comes when use findViewById() method in a wrong view.
In the activity you use like this findViewById(), maybe you need to call yourView.findViewById();
(If you post your class we can help you with more detailed answear.)
Also note that it is not allowed to call methods from Views from another Thread which created them. But a LogCat output including the Error will enlight us for shure :)
txtans might be NULL and you are trying to access a member of a NULL object.
hi i have found Uri as immutable reference i dont know what it is the exact meaning of immutable reference... can anyone help me?
It's a variable that cannot be changed once set. Very useful when you have multithreaded code since being able to change a variable's value might be a source of many hard to find problems in your code.
If it's immutable, it's usually good.
A good example of an immutable class within the .NET Framework is System.String. Once you create a String object, you can’t ever change it. There’s no way around it; that’s the way the class is designed. You can create copies, and those copies can be modified forms of the original, but you simply cannot change the original instance for as long as it lives, without resorting to unsafe code. If you understand that, you’re probably starting to get the gist of where I’m going here: For a referencebased object to be passed into a method, such that the client can be guaranteed that it won’t change during the method call, it must itself be immutable.
In a world such as the CLR where objects are held by reference by default, this notion of immutability becomes very important. Let’s suppose that System.String was mutable, and let’s suppose you could write a method such as the following fictitious method:
public void PrintString( string theString )
{
// Assuming following line does not create a new
// instance of String but modifies theString
theString += ": there, I printed it!";
Console.WriteLine( theString );
}
Imagine the callers’ dismay when they get further along in the code that called this method and now their string has this extra stuff appended onto the end of it. That’s what could happen if System. String were mutable. You can see that String’s immutability exists for a reason, and maybe you should consider adding the same capability to your design.
EX: string is immutable...
if u have for ex string s =" whatever" and u output it with uppercase letter..for ex
Console.Write(s.ToUpper())the console will print u WHATEVER...but the string s will still be whatever... unlike the mutable type which will change the string from whatever to WHATEVER
"immutable" means "can't change the value"
"mutable" == "changeable"
"immutable" == "not changeable"
In java , every thing is treated as String and object , Now try to think that if have created a program of 10000 lines and in this there you have added "public" 100 times so do you think that every time this public is created in storage . else what we can do , we can created something like that when ever we find something like this we will fetch it from there there ( String pool )