Nullpointer exception for Long variable [duplicate] - java

This question already has answers here:
Hibernate Parameter value [568903] did not match expected type [java.lang.Long]
(3 answers)
Closed 9 years ago.
I have the following code
private Long projectNumber; // with getters and setters
and when I am checking whether projectNumber is null or not, I am getting null pointer exception at the if condition
if(selected.getProjectNumber()!=null){
// do something
}
What could be the reason for this even though Long is a wrapper class.
If I change projectNumber from Long to String, it works fine.
Update 1
private Project selected = new Project();
public Project getSelected() {
return selected;
}
public void setSelected(Project selected) {
this.selected = selected;
}
I am getting selected value in ManagedBean of JSF in the following method
public void onRowSelect(SelectEvent event) {
}
projectNo getters and setters
public Long getProjectNo() {
return projectNo;
}
public void setProjectNo(Long projectNo) {
this.projectNo = projectNo;
}

The problem you have is because selected is null, projectNumber. Change the check to something like:
if(selected != null && selected.getProjectNumber()!=null){
// do something
}
Or alternatively add a separate check for selected above.

If you get an NPE here:
if(selected.getProjectNumber()!=null){
and all getProjectNumber() does is return projectNumber, this strongly indicates that selected is null.

the problem is that selected is null. Check it like:
if(selected != null && selected.getProjectNumber()!=null){
// do something
} else {
// here: selected = null OR projectNumber of selected is null
}

did you check if selected is null
you can do the following
if(null != selected)
{
if(null != selected.getProjectNumber())
{
// do something
}
}

Your object selected is apparently null, try to do:
if ((selected != null) && (selected.getProjectNumber()!=null)){
// do something
}

From what you posted, it sems that the problem is that the object referred by the selected variable is null. You have to check that too:
if(selected !=null && selected.getProjectNumber()!=null){
// do something
}
Explanation: Doing it this way, as the boolean AND (and the OR) operator evaluates only the left condition if it is false, not touching the right side, you won't get a NullPointerExceptyion anymore.
EDIT As OP mentioned that by changing the variable to String the problem is not encountered, as 0xCAFEBABE's suggestion implies, the same error might be possible if the getter returns (or somehow internally uses) a simple long value instead of a Long object, and the value of the variable is null:
/** error getter */
public long getProjectNumber() {
//this would trz to convert null, but what will it convert to? A NullPointerExecption...
return projectNumber;
}

Related

Not able to remove null from a list in Java [duplicate]

This question already has answers here:
Why do I get a NullPointerException when comparing a String with null?
(4 answers)
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 2 days ago.
I have a list of a bean class newSRMAPIResponseBeanList wherein I am always getting a null object at last which I am trying to remove but it is resulting in null pointer exception if I handle the exception, it is not removing that null value. Below is my code.
for (int i = 0; i < newSRMAPIResponseBeanList.size(); i++) {
try {
if (newSRMAPIResponseBeanList.get(i).getCompanyId().equals(null)) {
newSRMAPIResponseBeanList.remove(i);
}
}catch(Exception e) {
e.printStackTrace();
}
}
In the if condition itself it is failing. I want to remove the null value of company ID. Actually newSRMAPIResponseBeanList is a list of List<NewSRMAPIResponseBean> newSRMAPIResponseBeanList = new ArrayList<>(); and the bean class is as follows.
public class NewSRMAPIResponseBean {
private String companyId;
private String investmentId;
private String performanceId;
private List<String> values;
}
Is there any way I can remove that null value? I also tried using Java streams as follows.
List<NewSRMAPIResponseBean> finalList=newSRMAPIResponseBeanList.parallelStream()
.filter(Objects::nonNull)
.collect(Collectors.toList());
This too did not work.
I want to remove the null value of company ID.
I presume you mean remove the list element if the Id is null. So It's not the bean that is null, it is the companyId. Assuming you have getters, try it like this. If the Id is not null, let it pass thru.
List<NewSRMAPIResponseBean> finalList=newSRMAPIResponseBeanList.parallelStream()
.filter(bean->bean.getCompanyId() != null)
.collect(Collectors.toList());
You can also do it in a simple loop.
To avoid a ConurrentModificationException, use an iterator.
Iterator<NewSRMAPIResponseBean> iter = newSRMAPIResponseBeanList.iterator();
while (iter.hasNext()) {
if (iter.next().getCompanyId() == null) {
iter.remove();
}
}

Check if String is null from a Class [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
i know that my question is a duplicate of some question here before, i tried every solution that i see from that, but no solution work for me
i have a class named FilingModel and a method name getReason, i always get a null value to my tvReason TextView
public class FilingAdapter extends RecyclerView.Adapter<FilingAdapter.FilingHolder> {
List<FilingModel> lists;
#Override
public void onBindViewHolder(#NonNull FilingHolder holder, int position) {
FilingModel model = lists.get(position);
holder.tvReason.setText(model.getReason());
}
}
public class FilingModel {
private String reason;
public FilingModel(String reason) {
this.reason = reason;
}
public String getReason() {
if ( reason.isEmpty() || TextUtils.isEmpty(reason) || reason.equals(null)) {
reason = "-";
}
return reason;
}
}
String checks for null are rather straight forward (once you have done it):
First you want to check if the instance is null (otherwise all further manipulation might fail):
if(reason == null)
Then you want to check if it is empty as you already did it but maybe you want to trim it first (to remove all whitespaces):
if(reason == null || reason.trim().isEmpty())
as you can see you can chain the conditions with or since Java will stop evaluating the conditions once one of them was found true . So if your string is null, Java will not evaluate if it is empty.
And that's all you need, null and isEmpty (and optionally with a trim())
public String getReason() {
if(reason==null || reason.trim().isEmpty()){
reason = "-";
}
return reason;
}
Give type to your variable reason. For example String.
private String reason;
+
if(reason == null)

Check return value for if-statement

I'm trying to make a bit of code that returns a boolean value depending on whether an item was successfully removed from a HashMap or not.
My understanding is that map.remove(Key) should return the Key if it worked and null if not. My approach was to check if the return value is null and print false if it is, true if anything else.
The problem I'm having comes from that I don't know how to check what the return value was inside my method.
Here is my attempt so far.
public boolean deleteMapEntry(String entry)
{
testMap.remove(entry);
if(null)
{
return false;
}
else
{
return true;
}
}
Obviously saying if (null) doesn't work, but I can't find what would.
You need to assign the value of testMap.remove(entry) to a variable to test it to see if it is null...
String value = testMap.remove(entry);
return value != null;
you can also just test what you remove directly and not use a variable:
return testMap.remove(entry) != null;

JSF can't get property of a value returned by a method with parameters

I've been stuck on a problem which involves allowing an input field of type Double to be null or other values.
Since I'm working with automatically generated code, I can't touch the get / set methods for my object. Additionally, I am unable to modify server parameters, such as -Dorg.apache.el.parser.COERCE_TO_ZERO.
My most recent solution was to make a wrapper object for the auto-generated object, which deals in String instead of Double. Here it is:
public class WrapperType {
private AUTO_GENERATED_OBJECT autogen;
public WrapperType(AUTO_GENERATED_OBJECT autogen) {
this.autogen = autogen;
}
public String getOperation() {
if (autogen.getOperation() == null) {
return null;
}
return autogen.getOperation() + "";
}
public void setOperation(String value) {
if (value == null || value.isEmpty()) {
autogen.setOperation(null);
} else {
autogen.setOperation(Double.valueOf(value));
}
}
}
So all I have to do is, instead of calling the get/set on my autogenerated object, call the get/set on an equivilant wrapper, which can be obtained with something like:
public WrapperType convertVar(AUTO_GENERATED_OBJECT autogen) {
return new WrapperType(autogen);
}
And then refer to it where needed:
<p:inputText value="#{bean.convertVar(_var).operation}" />
Except that this doesn't work. I'm recieving an error that:
javax.el.PropertyNotFoundException: /operation/collections/tabs/page.xhtml The class 'MyClass$Proxy$_$$_WeldClientProxy' does not have the property 'convertVar'.
Anyone have any ideas on how to fix this problem, or to overcome my requirement of both null and numeric values?
Take a look at this. Just use a #WebListener to modify the propery and get nulls intead of zeroes.
coerce to zero

trouble comparing equality between two objects in java [duplicate]

This question already has answers here:
Trouble over riding and using equals method in java
(2 answers)
Closed 9 years ago.
I've been having numerous problems getting this project to work correctly but I'm currently stuck on getting this class to work properly. Whats its suppose to do is take the current station from the radio class and pass it along to this class. The problem is i'm trying to select between AM and FM and display the current station. I'm not sure if i'm using the equals method correctly as it keeps returning 0.0 which is the default value of currentStation.
public class AutoRadioSystem
{
private Radio selectedRadio;
private AMRadio radioAM;
private FMRadio radioFM;
private XMRadio radioXM;
public AutoRadioSystem()
{
selectedRadio = new AMRadio();
}
public double getCurrentStation()
{
if (selectedRadio.equals(radioAM))
{
return radioAM.getCurrentStaion();
}
else if (selectedRadio.equals(radioFM))
{
return radioFM.getCurrentStaion();
}
return 0.0;
}
public void selectRadio()
{
//if (selectedRadio.equals(radioAM))
// selectedRadio = radioFM;
}
public boolean equals (Object o)
{
if (o == null)
return false;
if (! (o instanceof AutoRadioSystem))
return false;
AutoRadioSystem other = (AutoRadioSystem) o;
return this.selectedRadio == other.selectedRadio;
}
public static void main (String [] args) {
AutoRadioSystem c = new AutoRadioSystem();
//c.selectRadio();
double b = c.getCurrentStation();
System.out.println(b);
}
}
Looks like you are doing it wrong (tm).
The Radio interface should expose the getCurrentStaion() method which will be implemented by all 3 radio classes. Then your getCurrentStation() method can just invoke selectedRadio.getCurrentStation() and return its result.
Also you are implementing equals() method in the AutoRadioSystem which will have no effect when comparing Radio instances.
Objects in Java are a bit differents when it comes to comparing them, as you can compare objects in two ways.
You can compare the objects's references, by using ==.
And you can let a self-made method do a customized check, by using o1.equals(o2) where o1,o2 are objects.
Note that o instanceof AutoRadioSystem returns false if o==null and does not throw a NullPointerException.
PS: There are other issues as well as answered in your previous question.
Note that simply with
private Radio selectedRadio;
private AMRadio radioAM;
private FMRadio radioFM;
private XMRadio radioXM;
public AutoRadioSystem()
{
selectedRadio = new AMRadio();
}
radioAM, radioFM, and radioXM are all initialized to null, by default.
Any proper equals() method will immediately return false when comparing with a null reference. So in this
public double getCurrentStation()
{
if (selectedRadio.equals(radioAM))
{
return radioAM.getCurrentStaion();
}
else if (selectedRadio.equals(radioFM))
{
return radioFM.getCurrentStaion();
}
return 0.0;
}
none of the if will evaluate to true, and you will get the last case of returning 0.0.
On top of implementing their equals() method correctly, you'll need to initialize them correctly as well.

Categories

Resources