Java strange issue changing string [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I've tried searching for this, but then I'm not sure when how to describe it.
I have a method that formats some data from a hashmap to go into a mySQL table:
private String valuesList() {
String valuesList = "";
HashMap<String,String> data = getData();
for(Map.Entry<String, String> entry : data.entrySet()) {
String value=entry.getValue();
valuesList+="'"+value+"',";
}
valuesList = valuesList.substring(0, valuesList.length() - 1);
return valuesList;
}
Most of the time that works fine, but in some cases one of the values has an apostrophe in, which leads to an output like this:
'4577314','18-02-2017','null','4566974','null','Overseas Domestic Workers' Rights Bill','1124','null'
Note the 'Overseas Domestic Workers' Rights Bill' bit at the end. I thought that would be easy to fix by changing
valuesList+="'"+entry.getValue()+"',";
to
valuesList+="'"+entry.getValue().replace("'","")+"',";
but the method now throws a null pointer exception at that line. In fact any kind of change to that string such as .trim() does the same, throwing a null.
I'm completely stumped now

You can escape quotes from value like this
value = value.replaceAll("'","''");

Related

How can I rewrite null checks with optional in a better way [duplicate]

This question already has an answer here:
Java 8 avoiding null pointer checks using Optional
(1 answer)
Closed 1 year ago.
I am having a small snippet of code. I would like to write it in a better way with fewer nested checks. How can I achieve it?
Item item = itemResponse.getItem();
Optional<Item> optionalItem = Optional.ofNullable(item);
if (optionalItem.isPresent()) {
List<NameValue> listValues = item.getValues();
Optional<List<NameValue>> optionalListValues = Optional.ofNullable(listValues);
if (optionalListValues.isPresent()) {
System.out.println(listValues);
}
}
Is there any concise way I can rewrite the above piece of code using Java 8?
You can make itemResponse.getItem() class to return Optional<Item> and use the chained map method which will executed only if Optional has value, and if map method return non null value then only final ifPresent(Consumer consumer) is executed
Optional<Item> item = itemResponse.getItem()
item.map(item::getValues)
.ifPresent(System.out::println);

Why null is not equal to null? [duplicate]

This question already has answers here:
How to compare null value from the JsonObject in java
(7 answers)
Closed 3 years ago.
I dont understand what is happening in my application. I'm sending PUT request with updates from Angular project to java api. I have a method that validates query parameters from the put request, the method looks like this:
private JsonObject validateRequestBody(JsonElement requestBody) {
if (!(requestBody instanceof JsonObject)) {
throw new IllegalArgumentException("Request body cannot be case to JSON object");
}
JsonObject bodyObj = requestBody.getAsJsonObject();
System.out.println(bodyObj.get("entityIri").equals(null));
if (bodyObj.get("entityIri") == null) {
System.out.println("null");
throw new IllegalArgumentException("Request body must contain entity IRI");
}
return bodyObj;
}
As you can see, I'm just trying to check if the enityIri paramter is equal to null. To test it, Im sending null as entityIri from Angular project. I tried to compare them with equal method and with ==, but in both cases the output is always false. Could someone explain me why they are not equal? Is it because I'm passing it to JsonObject?
I attach a screenshot from debugging (I cut out irrelevant parts).
Try to use isJsonNull method:
provides check for verifying if this element represents a null value
or not.
if (bodyObj.get("entityIri").isJsonNull()) {
...
}
Of course, you need to check whether bodyObj.get("entityIri") is not null before. I did not add it statement to make statement clear.

Streams: Avoid NullPointerException [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I have to get the first element of an array., but it is possible that the element is empty; If the element is empty I put an empty field (I am trying to generate a pdf)
Here is my code now:
public void makePdf(Long id) throws IOException {
Candidacy ca = candidacyRepository.findOne(id);
cos.beginText();
cos.showText(
ca.getInterviews().stream().map(Interview::getAgency).map(Agency::getAgencyName).collect( Collectors.toList()).get(0)!=null?ca.getInterviews().stream().map(Interview::getAgency).map(Agency::getAgencyName).collect( Collectors.toList()).get(0):""));
cos.endText();
}
So I will wish not to prevent the generation of the pdf.
Thank you very much for your support!
UPDATE
Sorry for the lack of precision:
I also sort on the date.
public void makePdf(Long id) throws IOException {
Candidacy ca = candidacyRepository.findOne(id);
cos.beginText();
cos.showText(
ca.getInterviews().stream().sorted((a,b)-> a.getInterviewDate().compareTo(b.getInterviewDate())).sorted((a,f)->f.getInterviewDate().compareTo(a.getInterviewDate())).sorted((b,f)->b.getInterviewDate().compareTo(f.getInterviewDate())).map(Interview::getAgency).map(Agency::getAgencyName).collect( Collectors.toList()).get(0)!=null?ca.getInterviews().stream().sorted((a,b)-> a.getInterviewDate().compareTo(b.getInterviewDate())).sorted((a,f)->f.getInterviewDate().compareTo(a.getInterviewDate())).sorted((b,f)->b.getInterviewDate().compareTo(f.getInterviewDate())).map(Interview::getAgency).map(Agency::getAgencyName).collect( Collectors.toList()).get(0):""));
cos.endText();
}
I get a NullPointerException:/
Thank you for you help
This code doesn't make sense. You are executing the same Stream pipeline twice, and each time you generate an entire List when you only need the first element of that List.
You can use findFirst to get the first element of the Stream.
EDIT :
After testing my original answer, it turned out it doesn't work. findFirst() throws a NullPointerException if the first element is null.
You can avoid that by setting the default value before calling findFirst() :
ca.getInterviews().stream()
.map(Interview::getAgency)
.map(Agency::getAgencyName)
.map(s->s!=null?s:"") // this will replace null with ""
.firstFirst()
.get();

how to get a component by name in java [duplicate]

This question already has answers here:
Get a Swing component by name
(8 answers)
Closed 6 years ago.
here is the edited code with specified method.
String value = obj.validateTextFields(txtFields);
public String validateTextFields(JTextField[] txtField){
String res = "";
for(JTextField txtFields : txtField) {
if(txtFields.getText().equals("") ) {
JOptionPane.showMessageDialog(null, txtFields.getName() +" is empty!");
res +=txtFields.getName()+",";
}
}
return res;
value is the names of text fields so how to get the text field by this name.
If you want to associate an object with a String for easy retrieval, one simple way is to use a Map<String, JTextField> with a concrete implementation as a HashMap<String, JTextField>.
Then in your initialization code, you place the components in the map with their associated String using the Map's put(...) method, and later when you want to retrieve it, use the Map's get(...) method.

To use a string value as a variable name [duplicate]

This question already has answers here:
Get variable by name from a String
(6 answers)
Closed 6 years ago.
Is it possible to use String as a variable name.. like in this example -
String musicPlaying = "music2";
Music music1 = new Music("blaalla");
Music music2 = new Music("blalala");
Music music3 = new Music("balaada");
if(!musicPlaying.stillPlaying) { // As you can see i am using string as a variable name.
changeMusic();
}
What you can do is by associating (mapping) those values to the Music object. Here is example:
Map<String, Music> musics = new HashMap<>();
String musicPlaying = "music2";
musics.put("music1", new Music("blaalla"));
musics.put("music2", new Music("blalala"));
musics.put("music3", new Music("balaada"));
if(!musics.get(musicPlaying).stillPlaying) { // As you can see i am using string as a variable name.
changeMusic();
}
You can't do this in Java, but you can almost do it using a map.
Map<String, Music> map = new HashMap<String, Music>();
map.put("music1", music1);
map.put("music2", music2);
map.put("music3", music3);
if(map.get(musicPlaying).stillPlaying) {
// happy listening
}
No, this is not supported in Java.
stillPlaying doesn't exist as a method (or variable) on String.
As the comment suggests below, it probably is doable through some reflection, however to quote another comment...
You can do all kinds of stupid tricks with reflection. But you're
basically breaking the "warranty void if removed" sticker on the class
the instant you do it.
No. But you might want to look into using a Map instead.
I used a switch case.
Switch (string)
{
case "string1":
string1();
break;
case "string2":
string2();
break;
}

Categories