简体   繁体   English

尝试与 android studio 中的 jsoup 连接时,模拟器应用程序崩溃

[英]emulator app crashes when trying to connect with jsoup in android studio

There are no errors when running and compiling the code in android studio, but after pressing the button to connect with jsoup the app just crashes for some reason.在android studio中运行和编译代码时没有错误,但是在按下按钮与jsoup连接后,应用程序由于某种原因崩溃了。 Anyone know what I'm doing wrong?有谁知道我做错了什么?

package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    }


    class JsoupParseTask extends AsyncTask<String, Void, Document> {

        protected Document doInBackground(String... urls) {

            Document doc = null;
            try {
                doc = Jsoup.connect("http://google.com/").get();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }

            return doc;
        }
    }

    public void connect(View v) {

        // Call from here, it will execute doInBackground
        new JsoupParseTask().execute();
    }


}

It's simply an exception typed NetworkOnMainThreadException , that is thrown when an application attempts to perform a networking operation on its main thread.它只是一个类型为NetworkOnMainThreadException的异常,当应用程序尝试在其主线程上执行网络操作时抛出该异常。

As for example, try to run your code in AsyncTask:例如,尝试在 AsyncTask 中运行您的代码:

class JsoupParseTask extends AsyncTask<String, Void, Document> {

    @Override
    protected Document doInBackground(String... urls) {

        Document doc = null;
        try {
            doc = Jsoup.connect("http://google.com/").get();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }

        return doc;
    }

    @Override    
    protected void onPostExecute(Document doc) { 
        // execution of result here 

        String title = doc.title();
    }

}

And call this like below:并像下面这样调用它:

public void connect(View v) {

    // Call from here, it will execute doInBackground
    new JsoupParseTask().execute();
}

Besides this don't forget to add internet permission in AndroidManifest.xml除此之外不要忘记在AndroidManifest.xml添加互联网权限

<uses-permission android:name="android.permission.INTERNET" />

But since AsyncTask is deprecated, you could try it's alternative.但是由于AsyncTask已被弃用,您可以尝试使用它的替代方法。 Here is a nice tutorial that mentioned some alternatives of AsyncTask这是一个很好的教程,其中提到了AsyncTask一些替代方案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM