Normally I make a comparison in every activity(Android) but I have a problem and I couldn't find the solution. I tried everything I could but result is still the same.
In if statement null value seems to be not null.
What am I doing wrong?
Here is the code :
System.out.println(item.getSub()); // output is null
if (item.getSub()!=null) {
r.putExtra("engsub", item.getSub()); // Normally it shouldn't, but it goes in here
startActivityForResult(r, position);
}
else {
//Do something
}
And I tried this :
String def = item.getSub()+"";
System.out.println(def); // output is not null
if (!def.equals("")) {
r.putExtra("engsub", item.getSub()); // Normally it shouldn't, but it goes in here
startActivityForResult(r, position);
}
else {
//Do something
}
Added :
JSONArray jsonResponse = new JSONArray(result);
asd = new String[5][jsonResponse.length()];
rowItems = new ArrayList<RowItem2>();
for (int i = 0; i < jsonResponse.length(); i++) {
JSONObject js = jsonResponse.getJSONObject(i);
// ....codes
asd[4][i] = js.getString("engsub");;
item = new RowItem2(asd[0][i], asd[1][i], asd[2[i],
asd[3][i],asd[4][i]);
rowItems.add(item);
}
RowItem2 class
private String engsub;
public RowItem2(String title, String desc,String desc2,String desc3,String engsub) {
this.engsub = engsub;
//......
}
//.......
public String getSub() {
return engsub;
}
public void setSub(String engsub) {
this.engsub = engsub;
}
I think JSON string result contains the word "NULL" in it.
Look at the docs about JSONObject on Android Developer site.
Here is the line that solves your problem:
When the requested type is a String, other non-null values will be
coerced using valueOf(Object). Although null cannot be coerced, the
sentinel value NULL is coerced to the string "null".
Below some ideas when trying to track down an issue like this:
Confirm your assumptions
You sound confused, so set your mind at ease. There is nothing wrong with Java / Android. Confirm this with a change that will work correctly every time.
This change challenges your assumption: you assume that item.getSub() is returning null.
String nullString = null;
System.out.println(nullString);
if (nullString != null) {
r.putExtra("engsub", item.getSub()); // Normally it shouldn't, but it goes in here
startActivityForResult(r, position);
}
else {
//Do something
}
This will NOT pass the if test, unless there is something wrong with your IDE.
Confirm your IDE is working
You may still think you are getting null. In some cases it could look like this.
Sometimes Eclipse will not put the correct code onto your emulator / device. There could be an issue with the build.
So do a project Clean. Then build again and test.
This will confirm that you are running the correct code.
Confirm what you are seeing
Sometimes when output looks like a "" string, it can be " " or " ".
Try logging your output surrounded by [ and ].
System.out.println("[" + item.getSub() + "]");
Look deeper into the code
This is why I asked to see the item.getSub() code, and the extra you have shown.
If the above tests don't help, look to see how that value is set / returned.
Looking into JSONObject.getString() javadoc, it shows that it cannot return a null value:
In your case, log out the JSON string, and log out the values in RowItem2 constructor.
That should show you the "NULL" I refer to at the top of this answer.
You could try:
if (item.getSub() instanceof String) {
r.putExtra("engsub", item.getSub()); // Normally it shouldn't, but it goes in here
startActivityForResult(r, position);
}
else {
//Do something
}
This way you're sure that the item.getSub() is a string.
Try this,
if(!"".equals(your string)
{
// do something
}
Related
I'm a groovy newbie so bear with me here. I love groovy's power to write less and often cleaner code but I'm trying to figure out if there's a better or more readable way of condensing these multiple if statements. It's a fairly straightforward code snippet but there's got to be a better way of doing this. I'm a newbie so any code snippets are greatly appreciated.
if (!textOverlay) {
textType = ""
if(url != null){
Page getPage = resource.getResourceResolver().getResource(url).adaptTo(Page.class)
if (getPage != null) {
showLink = showLink + ".html"
if (fragment.length() > 0) {
url += "#"+fragment;
}
}
}
} else {
//do something else
}
Thanks in advance for the help!
This doesn't help with nesting, but there are a few places where you could take advantage of Groovy to make the code a bit more compact. I've added some explanatory comments
if (!textOverlay) {
textType = ""
// null is considered false, so no need to explicitly check for null
if (url) {
// getResourceResolver() replaced by resourceResolver
// Page and Page.class are the same thing
Page getPage = resource.resourceResolver.getResource(url).adaptTo(Page)
// Groovy truth
if (getPage) {
// use String concatenation operator (also works in Java)
showLink += ".html"
// non-empty strings evaluate to true
if (fragment) {
// GString instead of string concatenation
url += "#$fragment"
}
}
}
} else {
//do something else
}
I have the following code snippet.
Explanation:
I have the array called result.
This array consists of different String attributes like "city", "countryName" and "IATA".
With a for loop, I try to access and retrieve all the aforementioned fields.
My problem now is: While "city" and "countryName" always have a value, "IATA" sometimes does not have a value and thus returning me "null", which leads to the nullPointerException as soon as I access an empty "IATA".
I tried this:
if(entry.getIATA().equals(null)) {
} else {
startIATA[count] = entry.getIATA();
}
But, this if condition is not working as I try to access a field which is null.
Has anyone an idea how I can solve this?
Here is the relevant code snippet:
private String[] startIATA = new String[200]; //That is more than long enough
...
for (int count = 0; count < result.getAirports().length(); count++) {
AirportsEntry entry = result.getAirports().get(count);
// Block for StartAirport
HorizontalPanel hp = new HorizontalPanel();
hp.setSpacing(5);
hp.add(new Label(entry.getCity()));
hp.add(new Label(entry.getCountryName()));
hp.add(new Label(entry.getIATA()));
GWT.log("IATA: " + entry.getIATA());
if(entry.getIATA().equals(null)) {
} else {
startIATA[count] = entry.getIATA();
}
startAirportVP.add(hp);
}
Thank you very much for your time and your help!
Perform a simple null check prior to accessing the property of the object.
if(entry != null && entry.getIATA() != null){
startIATA[count] = entry.getIATA();
}
You cannot use equals method to check for null. Use ==:
if (entry.getIATA () == null)
use this:
if (entry.getIATA() != null)
I have an application which requires to check if a String is present in an array of String type, before adding it so as to avoid duplication. To do this, I wrote the following function:
public boolean arrayHas(String[] arr, String str)
{
for(int i=0;i<arr.length;i++)
{
if(arr[i].equals(str))
return true;
}
return false;
}
To invoke this function, I'm using:
if(!arrayHas(contacts,str))
{
contacts[i] = str;
i++;
}
contacts and str are declared as follows
public static String contacts[] = new String[]{};
String str = "";
Bundle bun = getIntent().getExtras();
str = bun.getString("key");
Elements are added to 'contacts' only through the main code, it is empty at the beginning. I tried adding a toast to display the value of 'str' received through the intent and it works fine. But I'm getting a NullPointerException in the 'if' statement in the arrayHas function. Could someone help me out?
Seems that you haven't initialized the array with elements. So all of them are NULL.
In you arrayHas function check if the element you are comparing with is a null or not.
if(arr[i] != null && arr[i].equals(str) )
{
// do your operation
}
Also before calling arrayHas function in
if(arrayHas(contacts,str)) { }
put a check if contacts is null or not.
Two issues:
First: add a null check in if as:
if(arr[i] != null && arr[i].equals(str))
because that position may not have assigned with a valid string yet e.g. in the very beginning, no assignment is made and arr[0] is null so comparison will result into NullPointerException.
Second: I think you want to check the not ie. ! condition in this check:
if(!arrayHas(contacts,str))
{
contacts[i] = str;
i++;
}
If you want to avoid duplication, use a java.util.Set<String>, it will take care of it for you. You can always uso toArray() if you really need an array later on.
If you care about the order of your elements, you can also use a java.util.List, and check the presence of the element with list.contains(str)
Use this instead :
String contacts[] = new String[10];
String str = "somethiung";
if(Arrays.asList(contacts).contains(str))
{
contacts[i] = str;
i++;
}
Arrays.asList(.).contains(.) gives you a much better way to test if a string is present in an array.
By the way make sure that contacts and str are properly initialized.
Just a suggestion to code style. Try to defensive programming., ie. you are checking whether the string str is present in arr in that case always do the check in reverse ie., str.equals(arr[i]), so that unnecessary NPEs wont be raised.
In this case an NPE could be raised at 2 points, if arr is null .length and .equals will throw NPE's. From this its evident that, either arr is null , or arr[i] is null.
Find the method where arr is filled with data, there something is going wrong.
thanks
You must not have initialized your contacts[] but it might be the case like str[0]=null but str[1]="something";
in that case change
arr[i].equals(str) to `str.equals(arr[i])` as str is less likely to be null
- I think you are trying to find whether a String is a present in the Array of Not.
- First use Collections cause that will be much more flexible in comparision to Array.
- Use Collections.contains() method to find the String if present of not.
For example if you are using List:
List<String> list = new ArrayList<String>();
list.contains("string_to_be_found");
I want tov compare previous and new value coming from a loop and based on data increment some rows.For that i am doing like below but the data is getting overwritten since i am doing inside for loop.How can i perform this.
for (RecordData recordData : recordDataList) {
prevRespondentId = recordData.getRespondentId();
if (recordData.getRespondentId() != prevRespondentId) {
rowDataNumber++;
}
prevRespondentId = recordData.getRespondentId();
}
I have data like 1,2,3 as respondent Id ,i need to see new and prev based on that increment data.
Would this fix your issue?
prevRespondentId = recordDataList.get(0).getRespondentId(); //Initialize to first or default value probably -1?
for (RecordData recordData : recordDataList) {
if (recordData.getRespondentId() != prevRespondentId) {
rowDataNumber++;
}
prevRespondentId = recordData.getRespondentId();
}
Basically you are overwriting the prevRespondentId even before checking for it, which is causing the issue.
Difficult to understand what your trying to do however perhaps something like this:
for (RecordData recordData : recordDataList) {
if (recordData.getRespondentId() != prevRespondentId) {
rowDataNumber++;
}
prevRespondentId = recordData.getRespondentId();
}
Basically don't override the preRespondentId until you've done your if check. This will ensure that it will always be the previous respondent id. You'll of course need to initialise it though.
Hope that helps.
..some type.. prevRespondentId = -1;
for (RecordData recordData : recordDataList) {
if (recordData.getRespondentId() != prevRespondentId) {
rowDataNumber++;
}
prevRespondentId = recordData.getRespondentId();
}
I have this recursive method:
public Hund getMor(int id) {
Hund barn = getHund(id);
int idMor = barn.getId_mor();
Hund mor = getHund(idMor);
return mor;
}
public String getMorTre(int id) {
if (id == 0) {
return null;
}
if (!existHund(id)) {
return "Hunden du søkte etter finnes ikke";
} else {
if (id == 0) {
return null;
} else {
Hund mor = getMor(id);
MinRamme.jta.append(mor.toString() + "\n");
int morId = mor.getId();
return getMorTre(morId);
}
}
}
I have tried to remove the nullpointer by returning null if the id is 0 but this does not work. Does anyone have a solution?
NPE:
Exception in thread "AWT-EventQueue -0" java.lang.nullpointerexception
at Arkiv.getMorTre(Arkiv.java:209)
at Arkiv.getMorTre(Arkiv.java:211)
at Arkiv.getMorTre(Arkiv.java:211)
at MinRamme$4.actionPerformed(MinRamme.java:89) <37 internal calls>
Where does the NullPointerException occur? That would help... That being said:
Inside your else clause, your
if (id==0) {
is useless, since you're testing that at the beginning and the id isn't changed.
I think you need to check if
getMother(id)
returns null, that is probably where you're getting the NullPointer... but you could confirm that now, couldn't you?
It is likely (but difficult to confirm until you let us know what line is throwing the NPE) that the line that generates the NPE is
MyFrame.jta.append(mother.toString() + "\n");
because mother is null. You could change your code into this:
Dog mother = getMother(id);
if (mother == null) {
//do something
}
There really isn't enough information here. What line are you getting the null pointer on?
if, as I suspect, it's here:
MyFrame.jta.append(mother.toString() + "\n");
Then you need to determine, through debugging, that it's definitely mother that is null. If you have done that, then you can be absolutely positive that your getMother(id); returns null, for the id that you are passing in.
If I were you I would create a unit test for the getMother(id) method and pass in the id that is causing the failure.
If you don't know what id value is causing the problem, then at the very least stick in some System.out.print() statement to find out what is going on. Although, you'd be better using some logging framework, such as log4j.
Hope this helps.
Its because your exception is at mother.toString() method..
try this
try
{
MyFrame.jta.append(mother.toString() + "\n");
}catch(NullPointerException ignore){}