Search code examples
androidandroid-asynctaskjsoupnetworkonmainthread

android.os.NetworkOnMainThreadException and not fix with AsyncTask (jsoup)


try to show some specific part of web in web view and use jsoup library so select my Intended div and this is my code :

public class MainActivity extends AppCompatActivity {


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_page);
        WebView webView = (WebView) findViewById(R.id.web);
        webView.getSettings().setJavaScriptEnabled(true);

        try {
            Document document = Jsoup.connect("http://www.memaraneha.ir").get();
            Element elements=document.select("div.news-list").first();
            String html = elements.toString();
            String mime = "text/html";
            String encoding = "utf-8";
            webView.loadData(html, mime, encoding);
        } catch (IOException e) {
            e.printStackTrace();
        }

}}

but when run this got this error : android.os.NetworkOnMainThreadException

after some research i know what is this error and how must solve this with put codes in AsyncTask function with this question (and not duplicate in my case) i try this but not work and seems not possible to put this jsoup codes in AsyncTask or i dont know how must do that...

if any one can please help.


Solution

  • Use Asynctask to load the document

    public class MainActivity extends AppCompatActivity {
    
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main_page);
            WebView webView = (WebView) findViewById(R.id.web);
            webView.getSettings().setJavaScriptEnabled(true);
    
            new AsyncTask<Void, Void, String>() {
                @Override
                protected String doInBackground(Void... voids) {
                    String html = "";
                    try {
                        Document document = Jsoup.connect("http://www.memaraneha.ir").get();
                        Element elements=document.select("div.news-list").first();
                        html = elements.toString();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
    
                    return html;
                }
    
                @Override
                protected void onPostExecute(String html) {
                    String mime = "text/html; charset=utf-8";
                    String encoding = "utf-8";
                    webView.loadData(html, mime, encoding);
                }
            }.execute();
    
    }}