java - 我不知道为什么在使用 AsyncTask 时仍然出现“android.os.NetworkOnMainThreadException”错误
问题描述
我是 android 编程新手,我正在尝试了解 AsyncTask 概念,所以请查看此代码并告诉我它为什么崩溃并不断给出“android.os.NetworkOnMainThreadException”错误。这个应用程序只是根据给定的 x 和 y 坐标使用一点网络抓取来告诉天气。
这是我的代码:
public class MainActivity extends AppCompatActivity {
TextView weatherInfo;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
weatherInfo = (TextView) findViewById(R.id.weather_info);
Weathers runner = new Weathers();
String GetInfo = runner.doInBackground();
weatherInfo.append(GetInfo);
}
}
class Weathers extends AsyncTask<String,String,String>{
@Override
protected String doInBackground(String... strings) {
String x="19.11";
String y="72.88";
String result = null;
try {
Document doc = Jsoup.connect("https://weather.com/en-IN/weather/today/l/"+x+","+y).get();
for (Element row : doc.select("header[class=loc-container]") ){
result=row.text();
}
for (Element row : doc.select("div[class=today_nowcard-section today_nowcard-condition]") ){
result=result+(row.text());
}
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
}
这是 Android 清单文件:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.inferno.sunshine">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.INTERNET"/>
</manifest>
解决方案
用这个
String GetInfo = runner.execute();
而不是这个
String GetInfo = runner.doInBackground();
推荐阅读
- .net-core - 无法从 docker 容器写入 AWS CloudWatch
- php - php 回显数组的元素
- php - 面临一个问题使用substr PHP划分字符串的最大长度
- angular - 当页面刷新我的 ngnix 服务器给出 404 not found 错误
- selenium - 使用 testng 运行 selenium 时出错
- firebase - 如何在 Firebase 托管的不同 url 路径中部署不同版本的网络?
- linux - 节点:找不到命令 - 在 wsl bash 中
- vue.js - 如何使用 lodash 从数组中获取所有唯一标签?
- swift - 在swift UIButton中更新for循环中按钮的标题
- visual-studio-code - 使用 Bazel 在 VSCode 中查找 java 导入