首页 > 解决方案 > 我不知道为什么在使用 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>

标签: javaandroid

解决方案


用这个

String GetInfo = runner.execute();

而不是这个

String GetInfo = runner.doInBackground();

推荐阅读