Rohit Malish
Rohit Malish

Reputation: 3229

BufferedReader works in standard java but not in android

So I have this exact same code in java and android, but for some reason in android method get() always fails to do the job and returns false, but in standard java it works perfect. And I do have Internet permission in manifest.

Here is the code:

    public boolean get(){
        try {
            jsonObject = new JSONObject(readUrl(url)); // Ignore JSON thing.
            return true;
        } catch (Exception ex) {
            return false;
        }
    }

    private String readUrl(String urlString) throws Exception {
        BufferedReader reader = null;
        try {
            URL url = new URL(urlString);
            reader = new BufferedReader(new InputStreamReader(url.openStream()));
            StringBuffer buffer = new StringBuffer();
            int read;
            char[] chars = new char[1024];
            while ((read = reader.read(chars)) != -1) {
                buffer.append(chars, 0, read);
            }

            return buffer.toString();
        } finally {
            if (reader != null) {
                reader.close();
            }
        }
    }

Upvotes: 0

Views: 580

Answers (1)

Gabriel Netto
Gabriel Netto

Reputation: 1828

In Android when you start a service it still run in the Main Thread, aka, UIThread, as a good practice you shouldn't do any intensive processing in that thread as it will lock user interaction with your application. So even in a service you must create your own thread to access a network resource.
Here is a reference link to Services

Upvotes: 2

Related Questions