0

I am trying to read a JSON from a web page and store it as a string, however when debugging it keeps failing in the try statement at line:

BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));

public String networkRequest() throws IOException {

    URL url = new URL("https://graph.facebook.com/me");

    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    try
    {
        InputStream inputStream = url.openStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
        StringBuilder stringBuilder = new StringBuilder();
        int cp;
        while ((cp = bufferedReader.read()) != -1)
        {
            stringBuilder.append((char) cp);
        }

        return stringBuilder.toString();
    }
    catch(Exception ex)
    {
        return "nothing";
    }
}

In which because of the fail reaches the catch and returns "nothing", does anyone understand what I am doing wrong?

BTW: My network is perfectly fine!

Gusinator
  • 1
  • 2
  • Log the exception inside of your catch block. By doing `Log.d("TAG", ex + "");` and then in your Logcat, see what the exception is. – Bidhan Jun 10 '15 at 18:02
  • are you executing this method from UI thread? Please post your exception here for further help. – siva Jun 10 '15 at 18:15
  • @BidhanA So I get this exception, android.os.NetworkOnMainThreadException – Gusinator Jun 10 '15 at 18:18
  • @user950933 I get a NetworkOnMainThreadException – Gusinator Jun 10 '15 at 18:19
  • Great. It means you are executing this method from UI thread which is not recommended and android strict mode will not allow this. Hence there is an exception. Please execute the method from a background thread. – siva Jun 10 '15 at 18:22
  • Did you add internet permission to your AndroidManifest.xml ? – strings95 Jun 10 '15 at 18:23
  • @strings95 Yup I did! – Gusinator Jun 10 '15 at 18:32
  • possible duplicate of [Android HttpClient : NetworkOnMainThreadException](http://stackoverflow.com/questions/11736530/android-httpclient-networkonmainthreadexception) – Dan S Jun 10 '15 at 18:35

1 Answers1

0

Great. It means you are executing this method from UI thread which is not recommended and android strict mode will not allow this. Hence there is an exception. Please execute the method from a background thread.

siva
  • 1,850
  • 13
  • 14
  • When you say 'background thread' can I ask what do you mean? As this method is in a class which is called from a method in my presenter (following MVP design pattern) – Gusinator Jun 10 '15 at 18:35
  • You should create a new Java thread or runnable object and execute this method. – siva Jun 10 '15 at 18:37
  • Can you lead me to the correct tutorials? I don't understand what you are saying – Gusinator Jun 10 '15 at 18:50
  • developer.android.com/training/articles/perf-anr.html – siva Jun 11 '15 at 02:41