Networkonmainthreadexception error while recovering local IP from device

Asked

Viewed 100 times

0

  String netAddress = "000.000.000.000";
        try
        {
            netAddress = InetAddress.getLocalHost().getHostAddress();
        }
        catch (Exception e1)
        {
            e1.printStackTrace();
        }

        ipLocal.setText(netAddress);

I am trying to recover my local ip device, I put the above code in the onCreate of my Activity. But the TextView ipLocal only receives the value assigned at variable initialization ("000,000,000,000"). My device is connected to my wireless network and I imported the classes:

import java.net.InetAddress;
import java.net.UnknownServiceException;
import  java.net.UnknownHostException;

The error message:

E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: net.ddns.tiyuri.networkutilities, PID: 22999
                  java.lang.RuntimeException: Unable to start activity ComponentInfo{net.ddns.tiyuri.networkutilities/net.ddns.tiyuri.networkutilities.NuMain}: android.os.NetworkOnMainThreadException
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2830)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2905)
                      at android.app.ActivityThread.-wrap11(Unknown Source:0)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1606)
                      at android.os.Handler.dispatchMessage(Handler.java:105)
                      at android.os.Looper.loop(Looper.java:169)
                      at android.app.ActivityThread.main(ActivityThread.java:6595)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
                   Caused by: android.os.NetworkOnMainThreadException
                      at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1599)
                      at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:102)
                      at java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:90)
                      at java.net.InetAddress.getLocalHost(InetAddress.java:851)
                      at net.ddns.tiyuri.networkutilities.NuMain.onCreate(NuMain.java:49)
                      at android.app.Activity.performCreate(Activity.java:7016)
                      at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214)
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2783)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2905) 
                      at android.app.ActivityThread.-wrap11(Unknown Source:0) 
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1606) 
                      at android.os.Handler.dispatchMessage(Handler.java:105) 
                      at android.os.Looper.loop(Looper.java:169) 
                      at android.app.ActivityThread.main(ActivityThread.java:6595) 
                      at java.lang.reflect.Method.invoke(Native Method) 
                      at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) 
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767) 

2 answers

2

This Exception has been deleted as it is not possible to network operations in the Main Thread. This throw is only released for Androids newer than Honeycomb. But Google Android discourages doing this on any SDK.

One simple way to do this is to create an anonymous Thread in your class to handle these network operations.

new Thread(new Runnable(){
  @Override
  public void run() {
      // sua operação de rede aqui
  }
}).start();

Another way is to rotate in one AsyncTask such network operations

class RetrieveIP extends AsyncTask<String, Void, String> {

        private Exception exception;

        protected String doInBackground(String... urls) {
            try {
                try {
                    netAddress = InetAddress.getLocalHost().getHostAddress();
                } catch (Exception e1) {
                    e1.printStackTrace();
                }

                return netAddress;
            } catch (Exception e) {
                this.exception = e;

                return null;
            } finally {
                is.close();
            }
        }

        protected void onPostExecute(String netAddress) {
            // TODO: faça alguma coisa com seu return
            ipLocal.setText(address);
        }
    }

1

NetworkOnMainThreadException means that you tried to access a network resource on the main thread, which would cause UI blocking.

One of the ways around this is by using a Asynctask, that will "transform" your synchronous operation into asynchronous.

public class GetAddressTask extends AsyncTask<Void, Void, String> {

    protected String doInBackground(Void... urls) {
        // Executado em background
        return InetAddress.getLocalHost().getHostAddress();
    }

    protected void onPostExecute(String address) {
        // Executado na thread de UI
        ipLocal.setText(address);
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.