HttpURLConnection returning empty [duplicate]

1

Message

  

Attempt to invoke virtual method 'int java.lang.String.length ()' on a null object reference

Call

JSONArray data = new JSONArray(getHttpGet(url));

Code:

public static String getHttpGet(String url) {
        String result = null;
        try {
            URL myurl = new URL("http://www.exemplo.com.br/gerajson.php");
            HttpURLConnection urlconnection = (HttpURLConnection) myurl.openConnection();
            urlconnection.setRequestMethod("GET");
            urlconnection.setDoInput(true);
            urlconnection.connect();
            InputStream is = urlconnection.getInputStream();
            if (is != null) {
                StringBuffer sb = new StringBuffer();
                String line;
                try {
                    BufferedReader reader = new BufferedReader(
                            new InputStreamReader(is));
                    while ((line = reader.readLine()) != null) {
                        sb.append(line);
                    }
                    reader.close();
                } finally {
                    is.close();
                }
                result = sb.toString();
            }
        } catch (Exception e) {
            result = null;
        }
        return result;
    }

Update (when changing contents of catch ):

  

app has stopped. E.AndroidRuntime: FATAL EXCEPTION: mainProcess: br.com.webvisionsystems.shishamaps, PID: 2561 java.lang.RuntimeException: android.os.NetworkOnMainThreadException at br.com.webvisionsystems.shishamaps.MapFragment.getHttpGet (MapFragment.java:17 6) at br.com.webvisionsystems.shishamaps.MapaFragment.onMapReady (MapFragment.java:64)

    
asked by anonymous 31.10.2017 / 21:04

1 answer

1

The first problem is this snippet:

    } catch (Exception e) {
        result = null;
    }

This is not a good idea as it will swallow the actual error to mask it as a NullPointerException afterwards. Exchanging result = null; for this:

        e.printStackTrace();
        throw new RuntimeException(e);

The generated exception is different (depending on your comment). The exception becomes android.os.NetworkOnMainThreadException . As the exception name indicates, you are attempting to perform network operations on the main thread. If this were allowed, it would end up leaving your application frozen for some time while the operation is running, which would result in a poor user experience and a non-responsive application. For this reason, it is not allowed to perform this type of operation on the main thread.

So the solution is to invoke the getHttpGet method on a thread other than the application's main thread. To do this, the easiest and obvious way would be using class AsyncTask .

    
31.10.2017 / 21:56