Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I making android applicaton and i have java.lang.NullPointerException with this code. Java server is on the comuter. Thanks for help.
try {
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
Socket socket;
socket = new Socket("192.168.0.179", 5450);
os = new PrintStream(socket.getOutputStream());
is = new DataInputStream(socket.getInputStream());
in = is.readLine().trim();
if(in == "hello") {
os.print(edit.getText().toString());
os.flush();
Log.d("LoL", in);
Log.d("LoL", edit.getText().toString());
in = is.readLine().trim();
edit.setText(in);
os.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
} catch (Exception e) {
Log.d("LoL",e.toString());
}
The in == "hello" expression will always return false, because you'll want to compare the contents of the strings in and "hello"; that expression checks that they are the same object, and that will never happen. For any non-primitive type like strings, we should write "hello".equals(in). (you may also write in.equals("hello") but the latter form prevents another possible NullPointerException)
Since that expression will always return false, the if block will never execute. Therefore, the NPE may happen only in two places:
in ok.setOnClickListener: if the ok variable is null, e.g. is not initialized, calling any method on it will lead to NPE;
in in = is.readLine().trim();: if the InputStream is empty (e.g. got no data or EOF from the server) is.readLine() will return null, and calling trim() on a null object will lead to NPE.
BTW, InputStream.readLine() is deprecated, better use BufferedReader instead. That's explained here.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I have the following function body
String f(filename){
BufferredReader br = null;
try{..}
catch(Exception e){
e.printStackTrace();
}
}
Inside the try block I try to open the file and do something with it. At the end of the try block I return a string. The program does not compile.
So, I initialize a string variable before the try block, manipulate the variable inside the try block and return it after the catch block. Is this the right way to do it? My question is why does the compiler not allow me to directly return the string inside they try block. Furthermore, I've tried to close the file by doing br.close() after the catch blockand the program does not compile too saying I need to handel an IOException, so I had to close the file inside the try block.
Is this also the write way to do it? To open and close the file both inside the try block.
You must return some value from function in any possible case (or throw exception), so this code isn't compiled:
String f(filename){
BufferredReader br = null;
try{
...
return s;
}
catch(Exception e){
e.printStackTrace(); // what is return from function in this case?
}
}
You should use following code
String f(filename){
BufferredReader br = null;
try{
...
return s;
}
catch(Exception e){
e.printStackTrace();
}
return null; // or return "";
}
or
String f(filename){
BufferredReader br = null;
try{
...
return s;
}
catch(Exception e){
e.printStackTrace();
throw new RuntimeException(e);
}
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
Following is a part of Server program code
ServerSocket serverSocket = new ServerSocket(port);
...
cameraSocket = serverSocket.accept(); // problematic
And below is a part of a camera program who wants to connect to the above server
sock2server.connect((new InetSocketAddress("127.0.0.1", 6066)), 1000);
The problem is: the above problematic accept statement returns twice for
one connect request. The interval of return is about 7 milisecond.
Can someone explain this phenomenon?
Here is the client side code (I changed it a bit to make is a complete method)
The problem happens only when the client runs first (before server runs)
private Socket connectSocket() {
final short ID_SEND_PERIOD = 100; // irrelevant line maybe
try {
appendLine(cameraGUI.getMsgArea(), "calling at: " + currentTimeMillis());
Socket managerSocket = new Socket();
managerSocket.connect((new InetSocketAddress(serverName, port)), CAMERA_PERIOD);
managerSocket.setSoTimeout(CAMERA_PERIOD);
setManagerOutStream(managerSocket.getOutputStream()); // irrelevant line maybe
setManagerInStream(managerSocket.getInputStream()); // irrelevant line maybe
toleranceLevel = MAX_TOLERANCE; // irrelevant line maybe
sendID_forSure = new Timer(); // irrelevant line maybe
sendID_forSure.schedule(new ID_Sender( // irrelevant line maybe
cameraGUI, getManagerOutStream(), cameraID), // irrelevant line maybe
0, ID_SEND_PERIOD); // irrelevant line maybe
return managerSocket;
} catch (SocketTimeoutException e) {
return null;
} catch (IOException e) {
logParkingExceptionStatus(Level.INFO, e, "IO exception", cameraGUI.getCriticalInfoTextField());
disconnectSocket(e, "IO exception");
return null;
}
}
I some how found a solution. But, I don't have a complete understanding why.
That is, I commented out 2 lines from the above code
// Socket managerSocket = new Socket();
// managerSocket.connect((new InetSocketAddress(serverName, port)), CAMERA_PERIOD);
And replaced those lines with the following single line.
Socket managerSocket = new Socket(serverName, port);
After the change, the accept never executes twice even when the client runs first.
If anybody could give the reason, that might be help my understanding. Thanks.
The only plausible explanation for what you are seeing is that your camera application is actually connecting to the server twice.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
[12]
key1=val1
key2=val2
key3=val3
key4=val4
key5=val5
[13]
key1=val1
key2=val2
key3=val3
key4=val4
key5=xyz
[14]
key1=val1
key2=val2
key3=val3
key4=val4
key5=val5
I want to update key5=val5 where [13].
try {
br = new BufferedReader(new FileReader(oldFileName));
bw = new BufferedWriter(new FileWriter(tmpFileName));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
if (line.contains("[13]"))
{
while (line.contains("key5")) {
if (line.contains("key5"))
{
line = line.replace("key5", "key5= Val5");
bw.write(line+"\n");
}
}
}
}
} catch (Exception e) {
return;
} finally {
try {
if(br != null)
br.close();
} catch (IOException e) {
//
}
try {
if(bw != null)
bw.close();
} catch (IOException e) {
//
}
}
This block of code is problematic:
if (line.contains("[13]"))
{
while (line.contains("key5")) {
//etc....
Because there are NO lines which contain both [13] and key5 (they are on separate lines), so the while loop will NEVER be entered.
Instead, when the line [13] is encountered, it's necessary to remember it and store the flag in a boolean, something like the following:
boolean in13 = false;
//... other lines...
if (line.equals("[13]")) {
in13 = true;
} else if (line.startsWith("[")) {
in13 = false; //another block started, clear flag
}
if (in13 && line.startsWith("key5=")) {
// you've found it
}
You really need to step through your logic in your head; in your code:
if (line.contains("[13]")) {
while (line.contains("key5")) {
if (line.contains("key5")) {
line = line.replace("key5", "key5= Val5");
bw.write(line+"\n");
}
}
}
Try writing this out on a piece of paper or something and following it. Look at your while (line.contains("key5")) loop for example. If the line contains "[13]" then it does not contain "key5" and your loop does not even run once. There are many other problems as well (such as the fact that you're only attempting to write one line back out, as another person mentioned in the comments, or that you're not reading any more lines inside your loop, among other issues). For these types of things, work out precisely what you want to do, then write code to match. It looks like you want to do the following:
Search for the line "[13]". Once found...
Search for a line starting with "key5=", but stop when a new section (starting with "[") is encountered. If that is found:
Replace that line with "key5=" + new value.
And for each line you touch that you do not replace, you'd have to write it back out (although a general formula here, barring memory constraints, is to parse/load, then modify, then write).
So you'll want your code to do that.
Also note that some INI file parser implementations (presuming you are treating this as an INI file) ignore whitespace and/or case in the key and section names, so depending on the source of your file, you may want to take that into account.
By the way, perhaps consider using an INI file handling library such as ini4j, where you can load the file and replace keys directly. See What is the easiest way to parse an INI file in Java?.
This part looks wrong:
while (line.contains("key5")) {
if (line.contains("key5"))
I assume that NOT operator is missing in loop condition
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
i have following code and i like to get exception message using finally as by using catch i can easily get by its arg.but as much i know i am not able in get exception message using finally.
try {
MyClass obj=new MyClass();
obj.strProName = jobj1.getString("productname");
obj.strPrice = jobj1.getString("price");
obj.strCurrency = jobj1.getString("currency");
obj.strSalePrice = jobj1.getString("saleprice");
obj.strStoreName = jobj1.getString("storename");
//arrayList.add(obj);
throw new Exception("Exception Reason!");
}
finally{
//want to get that exception message here without using catch or can see how finally catching here the exception
}
Unlike catch block ,finally block does'nt receive any exception instance
So,The answer is No from my side.
What I mean is to print the message,You need Exception instance.
As per docs (jls-14.2)
A block is a sequence of statements, local class declarations, and local variable declaration statements within braces.
So outside of catch block catch(Exception e) {} you cannot access it (e).
but as much i know i am not able in get exception message using
finally.
That's correct, to catch an excpetion you, well... have to use a catch clause.
You could however store the message in a variable (in the catch clause) and use that variable in the finally clause later.
finally does not catch the exception. You can catch exception only in catch block.
The purpose of finally block is to execute in both cases, i.e. it will execute irrespective of exception being occured or not.
Finally does not catch exception, it is simply a thing you can use to always do something, even if there is no error and the catch is never called for.
try {
MyClass obj=new MyClass();
obj.strProName = jobj1.getString("productname");
obj.strPrice = jobj1.getString("price");
obj.strCurrency = jobj1.getString("currency");
obj.strSalePrice = jobj1.getString("saleprice");
obj.strStoreName = jobj1.getString("storename");
}
//arrayList.add(obj); here you can Catch the exception, meaning it will only show if there is an exception!
catch(Exception e){
System.out.print(e+"=Exception Reason!");
}
finally{
//Finally is used to do something no matter what.
//It will do what ever you want it to do,
//even if the catch is never used.
//Use catch to show exception,
//finally to close possible connections to db etc.
}
Try this
try {
.....
throw new Exception("Exception Reason!");
}
catch(Exception e){
msg=e.getMessage();
finally{
//USE String msg here.
}
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I want to know what would be the best way to save objects to a file ? Saving in the sense, the objects need to be appended.
When i searched the internet i found that printwriter saves an object in the format of it's toString method, but then if it saves an object to a file in the toString format , how can the programer use it to access an instance in an object.
What i mean is, if i save a student object to a text file using printwriter(The object has a name, id and age) , how can i use it in the future to compare the age of one student with another student's age / search by id , etc.
Since the object is saved as a string , it can only be read as a string so how can i access the instances of an object?
The other method i found out is serialization. Serialization looks like it does the job but then i found out that it cannot append objects to a file , because it's stream header keeps on overriding. Is there a method to append objects to a file using serialization ?
Currently these are the only 2 methods i found out for writing objects , but it seems i cannot use any of these methods since when saved using printwriter , it will be read as a string and if i use serialization i can store only one record.
Thank you for your time.
JAXB will be great choice for you, as I see from your problem description. Here is a simple example to start with.
JAXB is a part of standard JDK since 1.6, so you don't need any additional libraries.
Also is supports collections serialization so you can easily implement your "append" task.
What could be a good idea (in my opinion at least) is to use XStream to serialize entire objects to file as XML. Using that library you could serialize entire objects to store them and then use that same library to automatically convert the XML back to the objects so that you can compare them.
Also, saving stuff to File as XML will allow other languages to be able to process the same file.
Why not use FileOutputStream instead of PrintWriter and simply write the data to a file in append mode? FileOutputStream does have a append mode constructor.
Java Serialization example
FileOutputStream Javadoc
How about you override writeStreamHeader and reset?
ObjectOutputStream ooStream = null;
try{
ooStream = new ObjectOutputStream(new FileOutputStream("object-writer"));
ooStream.writeObject(new ObjectWriter());
} catch(Exception ex){
ex.printStackTrace();
} finally {
if(ooStream != null){
try {
ooStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
ObjectOutputStream ooStream2 = null;
try{
ooStream2 = new ObjectOutputStream(new FileOutputStream("object-writer", true)) {
#Override
public void writeStreamHeader() throws IOException {
reset();
}
};
ooStream2.writeObject(new ObjectWriter());
} catch(Exception ex){
ex.printStackTrace();
} finally {
if(ooStream2 != null){
try {
ooStream2.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
ObjectInputStream oiStream = null;
try {
oiStream = new ObjectInputStream(new FileInputStream("object-writer"));
System.out.println(oiStream.readObject());
System.out.println(oiStream.readObject());
} catch (Exception e) {
e.printStackTrace();
} finally {
if(oiStream != null){
try {
oiStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}