M
M
Millerish2016-09-07 14:04:21
Java
Millerish, 2016-09-07 14:04:21

First project in java. How to solve NetworkOnMainThreadException?

Good time of the day!
I am learning java and android. Help to deal with the first test project .
Files: YandexTranslate.java and MainActivity.java
The NetworkOnMainThreadException error occurs. As I understand it, it usually happens when accessing the Internet in main. I moved it to a separate class, why am I getting this error? How to fix?
From console:

09-07 13:46:04.796 25701-25701/info.stekolschikov.ytranslate E/AndroidRuntime: FATAL EXCEPTION: main
Process: info.stekolschikov.ytranslate, PID: 25701
android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy. onNetwork(StrictMode.java:1166)
at java.net.InetAddress.lookupHostByName(InetAddress.java:418)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
at java.net.InetAddress.getAllByName(InetAddress.java:215)
at com.android.okhttp.HostResolver$1.getAllByName(HostResolver.java:29)
at com .android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:232)
at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:124)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:272)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:211)
at com.android.okhttp.internal .http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:382)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:106)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.getOutputStream (HttpURLConnectionImpl.java:217
)
.http.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:25)
at info.stekolschikov.ytranslate.YandexTranslate.translate(YandexTranslate.java:58)
at info.stekolschikov.ytranslate.MainActivity$1.onClick(MainActivity.java:40)
at android.view.View.performClick(View.java:4851)
at android.view.View$PerformClick.run(View.java:20016)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5429)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect .Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:947)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:742)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
illuzor, 2016-09-07
@Millerish

Your "access to the Internet" needs to be moved to a separate thread, not a separate class.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question