我添加了一项新活动并将其作为主要活动。以前的主要活动以及其他活动从网站访问数据。 Everthing工作得很好。新的主要活动也需要从网站访问数据,但这次我收到了NetworkOnMainThreadException异常。我在新活动上实现了AsyncTask,它现在可以工作了。我正在为其他活动实现AsyncTask,即使它们仍然有效并且不抛出异常。我读过这是最好的做法。
以下是我用来从网站提取数据的代码。为什么它只对新的主要活动而不是任何其他活动抛出NetworkOnMainThreadException消息?
格雷格
protected String GetNewData(String URLIn) {
String ThisData = "";
try {
URL url = new URL(URLIn);
HttpURLConnection con = (HttpURLConnection) url
.openConnection();
RetrieveSiteData ThisSite = new RetrieveSiteData();
ThisData = ThisSite.readStream(con.getInputStream());
} catch (Exception e) {
e.printStackTrace();
}
return ThisData;
}
堆栈跟踪
android.os.NetworkOnMainThreadException
android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1236)
java.net.InetAddress.lookupHostByName(InetAddress.java:388)
java.net.InetAddress.getAllByNameImpl(InetAddress.java:239)
java.net.InetAddress.getAllByName(InetAddress.java:214)
com.android.okhttp.internal.Dns$1.getAllByName(Dns.java:28)
com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:216)
com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:122)
com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:292)
com.android.okhttp.internal.http.HttpEngine.sendSocketRequest(HttpEngine.java:255)
com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:206)
com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:345)
com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:296)
com.android.okhttp.internal.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:179)
com.windsweptsoftware.wslistit.Utilities.GetNewData(Utilities.java:45)
com.windsweptsoftware.wslistit.LogIn.onLoginClicked(LogIn.java:96)
java.lang.reflect.Method.invokeNative(Native Method)
java.lang.reflect.Method.invoke(Method.java:515)
android.view.View$1.onClick(View.java:3860)
android.view.View.performClick(View.java:4480)
android.view.View$PerformClick.run(View.java:18673)
android.os.Handler.handleCallback(Handler.java:733)
android.os.Handler.dispatchMessage(Handler.java:95)
android.os.Looper.loop(Looper.java:157)
android.app.ActivityThread.main(ActivityThread.java:5872)
java.lang.reflect.Method.invokeNative(Native Method)
java.lang.reflect.Method.invoke(Method.java:515)
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1069)
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:885)
dalvik.system.NativeStart.main(Native Method)
原始代码在大多数没有AsynTask的活动中仍然有效。
protected String GetNewData(String URLIn) {
String ThisData = "";
try {
URL url = new URL(URLIn);
HttpURLConnection con = (HttpURLConnection) url
.openConnection();
RetrieveSiteData ThisSite = new RetrieveSiteData();
ThisData = ThisSite.readStream(con.getInputStream());
} catch (Exception e) {
e.printStackTrace();
}
return ThisData;
}