2

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;

    }



    }

}

1 Answers1

0

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
Frederic Klein
  • 2,846
  • 3
  • 21
  • 37
  • Thank you it works fine! How can I use this to extract from a list? – Hilda Andersson Oct 24 '16 at 03:01
  • I want the third element, the 3 mm precipitation.
    • Max UV Index: N/A
    • Thunderstorms: 29%
    • Precipitation: 3 mm
    • Rain: 3 mm
    • Snow: 0 CM
    – Hilda Andersson Oct 24 '16 at 03:04
  • If the answer resolved your question, please accept it. Regarding your follow up question: `.select("ul.stats > li > strong").get(2);` would give you `3mm`, `.select("ul.stats > li").get(2);` would give you `Precipitation: 3 mm`. When you open the chrome dev tools (F12), select the Elements tab and right click on the element of interest, you can select `Copy -> Copy selector`. Then you have a starting point and can try to generalize the selector rule. – Frederic Klein Oct 24 '16 at 05:19