java.util.ConcurrentModificationException Exception error - java

i am trying to make a java application with GUI.
i am writing a code that i want to let the User change some data and save these changes on a text file. Before doing that i want to delete the old data that is changed from a list and then rewrite the new data with the last change.if i am missing any class you wanted to see please tell me i will put it online as fast as possible
this is my
public void saveChanges(footBall Player, String name, String level,
int[] scores, int footSize) {
try {
if (CompetitorsList.size() != 0) {
for (Competitors C : CompetitorsList) {
if (C instanceof footBall) {
String Number = Player.playerNumber + "";
if (C.getPlayerNumberAsString().equals(Number)) {
System.out.println("c");
//the error hit me here when i try to remove the object from the list the exception error is java.util.ConcurrentModificationException
CompetitorsList.remove(C);
}
}
}
Name NewName = new Name(name);
System.out.println("Please get in2");
footBall NewPlayer = new footBall(Player.playerNumber, scores,
level, footSize, NewName);
CompetitorsList.add(NewPlayer);
SaveOnFile();
} else {
System.out.println("No List");
}
} catch (Exception ex) {
System.out.print("testing4");
System.out.print("something wrong" + ex);
}
}
this is the SaveOnFile method:
public void SaveOnFile() {
String scoresInString;
FileWriter fw;
try {
fw = new FileWriter("footBall");
for (Competitors C : CompetitorsList) {
if (C instanceof footBall) {
footBall Scores = new footBall();
scoresInString = Scores.returnScoreAsString(C.scores);
fw.write(C.playerNumber + ", " + C.name.getFullName()
+ ", " + C.level + ", " + scoresInString + ","
+ ((footBall) C).footSize() + "\n");
fw.write("\r\n");
}
}
fw.close();
}
// message and stop if file not found
catch (FileNotFoundException fnf) {
System.out.println("File not found ");
System.exit(0);
}
// stack trace here because we don't expect to come here
catch (IOException ioe) {
ioe.printStackTrace();
System.exit(1);
}
}

Calling remove() on a collection invalidates all active iterator. Instead, you have to use the Iterator.remove() method:
for(Iterator<Competitors> it = CompetitorsList.iterator(); it.hasNext(); ) {
Competitors C = it.next();
if(C instanceof ...) {
if(C.getPlayerNumberAsString().equals(Number))
it.remove();
...
This way, the iterator() knows about how the collection changes, which otherwise wouldn't be possible since the ArrayList doesn't track the Iterators it generated.

Alternatively, if you want to use the same "for-next" syntax and not change to the Iterator syntax, collect all the objects to be removed into a temporary collection. e.g.
ArrayList<Competitors> removeThese = new ArrayList<Competitors>();
for (Competitors C : CompetitorsList) {
if (wantToRemove(C)) // your number logic goes here...
removeThese.add(C);
}
CompetitorsList.removeAll(removeThese);

Related

infinite loop stuck and having problem with code in java

the task at hand is to make a Blood Transfusion Manager application that efficiently chooses donors for blood transfusion.
When the application is launched it should try to open two files: “donors.txt” and “recipients.txt”. If one of the files is missing the program should announce the problem and exit. Both files should be formatted in the following way: each row should contain a person’s full name and their blood type separated by semicolon. The program should first read donors.txt, split each line into name and blood type and store the resulting array as a new element in a donors arraylist. It should also print the list on the screen and check that each person’s blood type is valid. If an invalid blood type is found that entry should not be added to the arraylist and the user should be notified which entry had a problem. Recipients should then be read, processed and stored (in recipients arraylist) in a similar manner this is part one of the task
this is my previous code and after updating it more to get closer to the end of my task i found that the code stopped work i debugged it and found that it is stuck in an infinite loop not sure how to fix it to or if there any other way to rewrite it to work maybe not using a while loop
package java_assigment_4;
import java.io.*;
import java.util.*;
public class java_assigment_4 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner file_donors;
Scanner file_recp;
ArrayList list_donors = new ArrayList();
ArrayList list_recp = new ArrayList();
String blood_type = "o- o+ a- a+ b- b+ ab- ab+";
try
{
file_donors = new Scanner(new FileReader("donors.text"));
while (file_donors.hasNextLine())
{
list_donors.add(file_donors.nextLine()); // store donors names & blood type in array list
}//end while
file_donors.close();
}//end try
catch (FileNotFoundException e)
{
System.out.println("Error: " + e.getMessage());
}//end catch
try
{
file_recp = new Scanner(new FileReader("recipients.text"));
while (file_recp.hasNextLine())
{
list_recp.add(file_recp.nextLine()); // store recipents names & blood type in array list
}//end while
file_recp.close();
}//end try
catch (FileNotFoundException e)
{
System.out.println("Error: " + e.getMessage());
}//end catch
System.out.println("donors " + list_donors);
System.out.println("\n");
System.out.println("recipents " + list_recp);
// for (int i=0;i<list_donors.size();i++) {
// list_donors.contains(";"); // need a substring to store type after ;
}
}
}
this code below is the lastest code and is the one that is not working
public class java_assigment_4 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner file_donors;
Scanner file_recp;
ArrayList<String> list_donors = new ArrayList<String>();
ArrayList<String> list_recp = new ArrayList<String>();
String [] blood_type = {"o-","o+","a-","a+","b-","b+","ab-","ab+"};
try
{
file_donors = new Scanner(new FileReader("donors.txt"));
while (file_donors.hasNextLine())
{
for (int i=0;i<list_donors.size();i++) {
String donor=list_donors.get(i);
String type =donor.substring((donor.indexOf(";") + 1)); // look for ; and stores info after witch is the blood type into a substring so i can use for checking if vaild
type=type.trim();
for (int z=0;z<blood_type.length;z++) {
if (type.equals(blood_type [z])) { compares the two lists
list_donors.add(file_donors.nextLine()); // store donors names & blood if vaild type in array list
}
else {
System.out.println( "this person with blood;" + type + " is not valid ");
}
}
}
}
file_donors.close();
}
catch (FileNotFoundException e)
{
System.out.println("Error: " + e.getMessage());
}
System.out.println("donors " + list_donors);
try
{
file_recp = new Scanner(new FileReader("recipients.txt"));
while (file_recp.hasNextLine())
{
for (int i=0;i<list_recp.size();i++) {
String recp=list_recp.get(i);
String type =recp.substring((recp.indexOf(";") + 1));
type=type.trim();
for (int z=0;z<blood_type.length;z++) {
if (type.equals(blood_type [z])) { // compares the two lists
list_recp.add(file_recp.nextLine()); // store recp names & blood type if vaild in array list
}
else {
System.out.println( "this person with blood ;" + type + " is not valid ");
}
}
}
}
file_recp.close();
}
catch (FileNotFoundException e)
{
System.out.println("Error: " + e.getMessage());
}
// System.out.println("donors " + list_donors);
// System.out.println("\n");
// System.out.println("recipents " + list_recp);
}
}
The list_donors.size() will always return 0,
cause the list_donors is empty when it begins
so the code never call file_donors.nextLine()
and file_donors.hasNextLine() will be always true
public class java_assigment_4 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner file_donors;
Scanner file_recp;
ArrayList<String> list_donors = new ArrayList<String>();
ArrayList<String> list_recp = new ArrayList<String>();
String [] blood_type = {"o-","o+","a-","a+","b-","b+","ab-","ab+"};
try
{
file_donors = new Scanner(new FileReader("donors.txt"));
// file_donors.hasNextLine() always true in your code
while (file_donors.hasNextLine())
{
// list_donors.size() will return 0, cause the list_donors is empty when it begins
// so the code never enter this for and never call file_donors.nextLine()
for (int i=0;i<list_donors.size();i++) {
...
}
}
you can avoid this kind of situation doing something like
while (file_donors.hasNextLine())
{
string current_line = file_donors.hasNextLine();
updating with some code to help
import java.io.*;
import java.util.*;
public class Blood
{
public static void main(String[] args)
{
ArrayList<String> list_donors = new ArrayList<String>();
ArrayList<String> list_recp = new ArrayList<String>();
System.out.println("Starting!");
copyFromFile("/home/mitz/stackoverflow/java/Donors.txt", list_donors);
System.out.println("imported "+ list_donors.size() + " registers");
copyFromFile("/home/mitz/stackoverflow/java/Receptors.txt", list_recp);
System.out.println("imported "+ list_recp.size() + " registers");
System.out.println("Finished!");
}
public static void copyFromFile(String filename, ArrayList<String> listDestiny)
{
Scanner fileScanner;
FileReader fileReader;
try
{
fileReader = new FileReader(filename);
fileScanner = new Scanner(fileReader);
while (fileScanner.hasNextLine())
{
String currentLine = fileScanner.nextLine();
String type = currentLine.substring((currentLine.indexOf(";") + 1));
if(isValidBloodType(type))
{
listDestiny.add(currentLine);
System.out.println("Imported: " + currentLine);
}else{
System.out.println("Invalid blood type!! Alien detected with blood type: " + type);
}
}
fileScanner.close();
}
catch (FileNotFoundException e)
{
System.out.println("Arquivo não encontrado");
}
}
public static Boolean isValidBloodType(String type)
{
String[] blood_type = {"o-", "o+", "a-", "a+", "b-", "b+", "ab-", "ab+"};
return Arrays.asList(blood_type).contains(type);
}
}

100 records at a time to udf

I have to pass record to an UDF which calls an API but as we want to do it parallely,we are using spark and thats why UDF is being developed, the problem here is that that UDF needs to take only 100 records at a time not more than that, it can't handle more than 100 records parallely, so how to ensure that only 100 record pass to it in one go please note we don't want to use count() function on whole record.
I am attaching the UDF code here,it's a generic UDF which returns array of struct.moreover if we pass 100 records in batchsize variable each time then,if suppose there are 198 records then if as we dont want to use count() we will not be knowing that its last batchsize is going to be 98.so how to handle that thing.
Guys... I have a generic UDF in which call is made for an API but before calling it creates batch of 100 firstly then only call restapi.. So the argument UDF takes are x1:string, x2:string, batchsize:integer(currently the batchsize is 100)..so in UDF until and unless the batchsize is not 100 the call will not happen.. And for each record it will return null.
So till 99th record it will return. Null but at 100th record the call will happen
[So, now the problem part:as we are taking batchsize 100 and call will take place only at 100th record. So, in condition like if we have suppose 198 record in file then 100 record will get the output but, other 98 will only return null as they will not get processed..
So please help a way around, and UDF take one record at a time, but it keep on collecting till 100th record.. I hope this clears up
public class Standardize_Address extends GenericUDF {
private static final Logger logger = LoggerFactory.getLogger(Standardize_Address.class);
private int counter = 0;
Client client = null;
private Batch batch = new Batch();
public Standardize_Address() {
client = new ClientBuilder().withUrl("https://ss-staging-public.beringmedia.com/street-address").build();
}
// StringObjectInspector streeti;
PrimitiveObjectInspector streeti;
PrimitiveObjectInspector cityi;
PrimitiveObjectInspector zipi;
PrimitiveObjectInspector statei;
PrimitiveObjectInspector batchsizei;
private ArrayList ret;
#Override
public String getDisplayString(String[] argument) {
return "My display string";
}
#Override
public ObjectInspector initialize(ObjectInspector[] args) throws UDFArgumentException {
System.out.println("under initialize");
if (args[0] == null) {
throw new UDFArgumentTypeException(0, "NO Street is mentioned");
}
if (args[1] == null) {
throw new UDFArgumentTypeException(0, "No Zip is mentioned");
}
if (args[2] == null) {
throw new UDFArgumentTypeException(0, "No city is mentioned");
}
if (args[3] == null) {
throw new UDFArgumentTypeException(0, "No State is mentioned");
}
if (args[4] == null) {
throw new UDFArgumentTypeException(0, "No batch size is mentioned");
}
/// streeti =args[0];
streeti = (PrimitiveObjectInspector)args[0];
// this.streetvalue = (StringObjectInspector) streeti;
cityi = (PrimitiveObjectInspector)args[1];
zipi = (PrimitiveObjectInspector)args[2];
statei = (PrimitiveObjectInspector)args[3];
batchsizei = (PrimitiveObjectInspector)args[4];
ret = new ArrayList();
ArrayList structFieldNames = new ArrayList();
ArrayList structFieldObjectInspectors = new ArrayList();
structFieldNames.add("Street");
structFieldNames.add("city");
structFieldNames.add("zip");
structFieldNames.add("state");
structFieldObjectInspectors.add(PrimitiveObjectInspectorFactory.writableStringObjectInspector);
structFieldObjectInspectors.add(PrimitiveObjectInspectorFactory.writableStringObjectInspector);
structFieldObjectInspectors.add(PrimitiveObjectInspectorFactory.writableStringObjectInspector);
structFieldObjectInspectors.add(PrimitiveObjectInspectorFactory.writableStringObjectInspector);
StructObjectInspector si2 = ObjectInspectorFactory.getStandardStructObjectInspector(structFieldNames,
structFieldObjectInspectors);
ListObjectInspector li2;
li2 = ObjectInspectorFactory.getStandardListObjectInspector(si2);
return li2;
}
#Override
public Object evaluate(DeferredObject[] args) throws HiveException {
ret.clear();
System.out.println("under evaluate");
// String street1 = streetvalue.getPrimitiveJavaObject(args[0].get());
Object oin = args[4].get();
System.out.println("under typecasting");
int batchsize = (Integer) batchsizei.getPrimitiveJavaObject(oin);
System.out.println("batchsize");
Object oin1 = args[0].get();
String street1 = (String) streeti.getPrimitiveJavaObject(oin1);
Object oin2 = args[1].get();
String zip1 = (String) zipi.getPrimitiveJavaObject(oin2);
Object oin3 = args[2].get();
String city1 = (String) cityi.getPrimitiveJavaObject(oin3);
Object oin4 = args[3].get();
String state1 = (String) statei.getPrimitiveJavaObject(oin4);
logger.info("address passed, street=" + street1 + ",zip=" + zip1 + ",city=" + city1 + ",state=" + state1);
counter++;
try {
System.out.println("under try");
Lookup lookup = new Lookup();
lookup.setStreet(street1);
lookup.setCity(city1);
lookup.setState(state1);
lookup.setZipCode(zip1);
lookup.setMaxCandidates(1);
batch.add(lookup);
} catch (BatchFullException ex) {
logger.error(ex.getMessage(), ex);
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
/* batch.add(lookup); */
if (counter == batchsize) {
System.out.println("under if");
try {
logger.info("batch input street " + batch.get(0).getStreet());
try {
client.send(batch);
} catch (Exception e) {
logger.error(e.getMessage(), e);
logger.warn("skipping current batch, continuing with the next batch");
batch.clear();
counter = 0;
return null;
}
Vector<Lookup> lookups = batch.getAllLookups();
for (int i = 0; i < batch.size(); i++) {
// ListObjectInspector candidates;
ArrayList<Candidate> candidates = lookups.get(i).getResult();
if (candidates.isEmpty()) {
logger.warn("Address " + i + " is invalid.\n");
continue;
}
logger.info("Address " + i + " is valid. (There is at least one candidate)");
for (Candidate candidate : candidates) {
final Components components = candidate.getComponents();
final Metadata metadata = candidate.getMetadata();
logger.info("\nCandidate " + candidate.getCandidateIndex() + ":");
logger.info("Delivery line 1: " + candidate.getDeliveryLine1());
logger.info("Last line: " + candidate.getLastLine());
logger.info("ZIP Code: " + components.getZipCode() + "-" + components.getPlus4Code());
logger.info("County: " + metadata.getCountyName());
logger.info("Latitude: " + metadata.getLatitude());
logger.info("Longitude: " + metadata.getLongitude());
}
Object[] e;
e = new Object[4];
e[0] = new Text(candidates.get(i).getComponents().getStreetName());
e[1] = new Text(candidates.get(i).getComponents().getCityName());
e[2] = new Text(candidates.get(i).getComponents().getZipCode());
e[3] = new Text(candidates.get(i).getComponents().getState());
ret.add(e);
}
counter = 0;
batch.clear();
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
return ret;
} else {
return null;
}
}
}

while loop needs to continue

I have this code
static String sCurrentLine = null;
/* keyword */
static String keyword = null;
Scanner keywordFile = null, siteFile = null;
try {
keywordFile = new Scanner(new File("/home/mearts/keywords.txt"));
siteFile = new Scanner(new FileReader(fileChooser.getSelectedFile()));
sCurrentLine = siteFile.nextLine().trim();
keyword = keywordFile.nextLine().trim();
while (sCurrentLine != null){
while (keywordFile.hasNext() || keyword == null) {
System.out.println("Line--> " + keyword);
System.out.println("Current here >>" + sCurrentLine);
if (sCurrentLine.contains(keyword)) {
System.out.println("Found it-->> " + keyword);
keyword = keywordFile.nextLine();
System.out.println("next keyword " + keyword);
///* reset search to top of site file */
siteFile = new Scanner(new
FileReader(fileChooser.getSelectedFile()));
sCurrentLine = siteFile.nextLine().trim();
}
else {
sCurrentLine = siteFile.nextLine();
if (sCurrentLine == null) {
break;
}
if (!sCurrentLine.matches(keyword)){
System.out.println("The following keyword " + keyword + " does not exist in file "
+ fileChooser.getSelectedFile());
}
}
} //2nd while loop
}
}
catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
siteFile.close();
keywordFile.close();
}
and i have a text file called keywords which has a list of keywords in it,
but my logic is off an I cannot figure out why.
I think I may need to run the loop one last time but not sure how to do that
My issue is that the last word in the keyword file never gets read in. so the program stops at the 2nd to last element in the text file.
I am not sure that I understand what your code should do.
If I understood correctly your code, your task is to read keywords from a file with keywords and then find all keywords in another file. Is it correct?
You should separate reading keywords from the file and search for them in the file. You should 'load' keywords in a list and then search through the file.
To load keywords in list
keywordFile = new Scanner(new File("/home/mearts/keywords.txt"));
List<String> keywordsList = new ArrayList<>();
while (keywordFile.hasNextLine()) {
keywordsList.add(keywordFile.nextLine());
}
And to search for keywords in the file
siteFile = new Scanner((Readable) new FileReader(fileChooser.getSelectedFile()));
while (siteFile.hasNextLine()) {
String sCurrentLine = siteFile.nextLine().trim();
for (String keyword : keywordsList) {
if (sCurrentLine.contains(keyword)) {
System.out.println("Found it-->> " + keyword);
break;
}
}
System.out.println(
"The following keyword " + keyword + " does not exist in file " + fileChooser.getSelectedFile());
}
I hope this will help :)

Strange bug while using import com.sun.net.httpserver.HttpExchange and HTTPserver in java

I'm currently working on a "big" project, and I'm facing a incomprehensible bug. This one is just beyond my competence.
I will try to be as clear as possible, because there is a lot of code, I'll try to show you some screenshots of the debug intereface (breakpoint).
Basically, this is a program about surveys, admins can create surveys, users can answer them.. basic.
I'm doing it in java, using a HttpServer which creates a lot of contexts, (html pages) using the createContext method .
I'm also using a RMI object to manage the surveys and the results.
I have written a form for an admin to create a new survey, using the post method, i post it to another page so as to process the query.
Once I have done that, I have three variables to create a new survey : an id, a title, an array of questions, and an integer to say if the survey will be visible for the user or not. Note: I am 100% sure that those variables are correct
(Sorry for the french words in the code / screens, I'll try to rename most of them)
ISurveyManagement test = (ISurveyManagement)Naming.lookup("rmi://localhost/surveys");
I get my RMI object,
test.addSurvey(nsondage, titre, questions, 1);
Then I call my method to add the survey. (of course, all of those instruction are in the Handle method, from the interface HttpHandler)
This is what happens after the break point :
I have clicked on my button, the title has been correctly printed
Same thing for the RMI object, not null or anything, Then, we are supposed to go into the method of the RMI object:
But we are here!!! ServerImpl ExChange run?? what!! I pass a few steps
I passed all the step of the third picture, now we are again in the beggining of the Handle method?? why? and what about my call of addSurvey??
If I pass again a lot of steps, you will see that "HELLO", my title, and the RMI object will be printed again, then instead of going into my method it goes int that Thread-2 thing again and then crash...
I'm really sorry for this big ugly question, but I'm completly lost, I'm searching for hour ><
Thank you so much by advance if you can help me
EDIT:
this is the addSurvey method:
#Override
public void addSurvey(int n, String title, ArrayList<Question> q, int active) throws RemoteException {
System.out.println("anything");
this.loadSurveys();
this.objSurveys.add(new Survey(n, title, q, active));
this.saveSurveys();
}
The sysout at the begining is not displayed, I'm sure that the methods load and save work perfectly, I'm using them in an other functionnality.
EDIT2: as you asked, this is the code of the whole class test
public class CreationManagement implements HttpHandler {
#Override
public void handle(HttpExchange t) throws IOException {
String reponse =
"<html>"
+"<head>"
+ "<title>Page admin</title>"
+"<meta http-equiv=\"content-type\" content=\"text/plain; charset=utf-8\"/>"
+"</head>"
+"<body style=\"font-family: Georgia, Times, serif;padding:20px;width:400px;border:1px solid #172183;\">"
+"<p style=\"text-align:center;padding:5px;color:white;background:#172183;\">Vos changements ont bien été pris en compte!</p>"
+ "<form action=\"http://localhost:8080/admin.html\">"
+ "<button style=\"border: none;color: #ffffff;display: block;margin: auto;background: #172183;padding: 5px 20px;cursor:pointer;\">Retour</button>"
+ "</form>";
URI requestedUri = t.getRequestURI();
String query = requestedUri.getRawQuery();
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(t.getRequestBody(),"utf-8"));
} catch(UnsupportedEncodingException e) {
System.err.println("Error flow" + e);
System.exit(-1);
}
try {
query = br.readLine();
} catch(IOException e) {
System.err.println("Error while reading line " + e);
System.exit(-1);
}
/*String [] p = query.split("&");
for (int i = 0 ; i < p.length ; i++) {
reponse += p[i] + "<br>";
}*/
ISurveyManagement test = null;
try {
test = (ISurveyManagement)Naming.lookup("rmi://localhost/sondages");
} catch(NotBoundException e) {
System.err.println("Error while getting rmi object : " + e);
System.exit(-1);
} catch(MalformedURLException e) {
System.err.println("URL mal forme : " + e);
System.exit(-1);
} catch(RemoteException e) {
System.err.println("not possible to get rmi obj : " + e);
System.exit(-1);
}
test.loadSurveys();
int length = test.getSurveys().size();
int nsurvey= length + 1;
String[] op = query.split("&");
String title = op[0].split("=")[1];
String[] params = Arrays.copyOfRange(op, 1, op.length);
/*for (int a = 0 ; a < params.length ; a++) {
System.out.println(a + " " +params[a]);
}*/
ArrayList<Question> questions = new ArrayList<Question>();
//System.out.println("taille " + params.length );
for (int i = 0 ; i < params.length ; i++) {
if (i%5 == 0) {
String[] detQ = params[i].split("=");
int nq = Integer.parseInt(detQ[0].substring(1, detQ[0].length()));
String libq = detQ[1];
Question q = new Question(nq, libq, nsondage);
q.setReponses(new ArrayList<Reponse>());
questions.add(q);
} else {
String[] detR = params[i].split("=");
if (detR.length == 2) {
String lib = detR[1];
int q = Integer.parseInt(detR[0].split("_")[0]);
int num = Integer.parseInt(detR[0].split("_")[1]);
String l = "";
if (num == 1) {
l = "A";
} else if (num == 2) {
l = "B";
} else if (num == 3) {
l = "C";
} else if (num == 4) {
l = "D";
}
Reponse r = new Reponse(l, lib, q, nsondage);
questions.get(q-1).getReponses().add(r);
}
}
}
System.out.println("HELLO");
System.out.println(title);
System.out.println(test);
//Survey s = new Survey(nsurvey, title, questions, 1);
test.addSurvey(nsurvey, title, questions, 1);
//System.out.println(s.display());
System.out.println(nsurvey);
reponse += "</body></html>";
try {
Headers h = t.getResponseHeaders();
h.set("Content-Type", "text/html; charset=utf-8");
t.sendResponseHeaders(200, 0);
} catch(IOException e) {
System.err.println("error while sending header : " + e);
System.exit(-1);
}
try {
OutputStream os = t.getResponseBody();
os.write(reponse.getBytes());
os.close();
} catch(IOException e) {
System.err.println("error sending corps : " + e);
}
}
}
Is I said the survey is displayed correctly when I try to display it, the object is correctly created.

Method that returns null is causing java.lang.NullPointerException

I wrote this method:
#Override
protected String call() {
if (list != null) {
int s = list.size();
Metadata metadata;
for (int i = 0; i < s; i++) {
try {
File f = list.get(i);
metadata = ImageMetadataReader.readMetadata(f);
// obtain the Exif directory
ExifSubIFDDirectory directory = metadata.getDirectory(ExifSubIFDDirectory.class);
// query the tag's value
Date date = directory.getDate(ExifSubIFDDirectory.TAG_DATETIME_ORIGINAL);
if (date != null) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
System.out.println("File: " + f.getAbsolutePath() + "\tDATETIME_ORIGINAL: " + sdf.format(date));
} else {
System.out.println("File: " + f.getAbsolutePath() + "\tDATETIME_ORIGINAL: no data!");
}
} catch (Exception ex) {
ex.printStackTrace();
System.out.println("Error: " + ex.getLocalizedMessage());
} finally {
updateProgress(i + 1, s);
}
}
}
return null;
}
Method directory.getDate(ExifSubIFDDirectory.TAG_DATETIME_ORIGINAL) can sometimes return null:
Source
Problem is that by just calling that method java throws Null Pointer Exception, so I cannot test it with date!=null. NetBeans also reports "Dereferencing possible null pointer" hint. I do not understand why this happens. Why I'm not able to store null value in some object and test it? Even if I don't store value in variable, that method still causes the same exception when returning null.
One solution to this problem would be using another catch statement for NullPointerException, then calling the code you would call if the Date was null. You would also have to move variable "File f" out of the try-statement block to ensure access in the catch.
Example,
catch(NullPointerException e) {
System.out.println("File: " + f.getAbsolutePath() + "\tDATETIME_ORIGINAL: no data!");
}

Categories

Resources