How to look for a webelement with out an exception being thrown? - selenium-webdriver

I am trying to verify to see some webelement is present or not on my result page, using id attribute. It is throwing an exception when such webelement is not present and it is NOT acceptable. In the Selenium API JavaDoc, it was recommended that 'findElement' should not be used to look for non-present elements, use 'findElements(By)' instead and assert zero length response. But this is also throwing an exception, I don't know why !! Any alternate suggestions?
try{
// THE PRESENT CODE TO BE MODIFIED. NOT TO THROW exception.***********
// if(driver1.findElement(By.id(orderResultsCheckbox_0)) != null)
// return true;
// *****************************
//Instead I wrote as below...
if(
(driver1.findElements(By.id(orderResultsCheckbox_0) != null)) && (driver1.findElements(By.id(orderResultsCheckbox_0)).length() > 0)
)
return true;
else
return false;
} catch (Exception e) {
println "Exception Thrown ==========>";
return false;
}

The findElements method returns a list of webelements and you can check whether the list contains any webelements using the size() method. Hence, replace your existing code with following and let me know whether it resolves your issue:
if(driver1.findElements(By.id(orderResultsCheckbox_0)).size() != 0)
return true;
else
return false;

Related

How to handle keys pressed almost in the same time?

I'm trying to resolve a problem with the search bar. It works but the problem is that if I press two keys almost at the same time, the app will only search the words with the first key pressed.
Here are the logs:
In this one, it works when I press the P then R:
[EDT] 0:4:9,283 - p
[EDT] 0:4:9,348 - 10
[EDT] 0:4:9,660 - pr
[EDT] 0:4:9,722 - 3
The second one doesn't because I press P and R nearly at the same time:
[EDT] 0:4:35,237 - p
[EDT] 0:4:35,269 - pr
[EDT] 0:4:35,347 - 0
[EDT] 0:4:35,347 - 10
The logs here are generated to show the String searched and the result size. As you can see, the first case get results before typing the next char and the second case got all results when the two chars are typed.
The main problem is that in the second case, results from the 'p' String are shown instead of those of 'pr'.
I'm using the searchbar from the Toolbar API with addSearchCommand and an InfiniteContainer to show result data.
Could it be a problem in the order of the events from the addSearchCommand are treated ?
EDIT: Here is the client side code. Server side it's just a simple rest service call which fetch the data from the database.
public static ArrayList<Patient>getSearchedPatient(int index,int amount, String word)
{
ArrayList<Patient> listPatient = null;
Response reponse;
try {
reponse = RestManager.executeRequest(
Rest.get(server + "/patients/search")
.queryParam("index", String.valueOf(index))
.queryParam("amount", String.valueOf(amount))
.queryParam("word", word),
RequestResult.ENTITIES_LIST,
Patient.class);
listPatient = (ArrayList<Patient>)reponse.getResponseData();
Log.p(""+listPatient.size());
} catch (RestManagerException e) {
LogError("", e);
}
return listPatient;
}
private static Response executeRequest(RequestBuilder req, RequestResult type, Class objectClass) throws RestManagerException
{
Response response = null;
try {
switch (type) {
case BYTES:
response = req.getAsBytes();
break;
case JSON_MAP:
response = req.acceptJson().getAsJsonMap();
break;
case ENTITY:
response = req.acceptJson().getAsProperties(objectClass);
break;
case ENTITIES_LIST:
response = req.acceptJson().getAsPropertyList(objectClass);
break;
default:
case STRING:
response = req.getAsString();
break;
}
} catch (Exception e) {
log().error("Erreur à l'exécution de la requête", e);
response = null;
}
if(response == null)
return null;
return response;
}
So the trick here is a simple one. Don't make a request... Most users type fast enough to saturate your network connection speed so you will see completion suggestions referring to things that are no longer relevant.
This is a non-trivial implementation which I discuss in-depth in the Uber book where such a feature is implemented.
The solution is to send a request after a delay while caching responses to avoid double requests and ideally canceling request in progress when applicable. The solution in the Uber book does all 3 I'll try to cover just the basics in this mockup code. First you need a field for the timer and current request. Ideally you would also have a Map containing cached data:
private UITimer delayedRequest;
private String currentSearch;
private Map<String, String> searchCache = new HashMap<>();
Then you need to bind a listener like this:
tb.addSearchCommand(e -> {
String s = (String)e.getSource();
if(s == null) {
if(delayedRequest != null) {
delayedRequest.cancel();
delayedRequest = null;
}
return;
}
if(currentSearch != null && s.equals(currentSearch)) {
return;
}
if(delayedRequest != null) {
delayedRequest.cancel();
delayedRequest = null;
}
currenSearch = s;
delayedRequest = UITimer.timer(100, false, () -> {
doSearchCode();
});
});
I didn't include here usage of the cache which you need to check within the search method and fill up in the result code. I also didn't implement canceling requests already in progress.

Why does File.listFiles() throws NullPointerException on some devices?

Please pay attention to all the tests in the following code:
File folder = new File(sFolderPath);
if (folder == null) {
//do nothing
} else {
if (folder.exists()) {
File[] flist = folder.listFiles();
}
}
folder.listFiles() throws the following exception:
java.lang.NullPointerException: Attempt to get length of null array
It rarely happens. I am wondering how this can be possible after passing the tests of null and existence.

Lost on how to implement writeCharecteristic in my android code

I am using android studio's example bluetoothlegatt, which has a read function and and works completely find (it interacts with the TI keyfob I have which sends over values when pressed).
However, I have no idea how to put in writeCharecteristic because my previous attempts have failed.
Can someone help me with this? I would like to send a "1" over so that the keyfob's led lights up.
Edit: I have tried something like this
public void writeCharacteristic(byte[] value) { BluetoothGattService LumService = mBluetoothGatt.getService(UUID_LUM_APP);
if (LumService == null) {
System.out.println("LumService null"); return; }
BluetoothGattCharacteristic LumChar = LumService.getCharacteristic(UUID_LUM_CHAR);
if (LumChar == null) {
System.out.println("LumChar null"); return; }
LumChar.setValue(value); boolean status = mBluetoothGatt.writeCharacteristic(LumChar);
System.out.println("Write Status: " + status);
This is not my code, though, just an example. I want to integrate this into the bluetoothlegatt given already, but I have had no success with it.

To check for infinite while loop. I am using a boolean variable

I am using the following code:
boolean continueProcessing = true;
boolean lastRecord = false;
while (continueProcessing) //can it be changed to while (continueProcessing == true), what's the advantage
{
if(refListItemItr.hasNext() || lastRecord)
{
continueProcessing = true;
lastRecord = false;
}
else
{
continueProcessing = false;
}
if(continueProcessing)
{
lSynonymListType = objFactory.createSynonymListType();
}
}
I suspect there is a scenario of infinite loop. How should I confirm that it does not happen.
The reason this will cause an infinite loop is that you keep checking if the next item exists, but you never actually call next() to retrieve it, so the internal pointer doesn't move along and you're just checking if there's a first item in the list.
Regardless, you're overcomplicating this. You should just be doing
while (refListItemItr.hasNext()){
Object item = refListItemItr.next(); // change Object to the item's type
// Presumably actually do something with the item here, which currently you're not...
}
Or, even more simply
for (Object o : refListItemItr){
// do stuff
}
And in answer to your other question, there is absolutely no difference between while(continueProcessing) and while (continueProcessing == true)

Else-part of code being executed, even if string.equals(otherstring) is true

The problem with this code seems to be that the 'else' part of the if-statement is executed, even if the variables match (so 'if' is true). Any advice, please?
Thanks!
public void CheckInstalledDBVersion() throws NullPointerException, IOException {
try {
//TRY TO OPEN DATABASE AND READ VERSION
//WRITE VERSION TO InstalledDBversion
} catch(RuntimeException e) {
//IF TABLE COULD NOT BE QUERIED
//SET InstalledDBversion to Bogus value
InstalledDBversion = "00";
Log.d("RTE", ".. but we've catched it!");
} finally {
if (InstalledDBversion.equals(PackedDBversion)){
// Installed DBVersion == Packed DBVersion .. nothing happens
}
else
showDialog(DBCHECKFAILDIALOG);
initialiseDatabase = false;
copyDB();
}
}
So, when I execute, copyDB(); gets called even if InstalledDBversion.equals(PackedDBversion) == true
else
showDialog(DBCHECKFAILDIALOG);
initialiseDatabase = false;
copyDB();
Fixed indentation for you. copyDB is outside of the if/then/else block. Use an IDE with code formatting.
What lines are supposed to be included in the else block? the showDialog(DBCHECKFAILDIALOG) is only included. Are you missing a set of {} for the else block?

Resources