NetworkOnMainThreadException error while retrieving device's local IP [duplicate]

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

        ipLocal.setText(netAddress);

I'm trying to recover my local ip from the device, I put the above code in onCreate of my Activity . However, TextView ipLocal only receives the value assigned at the initialization of the variable ("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) 
    
asked by anonymous 23.04.2018 / 01:13

2 answers

2

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

A simple way to do this is to create an anonymous Thread in your class to take care of these network operations.

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

Another way is to AsyncTask these 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);
        }
    }
    
23.04.2018 / 13:04
1

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

One way around this is to use a AsyncTask , which will "transform" your Synchronous operation in 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);
    }
}
    
23.04.2018 / 12:57