solving NullPointerException in JAVA for a URL request - java

So I am making a URL request to fetch a stream of data into a BufferedReader. The data that I am fetching has values "null" for various fields. The while condition I am using to read all the data is:
while (((inputLine = in.readLine()) != null))
so the condition is breaking in between, when it encounters a null value, which is actually not the EOF but only a field value. How do I resolve this?

When you read a line, it will never be null until it reaches the end of the data. If there's no data in the line, it will just be an empty string instead.
You haven't shown enough code to explain why you're getting a NullPointerException, but you really need to understand that you won't see any "null values" before reaching the end of the data.
To work out why you're getting a NullPointerException:
Look at the line indicated in the stack trace
Identify every dereferencing operation
Either put a breakpoint on that line, or add some logging, or split the line into multiple statements so that each statement only has a single dereferencing operation
That should let you work out exactly which value is null, causing the exception to be thrown. What you need to do to fix it will depend on what you're trying to do and which value is null - we don't have enough information to help you on that front at the moment.

Related

Getting a NullPointerException but printing the object returns a both a memory refence and a null value

I'm trying to make a program that simulates NFA's, I have state objects and an NFA object (named machine). The state objects refrence other states (like a tree data structure but without hierarchy) right now the NFA object only defines the starting state and the rest are linked from there.
The problem comes when I try to assign the NFA (named machine)'s start state to the search variable (type State). When I later try to use this object to move through out the NFA it gives a null pointer error. When debugging (shown by print statements) it seems that assigning the variable seems to work correctly but more strange: when I print the object later it prints both a memory refence and a null value.
System.out.println(machine.getStart()); //prints out State#6bc7c054
search = machine.getStart(); //assigns the starting state of the NFA to search variable
System.out.println(search); //prints out State#6bc7c054
... (there is no code related to search variable in this chunk)
System.out.println(search + " last ref");//prints State#6bc7c054 last ref (and also)
null last ref
search = search.move(sym);//line that gives NullPointerException
Any thoughts on whats going wrong here are greatly appreciated
My answer is obvious but, if 4 lines where printed, then you should have 4 println instruction (or an "\n" in one of them), check in the hidden chunk if you haven't any println.
As for me, the most probable is that, in the hidden chunk you've a println statement that prints well your search + "last ref" and an other statement that sets search to null.
If I'm right, then your last println is printing the null last ref, and you'll have NullPointerException if you try to act on search.

Comparing NULL values in Java

I have a code that compares data but that data contains null values not blank spaces ("") they may/may not be same i guess but I tried comparing repetitive NULL values like
for(int i=0;i<length;i++)
{
String data=sample_data.getData();// contains about
1000 null rows
if(data.equals(null) || data.equals("") || data== null
||data.isEmpty())
System.out.print("No Data");
}
I could have used .contains but that wont work because it is in the loop.
None of the method makes it print the output as No Data I have tried using try catch as well because in order to make sure if theres any error found and was correct at the same time isEmpty() and .equals(null) were somewhere or the other throwing the exception as NULL but even after removing and simply using ==Null realizing the fact that data is itself null and comparing like null.equals wont work but in case of == I found that the error exception got changed to value as 1 thereafter the same error and I wasnt able to recognize this.
Its the sample here which I am showing I cant post the exact but the above makes quite clear. Is there any other way I could treat these NULL values.
Note: I dont want to use a loop to iterate data as well and each time comparing NULL values because already theres an outer loop for large set of values dont go by the sample code.
Restoring windows to factory settings will restore windows (as its name suggests); it won't spoil anything.
In this
String data=sample_data.getData();// contains about 1000 null rows
if(data.equals(null) || data.equals("") || data== null
you are apparently concerned that data may be null.
If indeed it is null, then the very first clause in your if statement will throw a null pointer exception... because you can't call the equals method on a null reference.
You want
if (data == null || data.isEmpty())
and that covers all the cases of nothing, except possibly the case where data is "some number of space characters", but I'll leave that for you.

Java Byte[] to String conversion dropping end quotes / weird side-effect

I am currently trying to perform some regex on the result of a DatagramPacket.getData() call.
Implemented as String myString = new String(thepkt.getData()):
But weirdly, java is dropping the end quotation that it uses to encapsulate all data(see linked image below).
When I click the field in the variable inspector during a debug session and don't change anything, when I click off the variable field it corrects itself again without me changing anything. It even highlights the variable inspection field in yellow to signal change.
Its values are also displaying like it is still a byte array rather than a String object
http://i.imgur.com/8ZItsZI.png
It's throwing off my regex and I can't see anything that would cause it. It's a client server simulation and on the client side, the getData returns the data no problem.
I got it working by using the solution provided in:
https://stackoverflow.com/a/8557165/1700855
But I still don't understand how not specifying the length of the packet to the String constructor would cause it to drop the systematic end double quotes. Can anyone provide an explanation as I really like to understand solutions to my issues before moving on :)
The problem is that you didn't read the spec for DatagramPacket.getData:
Returns the data buffer. The data received or the data to be sent
starts from the offset in the buffer, and runs for length long.
So, to be correct, you should use
new String(thepkt.getData(), thepkt.getOffset(), thepht.getLength())
Or, to not use the default charset:
new String(thepkt.getData(), thepkt.getOffset(), thepht.getLength(), someCharset)

charAt :error java.lang.NullPointerException

I am trying to use talend to check if the 4th character = 4 then I conversion S _ if not we keep the value
the input file is an Excel file
who can help me
row1.B.charAt(4) == '4'? StringHandling.CHANGE(StringHandling.LEFT(row1.B,9) ,"_","S"):row1.B
I have this error
[statistics] connected
Exception in component tMap_1
java.lang.NullPointerException
at projectname.test_0_1.test.tFileInputExcel_2Process(test.java:1140)
at projectname.test_0_1.test.runJobInTOS(test.java:1672)
at projectname.test_0_1.test.main(test.java:1540)
Either row1 or row1.B (use proper caps! attributes begin with lower case) are null
UPDATE: Regardint the comment to your question, then row1.B is null. Check for it and either control it in the condition ((row1.B != null) && (....)) or ((row1.B == null) || (...)) or (more probably) check your logic to assign a proper value to it.
A null pointer exception is caused when you dereference a variable that is pointing to null.
In you case either row1 or row1.B are null.
The cleanest way to do this is to write a user routine and then just call the function from tMap on the row input.
E.g. userFunction(row1.B)
Make the function output whatever string manipulation you need.
This also allows you to handle the case where the B cell in Excel is null. You can't do that in a one liner in tMap.

reading multiple lines in file upload

can anyone tell me how to read multiple lines and store their value.
eg:file.txt
Probable Cause: The network operator has issued an alter attribute command for
the specified LCONF assign. The old value and the new value are show
Action Taken : The assign value is changed from the old value to the new
value. Receipt of this message does not guarantee that the new attribute
value was accepted by clients who use it. Additional messages may be.
Probable Cause: The network operator has issued an info attribute command for
the specified LCONF assign. The default value being used is displaye
Action Taken : None. Informational use only.
In the above file, Probable Cause and Action Taken are the column of a database table. And after Probable Cause: those are the value to be stored in the database table for probable cause column, same goes with action taken.
So how can i read the multiple lines and store their value? I have to read the value for probable cause until the line comes with Action Taken. I'm using BufferedReader and the readLine() method to read one line at a time. So can anyone tell me how to read directly from probable cause to action taken no matter how many line comes between them.
The simplest way is probably to just keep a List<String> for each value, with loops something like this:
private static final String ACTION_TAKEN_PREFIX = "Action Taken ";
...
String line;
while ((line = reader.readLine()) != null)
{
if (line.startsWith(ACTION_TAKEN_PREFIX))
{
actions.add(line.substring(ACTION_TAKEN_PREFIX))
// Keep reading the rest of the actions
break;
}
causes.add(line);
}
// Now handle the fact that either we've reached the end of the file, or we're
// reading the actions
Once you've got a "Probable Cause" / "Actions Taken" pair, convert the list of strings back to a single string, e.g. joining with "\n", and then insert in the database. (The Joiner class in Guava will make this easier.)
The tricky bit is dealing with anomalies:
What happens if you don't start with a Probable Cause?
What happens if one probable cause is followed by another, or one set of actions is followed by another?
What happens if you reach the end of the file after reading a probably cause but no list of actions?
I don't have the time to write out a complete solution now, but hopefully the above will help to get you going.

Categories

Resources