NullPointerException for statement - nullpointerexception

public void loadFileRecursiv(String pathDir)
{
File fisier = new File(pathDir);
File[] listaFisiere = fisier.listFiles();
for(int i = 0; i < listaFisiere.length; i++)
{
if(listaFisiere[i].isDirectory())
{
loadFileRecursiv(pathDir + File.separatorChar + listaFisiere[i].getName());
}
else
{
String cuExtensie = listaFisiere[i].getName();
String nume = cuExtensie.split(".")[0];
String acronimBanca = nume.split("_")[0];
String tipAct = nume.split("_")[1];
String dataActString = nume.split("_")[2];
//Date dataAct = new SimpleDateFormat("dd-MM-yyyy").parse(dataActString);
//String denBanca = inlocuireAcronim(acronimBanca);
insertData(listaFisiere[i], cuExtensie, acronimBanca, tipAct, dataActString);
//fisiere[i].renameTo(new File("u02/ActeConstitutive/Mutate"));
}
}
}
I have a simple code that checks all files and folders recursevely when a path is given. Unfortunately, i have a NULLPOINTEREXCEPTION for for(int i = 0; i < listaFisiere.length; i++) this line. What can be the problem? Thank you!

check whether listaFisiere is null or not
If not null, change this line as for(int i = 0; i < listaFisiere.length(); i++)
and
you can change your code as below
for(File path:listaFisiere)
{
if(path.isDirectory())
{
loadFileRecursiv(pathDir + File.separatorChar + path.getName());
}
else
{
String cuExtensie = path.getName();
String nume = cuExtensie.split(".")[0];
String acronimBanca = nume.split("_")[0];
String tipAct = nume.split("_")[1];
String dataActString = nume.split("_")[2];
//Date dataAct = new SimpleDateFormat("dd-MM-yyyy").parse(dataActString);
//String denBanca = inlocuireAcronim(acronimBanca);
insertData(path, cuExtensie, acronimBanca, tipAct, dataActString);
//fisiere[i].renameTo(new File("u02/ActeConstitutive/Mutate"));
}
}

Related

Saving ArrayList<Uri> in SharedPreferences and retrieving

I am trying to save multiple images into Uri List in SharedPreferences and retrieving them on another activity. I have code here. The error occurs that no adapter attached.
saving :
JSONArray a = new JSONArray();
for (int i = 0; i < uriList.size(); i++) {
a.put(uriList.get(i));
}
String save_form_image = "{\"uri\":\""+a+"\"}";
pref.setStringImage(getApplicationContext(),getTime,save_form_image);
retrieving :
pref = new PreferenceManager();
rv = (RecyclerView) findViewById(R.id.review_image_rv);
uriList = new ArrayList<Uri>();
manager = new LinearLayoutManager(Review.this, manager.HORIZONTAL, false);
rv.setLayoutManager(manager);
rv.setAdapter(image_adapter);
image_adapter = new MultiImageAdapter(uriList,Review.this);
prefs = getSharedPreferences("uri",MODE_PRIVATE);
Collection<?> col_val = prefs.getAll().values();
Iterator<?> it_val = col_val.iterator();
Collection<?> col_key = prefs.getAll().keySet();
Iterator<?> it_key = col_key.iterator();
while (it_val.hasNext() && it_key.hasNext()) {
String value = (String) it_val.next();
String key = (String) it_key.next();
try {
JSONObject jsonObject = new JSONObject(value);
String json = jsonObject.getString("uri");
JSONArray jsonArray = new JSONArray(json);
for(int i = 0; i < jsonArray.length(); i++) {
String a = (String) jsonArray.get(i);
uri = Uri.parse(a);
uriList.add(uri);
image_adapter.addItem(key,uriList);
}
Toast.makeText(getApplicationContext(),"loaded",Toast.LENGTH_SHORT).show();
} catch (JSONException e) {}
image_adapter.notifyDataSetChanged();
}
System.out.println(image_adapter.getItemCount());

Execution gets stuck at date picking functionality of selenium webdriver

I am new to selenium automation, I have written a script to pick check in and check out dates from webpage of tripadvisor.in. I hope the code and xpaths are correct coz out of 7 or 8 executions the scrips successfully running only once. I thought abt synchronization issue and tried adding all types of waits but still the execution getting stuck as calendar. Sometimes stucking at check-in date, sometimes at check-out date but sometimes working fine. Can I get help to sort this issue plz...
public void selectCheckDate(String date, WebElement forwardArrow) {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
try {
Date expectedDate = dateFormat.parse(prop.getProperty(date));
String day = new SimpleDateFormat("dd").format(expectedDate);
String month = new SimpleDateFormat("MMMM").format(expectedDate);
String year = new SimpleDateFormat("yyyy").format(expectedDate);
String expectedMonthYear = month + " " + year;
logger.log(Status.INFO, "Expected Month and year: "+expectedMonthYear);
WebDriverWait wait = new WebDriverWait(driver, 20);
String dd1 = "", dd2 = "";
String d1 = null, d2 = null;
boolean flag1 = false;
boolean flag2 = false;
while (true) {
String displayDate1 = driver.findElement(By.xpath("//*[#class='vr-datepicker-LargeStyles__caption--Srrff']/div")).getText();
String displayDate2 = driver.findElement(By.xpath("(//*[#class='vr-datepicker-LargeStyles__caption--Srrff']/div)[2]")).getText();
if (displayDate1.contains(expectedMonthYear)) {
//addWait();
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 7; j++) {
d1 = "//*[#id='BODY_BLOCK_JQUERY_REFLOW']/div[14]/div/div/div[2]/div/div/div[2]/div[1]/div[3]/div["
+ i + "]/div[" + j + "]";
boolean ex = isElementExists(d1);
if(ex==true) {
dd1 = driver.findElement(By.xpath(d1)).getText();
if (dd1.equals(day)) {
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(d1))).click();
//driver.findElement(By.xpath(d1)).click();
flag1 = true;
break;
}
}
}
if (flag1 == true) {
break;
}
}
if (flag1 == true) {
reportPass("Entered date: "+prop.getProperty(date));
break;
}
} else if (displayDate2.contains(expectedMonthYear)) {
//addWait();
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 7; j++) {
d2 = "//*[#id='BODY_BLOCK_JQUERY_REFLOW']/div[14]/div/div/div[2]/div/div/div[2]/div[2]/div[3]/div["
+ i + "]/div[" + j + "]";
boolean ex1 = isElementExists(d2);
if(ex1==true) {
dd2 = driver.findElement(By.xpath(d2)).getText();
if (dd2.equals(day)) {
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(d2))).click();
//driver.findElement(By.xpath(d2)).click();
flag2 = true;
break;
}
}
}
if (flag2 == true) {
break;
}
}
if (flag2 == true) {
reportPass("Entered date: "+prop.getProperty(date));
break;
}
} else {
forwardArrow.click();
}
}
} catch (ParseException e) {
reportFail(e.getMessage());
}
}

Null pointer exception on Processing (ldrValues)

My code involves both Processing and Arduino. 5 different photocells are triggering 5 different sounds. My sound files play only when the ldrvalue is above the threshold.
The Null Pointer Exception is highlighted on this line
for (int i = 0; i < ldrValues.length; i++) {
I am not sure which part of my code should be changed so that I can run it.
import processing.serial.*;
import processing.sound.*;
SoundFile[] soundFiles = new SoundFile[5];
Serial myPort; // Create object from Serial class
int[] ldrValues;
int[] thresholds = {440, 490, 330, 260, 450};
int i = 0;
boolean[] states = {false, false, false, false, false};
void setup() {
size(200, 200);
println((Object[])Serial.list());
String portName = Serial.list()[3];
myPort = new Serial(this, portName, 9600);
soundFiles[0] = new SoundFile(this, "1.mp3");
soundFiles[1] = new SoundFile(this, "2.mp3");
soundFiles[2] = new SoundFile(this, "3.mp3");
soundFiles[3] = new SoundFile(this, "4.mp3");
soundFiles[4] = new SoundFile(this, "5.mp3");
}
void draw()
{
background(255);
//serial loop
while (myPort.available() > 0) {
String myString = myPort.readStringUntil(10);
if (myString != null) {
//println(myString);
ldrValues = int(split(myString.trim(), ','));
//println(ldrValues);
}
}
for (int i = 0; i < ldrValues.length; i++) {
println(states[i]);
println(ldrValues[i]);
if (ldrValues[i] > thresholds[i] && !states[i]) {
println("sensor " + i + " is activated");
soundFiles[i].play();
states[i] = true;
}
if (ldrValues[i] < thresholds[i]) {
println("sensor " + i + " is NOT activated");
soundFiles[i].stop();
states[i] = false;
}
}
}
You're approach is shall we say optimistic ? :)
It's always assuming there was a message from Serial, always formatted the right way so it could be parsed and there were absolutely 0 issues buffering data (incomplete strings, etc.))
The simplest thing you could do is check if the parsing was successful, otherwise the ldrValues array would still be null:
void draw()
{
background(255);
//serial loop
while (myPort.available() > 0) {
String myString = myPort.readStringUntil(10);
if (myString != null) {
//println(myString);
ldrValues = int(split(myString.trim(), ','));
//println(ldrValues);
}
}
// double check parsing int values from the string was successfully as well, not just buffering the string
if(ldrValues != null){
for (int i = 0; i < ldrValues.length; i++) {
println(states[i]);
println(ldrValues[i]);
if (ldrValues[i] > thresholds[i] && !states[i]) {
println("sensor " + i + " is activated");
soundFiles[i].play();
states[i] = true;
}
if (ldrValues[i] < thresholds[i]) {
println("sensor " + i + " is NOT activated");
soundFiles[i].stop();
states[i] = false;
}
}
}else{
// print a helpful debugging message otherwise
println("error parsing ldrValues from string: " + myString);
}
}
(Didn't know you could parse a int[] with int(): nice!)

Find the largest String in the list

I am required to find the largest string in the ArrayList, and the print it. My code is not currently working though.
public class Solution {
private static List<String> strings;
public static void main(String[] args) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
strings = new ArrayList<String>();
for (int i = 0; i < 5; i++) {
String n = reader.readLine();
strings.add(n);
}
String largestString = strings.get(0);
for (int i = 0; i < strings.size(); i++) {
if (strings.get(i).length() > largestString.length()) {
largestString = strings.get(i);
System.out.println(largestString);
}
}
}
}
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
String value = null;
int length = 0;
for (int i = 0; i < 5; i++) {
String n = reader.nextLine();
if (n != null && n.length() > length) {
length = n.length();
value = n;
}
}
System.out.println("Largest String : " + value + " of length : " + length);
}

parser.getTokens() gives out junk data and singlecharacters PDFBox-1.8.9 version

I am new to pdfbox. I am using pdfbox-app-2.0.0-RC1 version to fetch the entire text from the pdf using PDFTextStripperByArea. Is it possible for me to get each string separately?
For Example,
In the following text,
Nomination : Name&Address
Shipper : shipper name
I need Nomination as seperate string and "Name&Address" as separate string. Instead I am getting each character separately. I have tried with different Pdfs. For most pdfs I am able to get the exact string but for few pdfs I don't.
I am using the following code to get the separate string.
for (PDPage page : doc.getPages()) {
PDFStreamParser parser = new PDFStreamParser(page);
parser.parse();
List<Object> tokens = parser.getTokens();
for (int j = 0; j < tokens.size(); j++) {
Object next = tokens.get(j);
if (next instanceof Operator) {
Operator op = (Operator) next;
if (op.getName().equals("Tj")) {
COSString previous = (COSString) tokens.get(j - 1);
String string = previous.getString();
System.out.println("string1===" + string);
if (string.contains("Plant")) {
int size = al.size();
al.add(string);
stop = false;
continue;
}
if (!string.contains("_") && !stop) {
if (string.contains("Nomination")) {
stop = true;
} else {
al.add(string);
}
}
} else if (op.getName().equals("TJ")) {
COSArray previous = (COSArray) tokens.get(j - 1);
for (int k = 0; k < previous.size(); k++) {
Object arrElement = previous.getObject(k);
if (arrElement instanceof COSString) {
COSString cosString = (COSString)arrElement;
String string = cosString.getString();
System.out.println("string2====>>"+string);
al.add(string);
}
}
}
}
}
}
I am getting the following output:
string2====>>Nom
string2====>>i
string2====>>na
string2====>>t
string2====>>i
string2====>>on
string1===
string2====>>(
string2====>>T
string2====>>o
string1===
string2====>>Loa
string2====>>di
string2====>>ng
string1===
string2====>>Fa
string2====>>c
string2====>>i
string2====>>l
string2====>>i
string2====>>t
string2====>>y
string2====>>)