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

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.

Related

Invalid Private length Issue

throw new _BadKeyError.default(`invalid private key length: ${data.length} bytes`);
getting this error while setting up test environment
const { Client } = require("#hashgraph/sdk");
require("dotenv").config();
async function main() {
//Grab your Hedera testnet account ID and private key from your .env file
const myAccountId = process.env.MY_ACCOUNT_ID;
const myPrivateKey = process.env.MY_PRIVATE_KEY;
// If we weren't able to grab it, we should throw a new error
if (myAccountId == null ||
myPrivateKey == null ) {
throw new Error("Environment variables myAccountId and myPrivateKey must be present");
}
// Create our connection to the Hedera network
// The Hedera JS SDK makes this really easy!
const client = Client.forTestnet();
client.setOperator(myAccountId, myPrivateKey);
console.log('success');
client.close();
}
main();
above code i ran and got the error.kindly someone check
The error message given points me to think your private key may be off. Double-check your .env file and ensure you have entered in your private key correctly.

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 groovy method doesn't print that file doesn't exist?

I have problem with my groovy script. I'm reading content from registerFile and I want to catch Exception when file is not found. Nevertheless below function doesn't throw exception even if registerfile does not exist, why?
Fragment of my code:
def registerFile
static void main(def args) {
Agent agent = new Agent()
agent.findSmth()
}
Agent() {
registerFile = new File(/path/toFile)
}
def findSmth() {
def s
try {
def lines = registerFile.readLines()
def numbers = lines.get(lines.size() - 1).findAll(/\d+/)*.toInteger()
s = numbers.get(numbers.size() - 1)
} catch (Exception e) {
println(e) //why not print that file doesn't exist?
} finally {
return s
}
}
I'm assuming that the above code is inside the class Agent.
As soon as you execute an operation on a non-existing file, an exception is thrown; so your catch statement should catch the Exception.
Are you sure that no such file exists in the path that you mentioned?

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

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;

Handling AccessViolation exception in try catch c#

How to catch the AccessViolation exception in try-catch block:
here is the code below:
public static BP GetBloodPressure(string vendorid, string productid)
{
BP Result = new BP();
try
{
GETBPData BPreadings = new GETBPData();
UInt16 VendorId = Convert.ToUInt16(vendorid, 16);
UInt16 ProductId = Convert.ToUInt16(productid, 16);
if (HealthMonitorData.HidDataTap_GetBloodPressure(VendorId, ProductId, ref BPreadings)) // error here
{
if (BPreadings.ucSystolic == 0 && BPreadings.ucDiastolic == 0 && BPreadings.DeviceId1 == 0 && BPreadings.DeviceId2 == 0 && BPreadings.ucPulse == 0)
{
Result = null;
}
else
{
Result.UcSystolic = BPreadings.ucSystolic;
Result.UcDiastolic = BPreadings.ucDiastolic;
Result.UcPulse = BPreadings.ucPulse;
Result.DeviceId1 = BPreadings.DeviceId1;
Result.DeviceId2 = BPreadings.DeviceId2;
}
}
}
catch (Exception ex)
{
}
return Result;
}
I am importing one dll to read the blood pressure values from the device. I have try to catch the exception but the control does not go beyond the "if" statement where the access violation exception is coming.
Kindly Suggest?
Thanks
Handling of AccessViolationExceptions and other corrupted state exceptions has been changed in .NET 4. Generally you should not catch these exceptions, so the runtime has been changed to reflect this. If you really need to catch these, you must annotate the code with the HandledProcessCorruptedStateExceptions attribute.
Please keep in mind, that the behavior was changed with good reason. Most applications will not be able to handle these exceptions in any meaningful way and thus should not catch them.
its HandleProcessCorruptedStateExceptions not HandleDProcessCorruptedStateExceptions

Resources