Search code examples
javaandroidexceptionioexception

Handling IOExceptions in Android


I'm creating an app where I need a function to get plain text from a website. I am able to get the text and print it out on my PC just fine, but when I try running it on an Android device, the app won't start.

I believe it has something to do with throwing an IOException. I've been reading that I am not supposed to do that because I don't define the interface. Is there a way to get around this? Android Studio won't compile my code if I don't throw the exception.

The function:

public String getText(String site) throws IOException {
    // Make a URL to the web page
    URL url = new URL(site);

    // Get the input stream through URL Connection
    URLConnection con = url.openConnection();
    InputStream is =con.getInputStream();
    BufferedReader br = new BufferedReader(new InputStreamReader(is));

    // read each line and return the final text
    String res = "";
    String line = null;
    while ((line = br.readLine()) != null) {
        //System.out.println(line);
        res += line;
    }
    return res;
}

And this is how Android Studio makes me run it in the onCreate method:

String text = null;
    try {
        text = getText("http://myWebsite.com");
    } catch (IOException e) {
        e.printStackTrace();
    }

    Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG).show();

Solution

  • First, read your logcat - you should see your exception there with full stacktrace. Second, there is nothing wrong with catching IOException, but you must do something with it once cached - like inform user of problem in functionality - like no more space, etc.

    And this is how Android Studio makes me run it in the onCreate method:

    this is a problem, because your are getting data from your site on UI thread, you must do it from worker thread, ie. AsyncTask.