Search code examples
androidjsoupreadfilewritefile

Writing a file from Jsoup document on Andorid and search for specific token


I am very new to android and am trying to create an app for a school project that fetches a piece of information from a website. I am using Jsoup to creat a document and then I try to store the html from the site as a file locally. The number I want is written right after "Average" in the long html file so I try to extract that part. For example the token could look like "class=sep-t>Average30 °C

When I run the app it krashes when I tap the button. I am getting java.lang.NumberFormatException: empty String in the onClick funcion. Does this mean my file is not being written properly? How can I solve this problem?

Thank you in advance! Detailed answers are very much appreciated as I am not used to java programming. Would also love some tips on how to extract the number in a more efficient way.

import android.content.Context;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

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

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.Scanner;


public class MainActivity extends AppCompatActivity {
    private TextView ViewT;
    private Double tempDouble;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button button = (Button) findViewById(R.id.button1);
    ViewT = (TextView) findViewById(R.id.ViewT);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            new getData().execute();
            File fileR = new File(getFilesDir(), "Tempfile.txt");
            Scanner scR = null;
            try {
                scR = new Scanner(fileR);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }//Det funkar hit
            while (scR.hasNext()) {
                String line = scR.next();
                if (line.matches("[Average</th><td>]")) {
                    String temperature = line.replaceAll("[^0-9]+", "");
                    double tempDouble = Double.parseDouble(temperature); //d == 3.78d
                    ViewT.setText(temperature);
                    Toast toast = Toast.makeText(getApplicationContext(), line, Toast.LENGTH_SHORT);
                    toast.show();
                }
            }
        }
    });
}

public class getData extends AsyncTask<Void, Void, Void> {
    String avgT;
    String fileNameT = "Tempfile.txt";


    @Override
    protected Void doInBackground(Void... params) {

         Document temp;
        try {
            temp = Jsoup.connect("http://www.timeanddate.com/weather/singapore/singapore/historic").get(); //avg temp
            avgT=temp.html();
            FileWriter fw1 = new FileWriter(fileNameT);
            PrintWriter pw1 = new PrintWriter(fw1);
            pw1.println(avgT);
            pw1.close();
            fw1.close();
            FileOutputStream fos = openFileOutput(fileNameT, Context.MODE_PRIVATE);
            fos.write(avgT.getBytes());
            fos.close();

        }catch (Exception e){e.printStackTrace();} 

        return null;

    }



    }

}


Solution

  • Simply use jsoup to select elements using CSS selectors.

    Example code

    Document temp = Jsoup.connect("http://www.timeanddate.com/weather/singapore/singapore/historic").get();
    
    Element avgTemp = temp.select("tr.sep-t > td").first();
    System.out.println(avgTemp.text());
    

    Output

    30 °C