Skip to content

Commit 70ffe0d

Browse files
author
Jeremy Williams
committedJun 3, 2011
fix CalledFromWrongThreadException error
1 parent 9affa91 commit 70ffe0d

File tree

1 file changed

+31
-9
lines changed

1 file changed

+31
-9
lines changed
 

‎src/com/strumsoft/phonegap/websocket/WebSocket.java

+31-9
Original file line numberDiff line numberDiff line change
@@ -282,6 +282,7 @@ public void run() {
282282
try {
283283
_connect();
284284
} catch (IOException e) {
285+
e.printStackTrace();
285286
this.onError(e);
286287
}
287288
}
@@ -321,7 +322,7 @@ public void send(String text) {
321322
} else {
322323
this.onError(new NotYetConnectedException());
323324
}
324-
} catch (IOException e) {
325+
} catch (Exception e) {
325326
this.onError(e);
326327
}
327328
}
@@ -333,21 +334,41 @@ public void send(String text) {
333334
* Message from websocket server
334335
*/
335336
public void onMessage(String msg) {
337+
final String data = msg;
336338
Log.v("websocket", "Received a message: " + msg);
337-
appView.loadUrl(buildJavaScriptData(EVENT_ON_MESSAGE, msg));
339+
appView.post(new Runnable() {
340+
public void run() {
341+
appView.loadUrl(buildJavaScriptData(EVENT_ON_MESSAGE, data));
342+
}
343+
});
338344
}
339345

340346
public void onOpen() {
341-
appView.loadUrl(buildJavaScriptData(EVENT_ON_OPEN, BLANK_MESSAGE));
347+
Log.v("websocket", "Connected!");
348+
appView.post(new Runnable() {
349+
public void run() {
350+
appView.loadUrl(buildJavaScriptData(EVENT_ON_MESSAGE, BLANK_MESSAGE));
351+
}
352+
});
342353
}
343354

344355
public void onClose() {
345-
appView.loadUrl(buildJavaScriptData(EVENT_ON_CLOSE, BLANK_MESSAGE));
356+
appView.post(new Runnable() {
357+
public void run() {
358+
appView.loadUrl(buildJavaScriptData(EVENT_ON_MESSAGE, BLANK_MESSAGE));
359+
}
360+
});
346361
}
347362

348363
public void onError(Throwable t) {
349-
String msg = t.getMessage();
350-
appView.loadUrl(buildJavaScriptData(EVENT_ON_ERROR, msg));
364+
final String msg = t.getMessage();
365+
Log.v("websocket", "Error: " + msg);
366+
t.printStackTrace();
367+
appView.post(new Runnable() {
368+
public void run() {
369+
appView.loadUrl(buildJavaScriptData(EVENT_ON_MESSAGE, msg));
370+
}
371+
});
351372
}
352373

353374
public String getId() {
@@ -372,11 +393,12 @@ public int getReadyState() {
372393
* @return
373394
*/
374395
private String buildJavaScriptData(String event, String msg) {
375-
String b64EncodedMsg;
396+
String b64EncodedMsg = "Error!";
376397
try{
377-
b64EncodedMsg = Base64.encodeBytes(msg.getBytes(UTF8_CHARSET));
398+
if(msg != null) {
399+
b64EncodedMsg = Base64.encodeBytes(msg.getBytes(UTF8_CHARSET));
400+
}
378401
} catch(Exception e) {
379-
b64EncodedMsg = "Base64 Encoding Error!";
380402
e.printStackTrace();
381403
}
382404
String _d = "javascript:WebSocket." + event + "(" + "{" + "\"_target\":\"" + id + "\","

0 commit comments

Comments
 (0)
Failed to load comments.