I am trying to display my ip address using Inet but the app crashes when i do so.. do i need to add any permissions so that this does not happen? following is my code
try {
Inet4Address ip= (Inet4Address) Inet4Address.getLocalHost();
String s=ip.toString();
TextView text= (TextView)findViewById(R.id.txt);
text.setText(s);
} catch (UnknownHostException e) {
e.printStackTrace();
}
android don't give u permission to run any network related work direct in main thread so you get this Exception :
android.os.NetworkOnMainThreadException
run your code like this:
Thread thread = new Thread(){
public void run(){
try {
Inet4Address ip= (Inet4Address) Inet4Address.getLocalHost();
String s=ip.toString();
TextView text= (TextView)findViewById(R.id.txt);
text.setText(s);
Log.e("my ip=> ",s+" <<");
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
};
thread.start();
it's just run you code another thread...
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments