Android FTP connection problems [duplicate] - java

This question already has answers here:
How can I fix 'android.os.NetworkOnMainThreadException'?
(66 answers)
Closed 7 years ago.
Hi I have been trying for two days to get a simple ftp connection to transfer a small xml file. I have tried lots of different examples of code, but all seem to give the same errors.
Main FTP class code:
public class MyFTPClientFunctions {
public FTPClient mFTPClient = null;
public boolean ftpConnect(String host, String username, String password, int port) {
try {
mFTPClient = new FTPClient();
// connecting to the host
mFTPClient.connect(host, port);
// now check the reply code, if positive mean connection success
if (FTPReply.isPositiveCompletion(mFTPClient.getReplyCode())) {
// login using username & password
boolean status = mFTPClient.login(username, password);
mFTPClient.setFileType(FTP.BINARY_FILE_TYPE);
mFTPClient.enterLocalPassiveMode();
return status;
}
//Log.d(TAG, "Error: could not connect to host " + host);
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
private Context getApplicationContext() {
return null;
}
}
Main Activity code to send
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//set up FTP file transfer here
MyFTPClientFunctions ftpSend = new MyFTPClientFunctions();
ftpSend.ftpConnect("xxxxxx.asuscomm.com","admin","xxxxxxxxxx",21);
}
LogCat messages
06-22 12:09:21.460 17329-17329/com.example.rats.moham_2 E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.rats.moham_2, PID: 17329
android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1147)
at java.net.InetAddress.lookupHostByName(InetAddress.java:418)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
at java.net.InetAddress.getByName(InetAddress.java:305)
at org.apache.commons.net.SocketClient.connect(SocketClient.java:203)
at com.example.rats.moham_2.MyFTPClientFunctions.ftpConnect(MyFTPClientFunctions.java:25)
at com.example.rats.moham_2.MainActivity$3.onClick(MainActivity.java:155)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5257)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

This Exception is usualy thrown, if you are using the network on the main thread.
Please use Async Tasks.

Related

Send data to a Php Script with Android Studio [duplicate]

This question already has answers here:
How can I fix 'android.os.NetworkOnMainThreadException'?
(66 answers)
Closed 3 years ago.
I have to send some parameters from my Android application to a Php script, for a database insert.
I tried this script on Eclipse and it works fine.
But when I try to run it on Android it crashes.
public static void Insert(){
try {
// open a connection to the site
URL url = new URL("http://192.168.1.105/JavaInsert.php");
URLConnection con = url.openConnection();
// activate the output
con.setDoOutput(true);
PrintStream ps = new PrintStream(con.getOutputStream());
// send your parameters to your site
ps.print("&email=random#gmail.com");
//ps.print("&Company=Company");
//ps.print("&Shares=Shares");
//ps.print("&Date=Date");
con.getInputStream();
ps.close();
} catch (MalformedURLException e1) {
e1.printStackTrace();
System.out.print("Db error 1");
} catch (IOException e2) {
e2.printStackTrace();
System.out.print("Db error 1");
}
}
There are these errors in the LogCat section
07-28 14:28:07.259 20554-20554/com.example.ivan.rocketsocialstudioapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.ivan.rocketsocialstudioapp, PID: 20554
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:389)
at android.view.View.performClick(View.java:6663)
at android.view.View.performClickInternal(View.java:6635)
at android.view.View.access$3100(View.java:794)
at android.view.View$PerformClick.run(View.java:26199)
at android.os.Handler.handleCallback(Handler.java:907)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:216)
at android.app.ActivityThread.main(ActivityThread.java:7593)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:987)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:384)
at android.view.View.performClick(View.java:6663) 
at android.view.View.performClickInternal(View.java:6635) 
at android.view.View.access$3100(View.java:794) 
at android.view.View$PerformClick.run(View.java:26199) 
at android.os.Handler.handleCallback(Handler.java:907) 
at android.os.Handler.dispatchMessage(Handler.java:105) 
at android.os.Looper.loop(Looper.java:216) 
at android.app.ActivityThread.main(ActivityThread.java:7593) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:987) 
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1523)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:390)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:231)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:213)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:436)
at java.net.Socket.connect(Socket.java:621)
at com.android.okhttp.internal.Platform.connectSocket(Platform.java:145)
at com.android.okhttp.internal.io.RealConnection.connectSocket(RealConnection.java:141)
at com.android.okhttp.internal.io.RealConnection.connect(RealConnection.java:112)
at com.android.okhttp.internal.http.StreamAllocation.findConnection(StreamAllocation.java:184)
at com.android.okhttp.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:126)
at com.android.okhttp.internal.http.StreamAllocation.newStream(StreamAllocation.java:95)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:281)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:224)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:461)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:127)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:258)
at com.example.ivan.rocketsocialstudioapp.MainActivity.Insert(MainActivity.java:72)
at com.example.ivan.rocketsocialstudioapp.MainActivity.send(MainActivity.java:45)
at java.lang.reflect.Method.invoke(Native Method) 
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:384) 
at android.view.View.performClick(View.java:6663) 
at android.view.View.performClickInternal(View.java:6635) 
at android.view.View.access$3100(View.java:794) 
at android.view.View$PerformClick.run(View.java:26199) 
at android.os.Handler.handleCallback(Handler.java:907) 
at android.os.Handler.dispatchMessage(Handler.java:105) 
at android.os.Looper.loop(Looper.java:216) 
at android.app.ActivityThread.main(ActivityThread.java:7593) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:987) 
07-28 14:28:07.284 20554-20554/com.example.ivan.rocketsocialstudioapp I/Process: Sending signal. PID: 20554 SIG: 9
The Php script works with Eclipse.
I've also already added the android Network and Internet Permissions
its because you cant run network operation on main thread it will cause the NetworkOnMainThreadException which you have
try networking libraries or do the operation on a AsyncTask
You need to create a Runnable Thread or AsyncTask to run network operations.
Check out my example below
private void login() {
JSONObject request = new JSONObject();
try {
//Populate the request parameters
request.put(KEY_USERNAME, username);
request.put(KEY_PASSWORD, password);
//Log.v("test", request.toString());
} catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest jsArrayRequest = new JsonObjectRequest
(Request.Method.POST, login_url, request, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
pDialog.dismiss();
try {
//Check if user got logged in successfully
if (response.getInt(KEY_STATUS) == 0) {
session.loginUser(username, response.getString(KEY_FULL_NAME));
loadDashboard();
} else {
Toast.makeText(getApplicationContext(),
response.getString(KEY_MESSAGE), Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
pDialog.dismiss();
//Display error message whenever an error occurs
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
}
});

Socket Exception while trying to connect to TCP Server [duplicate]

This question already has answers here:
How can I fix 'android.os.NetworkOnMainThreadException'?
(66 answers)
Closed 3 years ago.
I'm trying to check if I can establish a connection to my TCP server with this simple method:
public static boolean serverListening()
{
Socket s = null;
try
{
s = new Socket("192.168.42.213", 80);
return true;
}
catch (Exception e)
{
Log.d("SocketException", "Exception",e);
return false;
}
finally
{
if(s != null)
try {s.close();}
catch(Exception e){}
}
}
My server is already working as I'm able to connect to it with chrome inside the emulator so the problem must lie in my code.
Im getting the following exception if I try to run the code:
SocketException
android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1513)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:389)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:230)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:212)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:436)
at java.net.Socket.connect(Socket.java:621)
at java.net.Socket.connect(Socket.java:570)
at java.net.Socket.<init>(Socket.java:450)
at java.net.Socket.<init>(Socket.java:218)
at com.example.batterymonitor.MainActivity.serverListening(MainActivity.java:104)
at com.example.batterymonitor.MainActivity.onCreate(MainActivity.java:58)
at android.app.Activity.performCreate(Activity.java:7136)
at android.app.Activity.performCreate(Activity.java:7127)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2893)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Thank you very much for your help!
In android you can't run network related actions on the main thread - you need to run them on a different thread, for example:
Thread mThread = new Thread(new Runnable() {
#Override
public void run() {
try {
//Put your code that you want to run in here(check your connection for example)
} catch (Exception e) {
e.printStackTrace();
}
}
});
mThread.start

Checking for internet connectivity in Android app [duplicate]

This question already has answers here:
How can I fix 'android.os.NetworkOnMainThreadException'?
(66 answers)
Closed 7 years ago.
I'm trying to check for INTERNET connectivity from an Android app but just keep running in to problems.
I'm NOT looking for code that tests for an available network connection - I've got that bit working - this is to test whether I can reach an internet site or not.
(I appreciate that if I am behind a system which presents a logon screen instead of the requested site, I may not get the exact result I want, but I will handle that later)
Thanks to the following question I think I've made some progress, but when I run the app it crashes out (error info below).
The code I have so far is as follows (and I must admit that I find the try/catch stuff a bit puzzling and tedious :-/ )
static public boolean isInternetReachable() {
int statusCode = -1;
try{
URL url = new URL("http://www.google.com/humans.txt");
HttpURLConnection http = (HttpURLConnection) url.openConnection();
statusCode = http.getResponseCode();
http.disconnect();
} catch (MalformedURLException ex) {
return false;
} catch (IOException ex) {
return false;
}
if (statusCode == HttpURLConnection.HTTP_OK) {
return true;
}
else
{
//connection is not OK
return false;
}
}
I'm sure there are neater ways to do this and so any general advice is welcome.
The error that I'm getting when the app crashes is:
01-24 19:53:14.767 10617-10617/com.nooriginalthought.bluebadgeparking E/AndroidRuntime:
FATAL EXCEPTION: main
Process: com.nooriginalthought.bluebadgeparking, PID: 10617
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.nooriginalthought.bluebadgeparking/com.nooriginalthought.bluebadgeparking.PreLoadChecks}: android.os.NetworkOnMainThreadException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2411)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2474)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1359)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:155)
at android.app.ActivityThread.main(ActivityThread.java:5696)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1028)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823)
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1155)
at java.net.InetAddress.lookupHostByName(InetAddress.java:418)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
at java.net.InetAddress.getAllByName(InetAddress.java:215)
at com.android.okhttp.HostResolver$1.getAllByName(HostResolver.java:29)
at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:236)
at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:124)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:272)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:211)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:373)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:323)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:491)
at com.nooriginalthought.bluebadgeparking.PreLoadChecks.isInternetReachable(PreLoadChecks.java:41)
at com.nooriginalthought.bluebadgeparking.PreLoadChecks.onCreate(PreLoadChecks.java:70)
at android.app.Activity.performCreate(Activity.java:5958)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1129)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2364)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2474) 
at android.app.ActivityThread.access$800(ActivityThread.java:144) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1359) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:155) 
at android.app.ActivityThread.main(ActivityThread.java:5696) 
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1028) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823) 
As David is mentioning in the comments, you should just Google for the Exception name and try to get a turnaround by yourself.
By looking at the StackOverflow answer that he is referring to, you need to make all network communications outside the Main thread. The most used way to do this is by creating an AsyncTask.
In your case, it would look (you can create a new InternetTask.java or just append it to your current MainActivity.java) something like:
class InternetTask extends AsyncTask<Void, Void, Boolean>{
private MainActivity activity;
InternetTask(MainActivity activity){
this.activity = activity;
}
#Override
protected Boolean doInBackground(Void... params) {
int statusCode = -1;
try{
URL url = new URL("http://www.google.com/humans.txt");
HttpURLConnection http = (HttpURLConnection) url.openConnection();
statusCode = http.getResponseCode();
http.disconnect();
} catch (MalformedURLException ex) {
return false;
} catch (IOException ex) {
return false;
}
if (statusCode == HttpURLConnection.HTTP_OK) {
return true;
}
else
{
//connection is not OK
return false;
}
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
activity.receiveMagic(aBoolean);
}
}
Then, you just need to add a new public method in your activity to receive the boolean in your MainActivity.
public void receiveMagic(Boolean isGood){
if (isGood){
Toast.makeText(MainActivity.this, "It is good", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(MainActivity.this, "It is not connected", Toast.LENGTH_SHORT).show();
}
}
And you would need to call your new AsyncTask from your Activity with:
new InternetTask(this).execute();
Make sure you add the internet permission to your Manifest also.

Query working on local backend but not on deployed backend

class EndpointsAsyncTask extends AsyncTask<Void, Void, List<Quote>> {
private static QuoteEndpoint myApiService = null;
private Context context;
EndpointsAsyncTask(Context context) {
this.context = context;
}
#Override
protected List<Quote> doInBackground(Void... params) {
if(myApiService == null) { // Only do this once
/*QuoteEndpoint.Builder builder = new QuoteEndpoint.Builder(AndroidHttp.newCompatibleTransport(),
new AndroidJsonFactory(), null)
// options for running against local devappserver
// - 10.0.2.2 is localhost's IP address in Android emulator
// - turn off compression when running against local devappserver
.setRootUrl("http://10.0.2.2:8080/_ah/api/")
.setGoogleClientRequestInitializer(new GoogleClientRequestInitializer() {
#Override
public void initialize(AbstractGoogleClientRequest<?> abstractGoogleClientRequest) throws IOException {
abstractGoogleClientRequest.setDisableGZipContent(true);
}
});*/
// end options for devappserver
QuoteEndpoint.Builder builder = new QuoteEndpoint.Builder(AndroidHttp.newCompatibleTransport(), new AndroidJsonFactory(), null)
.setRootUrl("https://momcares-987.appspot.com/_ah/api/");
myApiService = builder.build();
}
try {
return myApiService.listQuote().execute().getItems();
} catch (IOException e) {
return Collections.EMPTY_LIST;
}
}
#Override
protected void onPostExecute(List<Quote> result) {
for (Quote q : result) {
Toast.makeText(context, q.getWho() + " : " + q.getWhom(), Toast.LENGTH_LONG).show();
}
}
}
The above class has been included in my MainActivity.java file.
http://rominirani.com/2014/08/26/gradle-tutorial-part-9-cloud-endpoints-persistence-android-studio/
I have been following this tutorial. I manually inserted quotes (Quote is the bean I am using) in the API Explorer and I successfully get the list of quotes in my emulator when I run the local server and test. However, when I deploy the same backend and run the application, I get a NullPointerException in the onPostExecuteMethod. Please help. Thanks!
Error Log:
06-26 11:50:19.889 26342-26342/com.sickstudios.sickapplication W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x430d4140)
06-26 11:50:19.909 26342-26342/com.sickstudios.sickapplication E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.sickstudios.sickapplication, PID: 26342
java.lang.NullPointerException
at com.sickstudios.sickapplication.EndpointsAsyncTask.onPostExecute(MainActivity.java:64)
at com.sickstudios.sickapplication.EndpointsAsyncTask.onPostExecute(MainActivity.java:25)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:149)
at android.app.ActivityThread.main(ActivityThread.java:5257)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:817)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:633)
at dalvik.system.NativeStart.main(Native Method)
06-26 11:50:23.639 26342-26342/com.sickstudios.sickapplication I/Process﹕ Sending signal. PID: 26342 SIG: 9
Try this:
http://www.momcares-987.appspot.com/_ah/api/
Sometimes https calls raise the connectivity issue.

Android with websocket communication (Node Websocket server and Android Java Client). Dosen't work on Android 4

I tried to use as a Android client Websocket - weberknecht with a thread to send every second a message to a Nodejs Websocket (js): Node WebSocket Server
It work fine on android 2 or 2.3.3, but when i trie on android 4 i get an error on websocket.connect();
Do you know why or what i am doing wrong?
My code is:
public class MainThread extends Thread {
private boolean is_running;
private URI url = null;
private de.roderick.weberknecht.WebSocket websocket = null;
public MainThread() {
this.is_running = false;
try {
url = new URI("ws://192.168.1.88:8088/");
websocket = new WebSocketConnection(url);
websocket.setEventHandler(new WebSocketEventHandler() {
public void onOpen(){
System.out.println("--open");
}
public void onMessage(WebSocketMessage message){
System.out.println("--received message: " + message.getText());
}
public void onClose(){
System.out.println("--close");
}
});
} catch (WebSocketException wse) {
wse.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (URISyntaxException use) {
use.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
#Override
public void run() {
while(is_running){
try {
websocket.send("hello world");
Thread.sleep(10000);
}
catch (WebSocketException wse) {
wse.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void set_running(boolean is_running) {
if(is_running == true)
try {
websocket.connect();
this.is_running = is_running;
} catch (WebSocketException e) {
System.out.println(e.toString());
//e.printStackTrace();
}
}
}
and the error I get on android 4:
ERROR/AndroidRuntime(562): FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.biskis.test.websocket/com.biskis.test.websocket.GameActivity}: android.os.NetworkOnMainThreadException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
at android.app.ActivityThread.access$600(ActivityThread.java:123)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)
at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
at libcore.io.IoBridge.connect(IoBridge.java:112)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
at java.net.Socket.startupSocket(Socket.java:566)
at java.net.Socket.tryAllAddresses(Socket.java:127)
at java.net.Socket.<init>(Socket.java:177)
at java.net.Socket.<init>(Socket.java:149)
at de.roderick.weberknecht.WebSocketConnection.createSocket(WebSocketConnection.java:238)
at de.roderick.weberknecht.WebSocketConnection.connect(WebSocketConnection.java:83)
at com.biskis.test.websocket.MainThread.set_running(MainThread.java:76)
at com.biskis.test.websocket.GameActivity.onCreate(GameActivity.java:20)
at android.app.Activity.performCreate(Activity.java:4465)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
... 11 more
Or do you know how to implement this in a better way to comunicate a client (java, android) to a server (nodejs, websocket) ?
Thank you.
Don't connect to the Websocket on the main Thread (i.e. in GameActivity.onCreate) and the error will go away. You could use an AsyncTask to connect to the Websocket in the background.
Blocking the main thread by I/O operations (and network access is ultimately a I/O operation) will lead (in the worst case) to a sluggish user interface or Android killing your application because it didn't react timely. See the designing for responsiveness document.

Categories