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)
Related
This question already has answers here:
Ignore case for 'contains' for a string in Java [duplicate]
(6 answers)
Closed 20 days ago.
I have created an Address class*
public class Address {
private long id;
private String organizationName;
private long entId;
private String orgAddress;
private String orgType;
}
And I have created a list which have Address objects inside and i have created an Api using it.
List<Address> list;
public AddressServiceImpl() {
list=new ArrayList<>();
list.add(new Address(1,"Anth",123456,"Time square,NY","Doctor"));
list.add(new Address(2,"carl",12114,"street 16,NY","Staff"));
}
and now i need to search a part of string from the list now and i want to fetch the objects that have **organizationName **as the related String
#Override
public List<Address> searchAddress(String search) {
List<Address> listClone= new ArrayList<>();
for(Address d : list){
if(d.getOrganizationName().toLowerCase() != null && d.getOrganizationName().contains(search.toLowerCase())) {
listClone.add(d);
}
}
return listClone;
}
But when i am searching "Anth" and "anth" it is not giving any response.Please Help!!!
But when i am searching "Anth" and "anth" it is not giving any response.Please Help!!!
Regarding the code
if(d.getOrganizationName().toLowerCase() != null
&& d.getOrganizationName().contains(search.toLowerCase())) {
listClone.add(d);
}
Two issues here:
your null check is bad. If d.getOrganizationName() is null (which can apparently happen), calling toLowerCase on it will throw a NullPointerException.
your other part of the check uses contains, but you don't use toLowerCase on it.
What you want is
if(d.getOrganizationName() != null
&& d.getOrganizationName().toLowerCase().contains(search.toLowerCase())) {
listClone.add(d);
}
you just miss toLower() in d.getOrganizationName() .
public static List searchAddress(String search) {
List<Address> listClone = new ArrayList<>();
for (Address d : AddressServiceImpl()) {
if (d.getOrganizationName() != null
&& d.getOrganizationName().toLowerCase().contains(search.toLowerCase())) {
listClone.add(d);
}
}
return listClone;
}
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
I got this. But my list is not empty and they have element with code "ADPL". Why this return me NoSuchElement ?
String retour = CodeExecutionChaine.A.getCode();
if (!lstChaines.isEmpty()) {
retour = lstChaines.stream()
.filter(t -> t.getNomChaine() == Chaines.ADPL.getCode())
.map(Chaine::getStatutChaine)
.findFirst()
.orElse(CodeExecutionChaine.A.getCode());
The enum Chaines
public enum Chaines {
ADPL("ADPL"),
ADIL("ADIL"),
ADSL("ADSL");
private String code = "";
Chaines(String code) {
this.code = code;
}
public String getCode() {
return this.code;
}
}
This is the same for CodeExecutionChaine
Change t -> t.getNomChaine() == Chaines.ADPL.getCode() to t -> t.equals(Chaines.ADPL.getCode()).
== checks for identity. Therefore, == will result into true only if two references point to the same object. On the other hand, equals checks for equality. Two references that don't point to the same object but have similar properties are still considered equal. You get a NoSuchElementException because you used == to filter your Stream which resulted in zero elements satisfying the condition.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
I have a simple piece of code to validate a username and a password.
public boolean isValid(String u, String p) {
if (u=="admin" && p=="password1") {
return true;
} else if (u=="user" && p=="password2") {
return true;
} else {
return false;
}
}
I've tried debugging it, and when it runs, u has the value "admin" and p has the value "password1", but it just skips the first condition. I must have done something wrong, but I can't figure out what.
== should not be used for String comparison. Use equals() instead.
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.
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;
}