简体   繁体   中英

jSoup method closes android App

I'm trying to use jsoup to display temperature of Boston from a website as a toast message in an android app. My Java program looks like this:

public static void showWeather() throws IOException
{
    Document doc = Jsoup.connect("http://www.wunderground.com/US/ma/boston.html?MR=1").get();
    Elements languages = doc.select("#tempActual span.b ");


    for(Element langElement: languages)
    {
        //System.out.println(" The temperature in Boston: "+langElement.text()+ " F");

    }

}

The Java program works Okay and prints the temperature of Boston to the screen. I want to use this method to try to display the temperature as a toast in a simple android app, but when I try to run to method (without the print statement of course) in the onCreate method in my android activity, the program closes automatically. Here's my onCreate method:

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

    try {
        showWeather();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

Can anybody please tell how to run this java program in my android activity? I don't know how to treat the try/catch clause properly. I tried put toast in the catch clause but to no avail. Please help.

AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.

Reference:
http://developer.android.com/reference/android/os/AsyncTask.html

Usage
AsyncTask must be subclassed to be used. The subclass will override at least one method ( doInBackground(Params...) ), and most often will override a second one ( onPostExecute(Result) .)

Here is an example of subclassing:

private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
  protected Long doInBackground(URL... urls) {
     int count = urls.length;
     long totalSize = 0;
     for (int i = 0; i < count; i++) {
         totalSize += Downloader.downloadFile(urls[i]);
         publishProgress((int) ((i / (float) count) * 100));
         // Escape early if cancel() is called
         if (isCancelled()) break;
     }
     return totalSize;
  }

  protected void onProgressUpdate(Integer... progress) {
      setProgressPercent(progress[0]);
  }

  protected void onPostExecute(Long result) {
      showDialog("Downloaded " + result + " bytes");
  }
 }

Once created, a task is executed very simply:

new DownloadFilesTask().execute(url1, url2, url3);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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