Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using HttpUrlconnection in Rss Reader causes Android to hang

Tags:

java

android

rss

I put together an RSS reader that works as-is but, I want to setup the connection to the RSS URL using HttpUrlConnection method. When I tried it, the program locked up after I clicked Read Rss button:

private class getRssFeedTask extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... params) {
        try {
            URL rssUrl = new URL(params[0]);
            HttpURLConnection urlIn = (HttpURLConnection) rssUrl.openConnection();
            InputStream in = new BufferedInputStream(urlIn.getInputStream());
            String line;
            feed = "";
            while ((line = in.toString()) != null) {
                feed += line;
            }
            in.close();
            return feed;
        } catch (MalformedURLException ue) {
            System.out.println("Malformed URL");
        } catch (IOException ioe) {
            System.out.println("The URL is unreachable");
        }
        return null;
    }

}

This is the connection method I am stuck using which works:

private class getRssFeedTask extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... params) {
        try {
            URL rssUrl = new URL(params[0]);
            BufferedReader in = new BufferedReader(new InputStreamReader(rssUrl.openStream()));
            String line;
            feed = "";
            while ((line = in.readLine()) != null) {
                feed += line;
            }
            in.close();
            return feed;
        } catch (MalformedURLException ue) {
            System.out.println("Malformed URL");
        } catch (IOException ioe) {
            System.out.println("The URL is unreachable");
        }
        return null;
    }

}

Thanks for any help you can provide!

like image 416
Nathaniel Warren Avatar asked Nov 07 '15 22:11

Nathaniel Warren


1 Answers

What you need to do is put it into a string I called it results. I have attached my code for the doInBackground. By adding it to a string it has a place to store the feed. And it works for the rss reader.

public String doInBackground(String... urls){

        String result = "";
        try{
            URL url = new URL(urls[0]);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            InputStream in = conn.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            String line = "";

            while((line = reader.readLine()) != null){
                result = result + line;
            }

            conn.disconnect();
        }
        catch(Exception e){
            Log.e("ERROR Fetching ", e.toString());
        }
        return result;
    }
like image 153
Amanda Avatar answered Oct 28 '22 13:10

Amanda