1
public class MainA extends Activity {
    WifiManager wifi=(WifiManager)getSystemService(Context.WIFI_SERVICE);
    WifiInfo info=wifi.getConnectionInfo();
    String ip;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button bt=(Button)findViewById(R.id.b1);

        try{
            InetAddress ownIP=InetAddress.getLocalHost();
            ip=ownIP.getHostAddress();
            //System.out.println("IP of my Android := "+ownIP.getHostAddress());
        }catch (Exception e){
            //System.out.println("Exception caught ="+e.getMessage());
        }

        bt.setOnClickListener(new OnClickListener(){
            public void onClick(View v) {
                // TODO Auto-generated method stub
                TextView tv1=(TextView)findViewById(R.id.tv1);
                tv1.setText(ip);
            }
        });
    }
}

It stops with the dialog, should I use other method or any other way of using it.I used the getHostAddress() with try- catch, but when I run this it just doesnt run What is wrong in this?

  • 1
    Stops with "the dialog"? What does the exception say? We need the troubleshooting information if you want help. – chrylis -cautiouslyoptimistic- Feb 11 '14 at 06:34
  • 1
    @user3293724 Would you provide the `stack-trace` of exception. – Satyendra Feb 11 '14 at 06:57
  • The javadoc for `.getLocalHost()` says that it is "[...] achieved by retrieving the name of the host from the system, then resolving that name into an InetAddress.". Unavailable/slow name resolution? – fge Feb 11 '14 at 07:11
  • My guess would be NetworkOnMainThreadException. Please log your exception stacktraces and do not just ignore them. – laalto Feb 11 '14 at 07:59

1 Answers1

0

My guess is that you're trying to get the host of your loopback address and that's throwing an Exception, as it's not being resolved to any host. You're probably catching that Exception but as you have not code inside, you think there's nothing happening.

By the way: Catching all exceptions is a bad practice as you might be catching some exception that is not intended by the try block. You can read more on this here.

Community
  • 1
  • 1
nKn
  • 13,691
  • 9
  • 45
  • 62