I created a class to check the internet available to upload a string to the server.
My application does not show any error or warning in log cat. So, I can't post any log.
But when I connected or not connect to the internet, it always shows the message: You do not connect to the internet.
in the else clause.
When I debug to isInternetAvailable
method, it go to the first line:
InetAddress ipAddr = InetAddress.getByName("google.com");
After, it throws exception like:
cause = {NetworkOnMainThreadException} "android.os.NetworkOnMainThreadException"
and return false.
Code bellow to show check internet available, all code in a class extends BroadcastReceiver
:
public boolean isInternetAvailable() {
try {
InetAddress ipAddr = InetAddress.getByName("google.com");
if (ipAddr.equals("")) {
return false;
} else {
return true;
}
} catch (Exception e) {
return false;
}
}
@Override
public void onReceive(final Context context, final Intent intent) {
String textToServer = "text example";
if(isInternetAvailable()){
sendToServer(context, textToServer.toString());
} else {
Toast.makeText(context, "You not connect to internet.", Toast.LENGTH_LONG).show();
}
}
public void sendToServer(final Context context, final String text){
contact = new AddContactActivity();
new Thread(new Runnable() {
@Override
public void run() {
try {
String textparam = "text1=" + URLEncoder.encode(text, "UTF-8");
URL scripturl = new URL(scripturlstring);
HttpURLConnection connection = (HttpURLConnection) scripturl.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setFixedLengthStreamingMode(textparam.getBytes().length);
OutputStreamWriter contentWriter = new OutputStreamWriter(connection.getOutputStream());
contentWriter.write(textparam);
contentWriter.flush();
contentWriter.close();
InputStream answerInputStream = connection.getInputStream();
final String answer = getTextFromInputStream(answerInputStream);
if(answer!="") {
String[] contactInfo = answer.split(":::::");
if(!contactExists(context, contactInfo[1])) {
contact.insertContact(context, contactInfo[0], contactInfo[1], contactInfo[2], contactInfo[3], contactInfo[4]);
} else {
return;
}
}
answerInputStream.close();
connection.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}