0

Here is my code for a web scraper button. I always get the same error. I just want to print a Log with one of the elemnts I scraped to see if it's working before I move on. Could I just create a new Runnable? What's the simplest, most up to date way to do this?

Caused by: android.os.NetworkOnMainThreadException

Main Activity:

package com.example.ezhedge3;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import java.io.IOException;

public class MainActivity extends AppCompatActivity {

    Elements contango1;
    Elements contango2;
    Elements contango3;
    Document document;

    public void scrape (View view) throws IOException {

        document = Jsoup.connect("http://vixcentral.com/historical/?days=30").get();
        contango1 = document.getElementsByIndexEquals(32);
        contango2 = document.getElementsByIndexEquals(47);
        contango3 = document.getElementsByIndexEquals(62);

        Log.i("contango1 = ", contango1.toString());
    }

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

XML:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="scrape"
        android:text="Go!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Matt
  • 5
  • 1
  • 3
  • Does this answer your question? [NetworkOnMainThreadException](https://stackoverflow.com/questions/5150637/networkonmainthreadexception) – Krystian G May 18 '20 at 17:43
  • Not really. I have read documentation for AsyncTask, Handlers and Runnables, but I am still unsure how to properly implement them. Forgive me, as I have only been doing this for about a month now. I'll look more into those posts and see if I can spot where I am having a more specific issue, thanks. – Matt May 18 '20 at 23:03
  • Inside the onCreate method, am I to replace the standard line of code with the following: "setContentView(R.layout.activity_net_work_exception);" as apposed to the usual code that comes standard on a new project? – Matt May 18 '20 at 23:05

0 Answers0