Frage

I am trying to check if a web service is reachable with an android application.

Within my button click listener is:

    try {

            InetAddress address = InetAddress.getByName(result); // user input is 'result' (a URL) LINE 73
            boolean b = address.isReachable(3000); 
            String str = String.valueOf(b); // turning the value of the boolean into string
            pingResult.setText(str); // value displays as true or false

            }

    catch (UnknownHostException e) {} // will fill with helpful message later
    catch (IOException e) {}

Logcat is displaying:

05-10 15:21:21.390: E/AndroidRuntime(11653): FATAL EXCEPTION: main
05-10 15:21:21.390: E/AndroidRuntime(11653): Process: com.example.c3po, PID: 11653
05-10 15:21:21.390: E/AndroidRuntime(11653): android.os.NetworkOnMainThreadException
05-10 15:21:21.390: E/AndroidRuntime(11653):    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1145)
05-10 15:21:21.390: E/AndroidRuntime(11653):    at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
05-10 15:21:21.390: E/AndroidRuntime(11653):    at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
05-10 15:21:21.390: E/AndroidRuntime(11653):    at java.net.InetAddress.getByName(InetAddress.java:289)
05-10 15:21:21.390: E/AndroidRuntime(11653):    at com.example.c3po.MainActivity$2.onClick(MainActivity.java:73)

And some more, line 73 has been commented.

Any ideas where I am going wrong?

Thanks

War es hilfreich?

Lösung

You are getting a network on main thread exception. It is not a good practice to use any type of blocking (or network activity ) on mainthread(i.e your UI thread).

Possible solution:

1.Upon your button click Spawn a thread , In that thread perform your Network activity that you tried to perform.() 2.This solution is not advisable. but still , You can set your manifest to allow network activity on main thread, Google can provide you the manifest commands .

You can google on NetworkOnMainThreadException to know more about it.

Andere Tipps

The stack trace tells you exactly what you're doing wrong, you're running a network operation on the UI thread. Simply move this to a Thread or an AsyncTask and it should work.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top