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

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

Related

How to read text from doc or pdf in JodConverter

Caused by:
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.io.File.isDirectory()' on a null object reference
LocalOfficeManager officeManager = LocalOfficeManager.install();
try {
// Start an office process and connect to the started instance (on port 2002).
officeManager.start();
File inputFile = new File("storage/emulated/0/COVID-19/111.pdf");
wordtext = String.valueOf(JodConverter.convert(inputFile));
} catch (OfficeException e) {
e.printStackTrace();
} finally {
// Stop the office process
OfficeUtils.stopQuietly(officeManager);
}
E/AndroidRuntime: FATAL EXCEPTION: main Process: handbook_multi_maker.TJ, PID: 17976 java.lang.RuntimeException: Unable to start activity ComponentInfo{handbook_multi_maker.TJ/TJ.SecondActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.io.File.isDirectory()' on a null object reference at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3107) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3250) 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:1947) at android.os.Handler.dispatchMessage(Handler.java:106) at android.os.Looper.loop(Looper.java:214) at android.app.ActivityThread.main(ActivityThread.java:7032) 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:964) Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.io.File.isDirectory()' on a null object reference at org.jodconverter.local.office.LocalOfficeUtils.validateOfficeHome(LocalOfficeUtils.java:339) at org.jodconverter.local.office.LocalOfficeManager$Builder.build(LocalOfficeManager.java:169) at org.jodconverter.local.office.LocalOfficeManager.install(LocalOfficeManager.java:78) at TJ.SecondActivity.initWebView(SecondActivity.java:132) at TJ.SecondActivity.onCreate(SecondActivity.java:104) at android.app.Activity.performCreate(Activity.java:7327) at android.app.Activity.performCreate(Activity.java:7318) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3087) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3250) 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:1947) at android.os.Handler.dispatchMessage(Handler.java:106) at android.os.Looper.loop(Looper.java:214) at android.app.ActivityThread.main(ActivityThread.java:7032) 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:964)
You got this error because the default behavior of JODConverter is to auto-detect the office (LibreOffice or Apache OpenOffice) installation you will be working with. In your particular case, the office home directory was not found (thus null).
So, if your office installation is within a custom directory, you can use the officeHome property.
Here's your updated code:
OfficeManager officeManager =
LocalOfficeManager.builder()
.officeHome("Path to your office home")
.install()
.build();
try {
// Start an office process and connect to the started instance (on port 2002).
officeManager.start();
File inputFile = new File("storage/emulated/0/COVID-19/111.pdf");
wordtext = String.valueOf(JodConverter.convert(inputFile));
} catch (OfficeException e) {
e.printStackTrace();
} finally {
// Stop the office process
OfficeUtils.stopQuietly(officeManager);
}

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();
}
});

android OkHttpClient Requesting Error

I am trying to store some data in mysql database using my android app. I am using okhttp3 to send request , but an error appears to me at this line:
client.newCall(request).execute();
I tried it on local machine and online but it gives me the same error here is the code ,
public class MainActivity extends AppCompatActivity {
String token1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
System.out.println("MainActivity is :" + FirebaseInstanceId.getInstance().getToken());
FirebaseMessaging.getInstance().subscribeToTopic("test");
FirebaseInstanceId.getInstance().getToken();
token1=FirebaseInstanceId.getInstance().getToken();
}
public void clicking(View view) {
OkHttpClient client = new OkHttpClient();
RequestBody body = new FormBody.Builder()
.add("Token",token1)
.build();
okhttp3.Request request = new okhttp3.Request.Builder()
.url("http://saleh923.byethost8.com/hii.html")
.post(body)
.build();
try {
client.newCall(request).execute();
} catch (IOException e) {
e.printStackTrace();
}
}
}
and here is the log:
com.example.user.firebasenot E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.user.firebasenot, PID: 3280
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:5198) 
at android.view.View$PerformClick.run(View.java:21147) 
at android.os.Handler.handleCallback(Handler.java:739) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5417) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1273)
at java.net.InetAddress.lookupHostByName(InetAddress.java:431)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
at java.net.InetAddress.getAllByName(InetAddress.java:215)
at okhttp3.Dns$1.lookup(Dns.java:39)
at okhttp3.internal.connection.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:172)
at okhttp3.internal.connection.RouteSelector.nextProxy(RouteSelector.java:138)
at okhttp3.internal.connection.RouteSelector.next(RouteSelector.java:80)
at okhttp3.internal.connection.StreamAllocation.findConnection(StreamAllocation.java:178)
at okhttp3.internal.connection.StreamAllocation.findHealthyConnection(StreamAllocation.java:129)
at okhttp3.internal.connection.StreamAllocation.newStream(StreamAllocation.java:98)
at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.java:42)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:67)
at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.java:109)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:67)
at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.java:93)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92)
at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:124)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:67)
at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:170)
at okhttp3.RealCall.execute(RealCall.java:60)
at com.example.user.firebasenot.MainActivity.clicking(MainActivity.java:54)
at java.lang.reflect.Method.invoke(Native Method) 
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288) 
at android.view.View.performClick(View.java:5198) 
at android.view.View$PerformClick.run(View.java:21147) 
at android.os.Handler.handleCallback(Handler.java:739) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5417) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
The error message says it all:
Caused by: android.os.NetworkOnMainThreadException
You are not supposed to make network requests on the main (aka UI) thread.
There are many ways in which you can make this request on a different thread, here's one:
final OkHttpClient client = new OkHttpClient();
RequestBody body = new FormBody.Builder()
.add("Token",token1)
.build();
final okhttp3.Request request = new okhttp3.Request.Builder()
.url("http://saleh923.byethost8.com/hii.html")
.post(body)
.build();
final Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
client.newCall(request).execute();
} catch (IOException e) {
e.printStackTrace();
}
}
});
But okhttp makes it easier for us to make asynchronous requests using the enqueue method:
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
#Override
public void onResponse(Call call, final Response response) throws IOException {
if (!response.isSuccessful()) {
throw new IOException("Unexpected code " + response);
}
// you code to handle response
}
);
Here is how you should go about debugging your code:
Your 1st cue in the log that states,
java.lang.IllegalStateException: Could not execute method for
android:onClick
tells you that there is something wrong with you onClick method implementation, which in this case is clicking(View view). You then go on to hunt for your next hint, which is your 2nd cue in the log that states,
Caused by: android.os.NetworkOnMainThreadException
and that certainly is happening in your clicking(View view) method implementation line that you pointed out. It's making a network request from the main thread; and oh!, Android system reckons it a bad thing.
So what is the way out? You can use any of the following alternatives methods:
Alternative 1: View.post(Runnable) or View.postDelayed(Runnable, long)
Alternative 2: Activity.runOnUiThread(Runnable)
Alternative 3: Handler
Alternative 4: AsyncTask
I have demoed each of these alternatives, including the wrong way like the one you showcased in my Github project titled, DemoThreadsAndProcesses. Please feel free to (fork and) download it and play with it to see which implementation alternative suits your interest and go about using it in you own very project.
For quick check, I'll go about implementing your clicking(View view) like below:
public void clicking(View view) {
new MakeNetworkRequestAsyncTask().execute();
}
private void makeNetworkRequest() {
OkHttpClient client = new OkHttpClient();
RequestBody body = new FormBody.Builder()
.add("Token",token1)
.build();
okhttp3.Request request = new okhttp3.Request.Builder()
.url("http://saleh923.byethost8.com/hii.html")
.post(body)
.build();
try {
client.newCall(request).execute();
} catch (IOException e) {
e.printStackTrace();
}
}
private class MakeNetworkRequestAsyncTask extends AsyncTask<Void, Void, Void> {
// The system calls this to perform work in a worker thread and
// delivers it the parameters given to AsyncTask.execute()
protected transient Void doInBackground(Void[] params) {
makeNetworkRequest();
}
// The system calls this to perform work in the UI thread and
// delivers the result from doInBackground() method defined above
#Override
protected void onPostExecute(Void result) {}
}
Hope that helps!

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.

Android FTP connection problems [duplicate]

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.

Categories