0

Been trying to send a datagram package to the server, which does work when the targetSdkVersion and compileSdkVersion is set to 8 (2.2). But the problem arises when i try do the same after changing the targetSdkVersion to 22 (5.1) (The theme gets changed to material). The app gets installed but the packet does not get sent and an exception of android.os.networkonmainthreadexception is thrown. Also, the server does not receive any package. Here is the code:

public void led(String s) throws Exception
{

    byte[] b=(s.getBytes());
    if(isOnline())
    {

    serverHostname1 = new String ("192.168.1.177");
    ip = InetAddress.getByName(serverHostname1);       
    d1 = new DatagramSocket();

    try{
        sendp =  new DatagramPacket(b,b.length, ip, 8032);
    }catch(Exception e){
        Toast.makeText(getApplicationContext(),e.toString(),Toast.LENGTH_LONG).show();
    }

    try{
    d1.send(sendp);}
    catch(Exception e){         Toast.makeText(getApplicationContext(),e.toString(),Toast.LENGTH_LONG).show();
    }
}
}

Build.gradle (Module)

apply plugin: 'com.android.application'
android {
compileSdkVersion 22
buildToolsVersion "22.0.1"
defaultConfig {
    applicationId "com.android.arduino"
    minSdkVersion 8
    targetSdkVersion 22
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_5
        targetCompatibility JavaVersion.VERSION_1_5
    }
}
productFlavors {
}
}
dependencies {
}
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
user3289834
  • 3
  • 1
  • 8
  • Please post the logs – Psypher Jul 02 '15 at 10:17
  • `android.os.NetworkOnMainThreadException` You should put your network code in an **AsyncTask**. – Phantômaxx Jul 02 '15 at 10:19
  • @DerGolem I did read a bit about AsyncTask. I believe it is the solution to my problem. Thank You. Could you help me implement it in the above code to send packet? Me being new to android programming, it seems fairly complicated. – user3289834 Jul 02 '15 at 10:35
  • It's not so complicated. Read this [official doc](http://developer.android.com/reference/android/os/AsyncTask.html). It is explained very well. You will use AsyncTask in **many** occasions, when you want your app to perform a time consuming task. So, print it. It's worth having it handy. – Phantômaxx Jul 02 '15 at 10:38
  • Thanks for the help :) – user3289834 Jul 02 '15 at 11:15

0 Answers0