Jackson can't parse json, returns NPE - java

I'm trying to parse json (steam webchat) which looks like that (I've changed response cause I don't wanna show the data):
/**/({
"pollid": 00,
"messages": [
{
"type": "personastate",
"timestamp": 0000000000,
"utc_timestamp": 000000000,
"steamid_from": "000000000000",
"status_flags": 0000000,
"persona_state": 0,
"persona_name": "asd"
}
]
,
"messagelast": 00,
"timestamp": 0000000000,
"utc_timestamp": 000000000000,
"messagebase": 00,
"sectimeout": 0,
"error": "OK"
})
And my parsing class looks like that:
package jsonRequest;
import java.io.IOException;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
public class NewMessageJson {
public Integer poollid;
private String lastMessageId;
private String error;
private String messageBase;
public NewMessageJson(String response) {
response = response.substring(response.indexOf("{"),
response.indexOf("}") + 1); // cut off comment block
JsonFactory factory = new JsonFactory();
JsonParser jp = null;
try {
jp = factory.createJsonParser(response);
} catch (JsonParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
if (jp.nextToken() != JsonToken.START_OBJECT) {
throw new IOException("Server didn't return any data");
}
while (jp.nextToken() != JsonToken.END_OBJECT) {
String fieldName = jp.getCurrentName();
jp.nextToken();
if (fieldName.equals("messagelast")) {
setLastMessageId(jp.getText());
} else if (fieldName.equals("pollid")) {
setPoollid(jp.getIntValue());
} else if (fieldName.equals("messagebase")) {
setMessageBase(jp.getText());
} else if (fieldName.equals("error")) {
setError(jp.getText());
}
}
jp.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NullPointerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
jp.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public Integer getPoollid() {
return poollid;
}
public void setPoollid(Integer poollid) {
this.poollid = poollid;
}
public String getLastMessageId() {
return lastMessageId;
}
public void setLastMessageId(String lastMessageId) {
this.lastMessageId = lastMessageId;
}
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
public String getMessageBase() {
return messageBase;
}
public void setMessageBase(String messageBase) {
this.messageBase = messageBase;
}
}
And when it comes to the line
if (fieldName.equals("messagelast")) {
It crashes and returns NPE.
I have 3 other classes looking exactly like this one and everything works perfectly.

I am pretty sure the reason you are getting the NPE is because you initially instantiate JsonParser jp as null. You assign it to factory.createJsonParser(response) in your try block but do not deal with the error in any way besides printing the stack trace. If there was an error executing factory.createJsonParser(response), you need to make sure nothing else runs.
I would suggest changing your code to this:
...
JsonFactory factory = new JsonFactory();
JsonParser jp = null;
try {
jp = factory.createJsonParser(response);
} catch (JsonParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
System.out.println("There was an error while setting jp to factory.createJsonParser(response). Error message is: " + e1.getMessage());
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
System.out.println("There was an error while setting jp to factory.createJsonParser(response). Error message is: " + e1.getMessage());
}
if(jp != null) {
try {
if (jp.nextToken() != JsonToken.START_OBJECT) {
throw new IOException("Server didn't return any data");
}
while (jp.nextToken() != JsonToken.END_OBJECT) {
String fieldName = jp.getCurrentName();
jp.nextToken();
if (fieldName.equals("messagelast")) {
setLastMessageId(jp.getText());
} else if (fieldName.equals("pollid")) {
setPoollid(jp.getIntValue());
} else if (fieldName.equals("messagebase")) {
setMessageBase(jp.getText());
} else if (fieldName.equals("error")) {
setError(jp.getText());
}
}
jp.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NullPointerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
jp.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
...
This way, you can avoid all NPEs!
EDIT: You should also implement what peeskillet suggested

Related

Exception in thread "pool-1-thread-1" null pointer Exception NoSuchMethodError

I am working on a multi threaded application where i get some request from JMS, threads are running to receive the message. Here how my thread is working:
Model mapper in the try block is causing the issue i think:
patientAdder.addPatient(patientAddMessage, authResult, queueSender, baseUrl, modelMapper);
here is complete code:
Executors.newSingleThreadExecutor().execute(new Runnable() {
public void run() {
while (true) {
SonicQueueMessageSender queueSender = null;
try {
queueSender = new SonicQueueMessageSender(queueConnProvider);
} catch (JMSException e3) {
// TODO Auto-generated catch block
e3.printStackTrace();
}
String patientAddMessage = null;
try {
patientAddMessage = new SonicMessageReceiver(connectionProvider)
.getAddJsonMessage("MirthMessage");
} catch (JMSException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
final AuthModel auth = new AuthModel();
String authResult = null;
final PatientAdder patientAdder = new PatientAdder();
SecurityTokenModel securityToken = null;
String authPostString = null;
try {
authPostString = new ObjectMapper()
.writeValueAsString(auth);
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Auth post string is: "+ authPostString);
System.out.println("base url is: " + baseUrl);
String authPostOutput = client
.doGetAuthRestPost(authPostString, url);
try {
securityToken = getAuth(authPostOutput);
} catch (JsonParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (JsonMappingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
authResult = securityToken.getAccessToken();
try {
patientAdder.addPatient(patientAddMessage, authResult, queueSender, baseUrl, modelMapper);
} catch (JsonParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JsonMappingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// poster.postMessage(patientAddMessage, authResult);
catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
}
}
});
I need to map the message i'm getting in request to a bean class and for that i'm creating a ModelMapper class object that has a function to map properties but when i try to create new object of my mapper class i'm getting a NPE:
Exception in thread "pool-1-thread-1" java.lang.NullPointerException
at com.prnreferral.util.commons.ModelMapper.mapCanonicalMessageToPatientModel(ModelMapper.java:82)
at com.prnreferral.patientprocess.add.PatientAdder.addPatient(PatientAdder.java:52)
at com.prnreferral.patientprocess.add.PIXSAddPatient$1.run(PIXSAddPatient.java:148)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:722)
I'm sure that object is created as i checked it by adding some conditions, but there is something that i'm missing causing this issue
I also tried to add a new function to check if there is any issue with this function, but getting
Exception in thread "pool-1-thread-1" java.lang.NoSuchMethodError: com.prnreferral.util.commons.ModelMapper.printString()V
at com.prnreferral.patientprocess.add.PatientAdder.addPatient(PatientAdder.java:49)
at com.prnreferral.patientprocess.add.PIXSAddPatient$2.run(PIXSAddPatient.java:173)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:722)
I'm stuck on this issue, no idea what to do, can anyone help me. Thanks in advance.

How to not use nested try catch blocks when parsing JSON?

Is there a more elegant solution to my code below than to have multiple nested try-catch blocks for JSONException?
The reason I nest them is because I don't want to rest of the parsing to stop if there is one error in parsing. I want each to be independent of each other.
if (obj.has(GlobalVars.KEY_DESC)) {
try {
JSONObject descObj = obj.getJSONObject(GlobalVars.KEY_DESC);
if (descObj.has(GlobalVars.KEY_COUNTRY)) {
try {
description.put(GlobalVars.KEY_COUNTRY, descObj.getString(GlobalVars.KEY_COUNTRY));
}
catch (JSONException e) { e.printStackTrace(); }
}
if (descObj.has(GlobalVars.KEY_CITY)) {
try {
description.put(GlobalVars.KEY_COUNTRY, descObj.getString(GlobalVars.KEY_CITY));
}
catch (JSONException e) { e.printStackTrace(); }
}
if (descObj.has(GlobalVars.KEY_POSTAL)) {
try {
description.put(GlobalVars.KEY_COUNTRY, descObj.getString(GlobalVars.KEY_POSTAL));
}
catch (JSONException e) { e.printStackTrace(); }
}
if (descObj.has(GlobalVars.KEY_STREET)) {
try {
description.put(GlobalVars.KEY_COUNTRY, descObj.getString(GlobalVars.KEY_STREET));
}
catch (JSONException e) { e.printStackTrace(); }
}
if (descObj.has(GlobalVars.KEY_SUBSTREET)) {
try {
description.put(GlobalVars.KEY_COUNTRY, descObj.getString(GlobalVars.KEY_SUBSTREET));
}
catch (JSONException e) { e.printStackTrace(); }
}
if (descObj.has(GlobalVars.KEY_YEAR)) {
try {
description.put(GlobalVars.KEY_COUNTRY, descObj.getInt(GlobalVars.KEY_YEAR));
}
catch (JSONException e) { e.printStackTrace(); }
}
if (descObj.has(GlobalVars.KEY_SQUARE_METERS)) {
try {
description.put(GlobalVars.KEY_COUNTRY, descObj.getInt(GlobalVars.KEY_SQUARE_METERS));
}
catch (JSONException e) { e.printStackTrace(); }
}
}
catch (JSONException e) { e.printStackTrace(); }
}
You seems to be doing similar stuff in all of your if statements:
try {
description.put(GlobalVars.KEY_COUNTRY, descObj.getString(GlobalVars.KEY_COUNTRY));
}
catch (JSONException e) { e.printStackTrace(); }
So you can move this code to a method and can call that method from each if statement. It will make your code cleaner
I think you don't need to use all these try catch if you use Gson lib, it ignored missing fields and continue the parsing, but you can register the missing fields by using the below code:
package json;
import java.lang.reflect.Field;
import java.lang.reflect.Type;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
public class App {
public static void main(String[] args) {
Gson gson = new GsonBuilder().registerTypeAdapter(
MyAnnotationBean.class,
new AnnotatedDeserializer<MyAnnotationBean>()).create();
String json = "{\"desc\":\"This is desc\",\"country\":\"this is country\"}";
MyAnnotationBean tab = gson.fromJson(json, MyAnnotationBean.class);
System.out.println(tab.desc);
System.out.println(tab.country);
json = "{\"desc\":\"This is desc\"}";
tab = gson.fromJson(json, MyAnnotationBean.class);
System.out.println(tab.desc);
System.out.println(tab.country);
json = "{\"country\":\"This is country\"}";
tab = gson.fromJson(json, MyAnnotationBean.class);
System.out.println(tab.desc);
System.out.println(tab.country);
}
}
class MyAnnotationBean {
public String desc;
public String country;
}
class AnnotatedDeserializer<T> implements JsonDeserializer<T> {
public T deserialize(JsonElement je, Type type,
JsonDeserializationContext jdc) throws JsonParseException {
T obj = new Gson().fromJson(je, type);
Field[] fields = obj.getClass().getDeclaredFields();
for (Field f : fields) {
try {
f.setAccessible(true);
if (f.get(obj) == null) {
// throw new JsonParseException("required json " +
// f.getName());
// add your code to know missing fields
}
} catch (IllegalArgumentException ex) {
ex.printStackTrace();
} catch (IllegalAccessException ex) {
ex.printStackTrace();
}
}
return obj;
}
}

how to not print exception by using HandlerExceptionResolver

public class AtrExceptionResolver implements HandlerExceptionResolver {
private final static Log log =LogFactory.getLog(AtrExceptionResolver.class);
#Override
public ModelAndView resolveException(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex) {
boolean ajaxrequest = false;
if (request.getRequestURI().indexOf("/ajax/") > 0)
ajaxrequest = true;
if (ex instanceof AtrException) {
AtrException atrE = (AtrException) ex;
log.error(
"AtrException:code:" + atrE.getCode() + ",desc:"
+ atrE.getMsg(), ex);
if (ajaxrequest) {
PrintWriter out = null;
try {
out = response.getWriter();
out.print("{\"e\":\"" + atrE.getCode()
+ "\",\"message\":\"" + atrE.getMsg() + "\"}");
out.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
out.close();
}
} else {
try {
goToError(request, response);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} else {
log.error("Exception:desc:" + ex.getMessage(), ex);
if (ajaxrequest) {
PrintWriter out = null;
try {
out = response.getWriter();
out.print("{\"e\":\"3\",\"message\":\"system error\"}");
out.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
out.close();
}
} else {
try {
goToError(request, response);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
private void goToError(HttpServletRequest request,
HttpServletResponse response) throws Exception {
response.sendRedirect(request.getContextPath() + "/jsp/error.jsp");
}
atrException is defined by myself,so I do not want to printStackTrace() in console.only print it in log.
I debug it,found it print by standardwrappervalve.invoke().
How to not print atrException message in console?
If I understand your question then you want the exception stack trace in a String object which you can use it for logging.
You can use below method.
public String getErrorLog(Throwable throwable) {
if (throwable != null) {
StringWriter errors = new StringWriter();
throwable.printStackTrace(new PrintWriter(errors));
return errors.toString();
}
return "";
}
Returned value is stack trace which you can log.
return new ModelAndView();
This way can solve.

Program won't run because variables "may be uninitialized"?

I'm trying to make a new thread for parsing xml from an rss feed. When I click run it says there are errors please correct them etc. I have 2 classes in my project. The other class has no errors and this class below has only warnings that a lot of the things in the try/catch statements may be uninitialized. I understand that and figured I should still be able to run the program anyways, I expect them to be initialized and if they're not that's fine I want to know about it. Is this really what's going on or am I missing something? I thought it would compile if something may be uninitialized but its not certainly uninitialized.
public class RssParse extends Thread {
Thread th=new Thread() {
public void run(){
System.out.println("1");
URL iotd;
try {
iotd = new URL("http://www.nasa.gov/rss/image_of_the_day.rss");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("2");
BufferedReader in;
try {
in = new BufferedReader(new InputStreamReader(iotd.openStream()));
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println("3");
XmlPullParserFactory factory;
try {
factory = XmlPullParserFactory.newInstance();
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
factory.setNamespaceAware(true);
System.out.println("4");
XmlPullParser xpp;
try {
xpp = factory.newPullParser();
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("5");
try {
xpp.setInput(in);
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("6");
int eventType;
try {
eventType = xpp.getEventType();
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(eventType+"!!!!!!!!!!!!!!!!");
while(eventType!=XmlPullParser.END_DOCUMENT){
if(eventType==XmlPullParser.START_DOCUMENT){
System.out.println("start");
}
}
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}//method
};//thread
}//class
Look at this try/catch block for example :
URL iotd;
try {
iotd = new URL("http://www.nasa.gov/rss/image_of_the_day.rss");
} catch (MalformedURLException e) {
e.printStackTrace();
}
If iotd = new URL("...") fails, iotd will remain uninitialized.
There are two ways to deal with this :
Assign a default value to iotd, like : URL iotd = null; However, it's bad here because if you use iotd later its value may be null and can throw a NullPointerException.
Stop the execution of your function if something failed instead of just printing the stack trace. For example you can add a return statement in the catch block :
URL iotd;
try {
iotd = new URL("http://www.nasa.gov/rss/image_of_the_day.rss");
} catch (MalformedURLException e) {
e.printStackTrace();
return;
}
All the warnings you are getting are because all your catch blocks are not dealing with the exception at all (just printing the stacktrace to standard out).
Let's see it through an example:
URL iotd;
try {
iotd = new URL("http://www.nasa.gov/rss/image_of_the_day.rss");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
at that snipped you are declaring a iotd variable as a URL but without initializing it (not assigning any value), you do it inside the try block - which isn't wrong by the way. However if for any reason the statement inside the try block throws an exception program flow will go to the catch block leaving the iotd variable with its initial value (unassigned).
So, in that case, execution of the program will continue and when reaching this statement:
in = new BufferedReader(new InputStreamReader(iotd.openStream()));
it will find no value assigned to the iotd variable.
To remove the warning regarding the uninitialized value you can either assign a null value to the variable when declaring it or rethrow another exception inside the catch block, stopping the program flow.
In the other hand, the snippet you posted here is not just one class, it's actually two as you are extending the Thread class and then creating an anonymous one inside its body. Using threads is easier than that in Java, just implement the Runnable interface and then instantiate a new thread from that interface:
public class MyRunnable implements Runnable {
public void run() {
// do stuff
}
}
and then:
new Thread(new MyRunnable()).start();
cheers
you need to initialize the variables above the try catch block, or give them a value in catch or finally block
find updated code here
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
public class RssParse extends Thread {
Thread th=new Thread() {
public void run(){
System.out.println("1");
URL iotd=null;
try {
iotd = new URL("http://www.nasa.gov/rss/image_of_the_day.rss");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("2");
BufferedReader in=null;
try {
in = new BufferedReader(new InputStreamReader(iotd.openStream()));
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println("3");
XmlPullParserFactory factory=null;
try {
factory = XmlPullParserFactory.newInstance();
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
factory.setNamespaceAware(true);
System.out.println("4");
XmlPullParser xpp=null;
try {
xpp = factory.newPullParser();
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("5");
try {
xpp.setInput(in);
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("6");
int eventType=-1; // set to a default value of your choice
try {
eventType = xpp.getEventType();
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(eventType+"!!!!!!!!!!!!!!!!");
while(eventType!=XmlPullParser.END_DOCUMENT){
if(eventType==XmlPullParser.START_DOCUMENT){
System.out.println("start");
}
}
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}//method
};//thread
}//class

Using sockets and Object IO streams in Android programming

I'm trying to implement multiplayer in a game I've been writing, and I've gotten everything to successfully connect (I think..), but when I'm running it, there's an EOFException thrown by the client, and the object (an ArrayList) isn't successfully received.
Code for the server thread:
class ServerThread implements Runnable
{
ServerSocket server = null;
Socket controlSocket = null;
ObjectOutputStream outStream = null;
ObjectInputStream inStream = null;
#Override
public void run() {
setupConnection();
while(true){
sendObject(out.getStuff());
}
}
void setupConnection(){
Log.e("OUTPUTSHOOTER","init-connect");
try {
server = new ServerSocket(SERVERPORT);
Log.e("OUTPUTSHOOTER","server initiated port: "+SERVERPORT);
controlSocket = server.accept();
Log.e("OUTPUTSHOOTER","connected");
inStream = new ObjectInputStream(controlSocket.getInputStream());
outStream = new ObjectOutputStream(controlSocket.getOutputStream());
} catch (StreamCorruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.e("OUTPUTSHOOTER",server+" "+controlSocket+" "+inStream+" "+outStream);
}
public Object recieveObject(){
Object o = null;
try {
o = inStream.readObject();
} catch (OptionalDataException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return o;
}
public void sendObject(Object o)
{
try {
outStream.writeObject(o);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
And then the code for the client:
class ClientThread implements Runnable
{
Socket controlSocket = null;
ObjectOutputStream outStream = null;
ObjectInputStream inStream = null;
#Override
public void run() {
setupConnection();
while(true){
Log.e("OUTPUTSHOOTER","recieving");
Object in = recieveObject();
if(in!= null && in instanceof ArrayList)
{
Log.e("OUTPUTSHOOTER","loading");
out.load((ArrayList<UniverseObject>)in);
}
}
}
void setupConnection(){
Log.e("OUTPUTSHOOTER","ip: "+SERVERIP);
while(controlSocket == null) {
try {
controlSocket = new Socket(SERVERIP,SERVERPORT);
Log.e("OUTPUTSHOOTER","socket connected");
} catch (IOException e) {
e.printStackTrace();
}
}
try {
Log.e("OUTPUTSHOOTER","attempting streams");
outStream = new ObjectOutputStream(controlSocket.getOutputStream());
Log.e("OUTPUTSHOOTER","output working");
inStream = new ObjectInputStream(controlSocket.getInputStream());
Log.e("OUTPUTSHOOTER","streams connected");
} catch (StreamCorruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public Object recieveObject(){
Object o = null;
try {
o = inStream.readObject();
} catch (OptionalDataException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return o;
}
public void sendObject(Object o)
{
try {
outStream.writeObject(o);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
What does this mean? And perhaps more importantly, how can I fix it? Thanks in advance..
I don't see you closing your outputstream.
See this SO topic: Problem serializing and deserializing ArrayList
Turns out the server wasn't properly initiating it's input and output streams, even though its sockets were successful. Dunno why, but it only works if I started with the output stream first, then the input (?). Having some other really strange bugs, but at least the communication seems to work.. I'll look more in to them before posting here about it. Thanks guys!

Categories