Skip to content Skip to sidebar Skip to footer

Attempt To Invoke Virtual Method 'void Java.io.bufferedreader.close()

i have this exception shows when i run my app so i wish to help me :) the exception is : java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.len

Solution 1:

Looks like a relatively simple mistake. In your finally block of your HttpManager class.

Should be

} finally {
    if ((reader != null)) {
      try {
         reader.close();
      } catch (Exception e) {
         e.printStackTrace();
      }
    }
}

However I highly suggest if you are using java 7+ you use try-with-resources.

So your getData method would become

publicstatic String getData(RequestPackage p) {
     = null;
    Stringuri= p.getUri();
   if(p.getMethod().equals("GET")){

       uri+= "?"+p.getEncodeParams();
   }
    try (BufferedReaderreader=newBufferedReader(newInputStreamReader(con.getInputStream()))) {
        URLurl=newURL(uri);
        HttpURLConnectioncon= (HttpURLConnection) url.openConnection();
        con.setRequestMethod(p.getMethod());

        StringBuildersb=newStringBuilder();
        String line ;
        int fl=0;
        while ((line = reader.readLine()) != null) {
           if(fl!= 0)
            sb.append(line + "  \n");
            fl++;
        }
        return sb.toString();
    } catch (Exception e) {
        e.printStackTrace();
        returnnull;
    }
}

Thats much easier and you don't have to worry about closing the resources because they implement AutoCloseable.

Post a Comment for "Attempt To Invoke Virtual Method 'void Java.io.bufferedreader.close()"