bhuvesh
bhuvesh

Reputation: 749

url.openStream() gives NullPointerException for just one url

please do not mark it as a duplicated because I have already searched Stackoverflow before posting it, and found this solution,

url.openstream() or urlconnection.getinputstream() raise nullpointerexception on valid URL

but this solution doesn't work either.

The problem is i am trying to openStream on this url > http://www.techworld.com/security/rss for my Android App.

but it always give NullPointerException.

I first checked the connection to see if the connection is successful,

connection.getResponseCode();

and it return 200 so the connection is ok.

Then according to the available solutions, I changed the JRE version from 1.7 to 1.6 but this still don't work.

When I try to openStream other urls then they work absolutely fine with the same code but the above link gives NPE.

this is the code,

URL mylink = new URL ("http://www.techworld.com/security/rss");

HttpURLConnection connection;
connection = (HttpURLConnection) myLink.openConnection();   
connection.connect();

if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
    try {
        domObject = new DOM(myLink.openStream());
        domObject.start();

    } catch (Exception e) {
        Log.e(TAG,e+" " + host);
    }    
}

in the above code, host = myLink.getHost();.

one more thing i would like to mention that, when I run this code as a Java project instead of Android project then it loads finds and do not throw NPE.

What could be the problem here ?

This is the logCat, it only shows one line error,

01-21 20:46:11.575: E/testApp(30335): java.lang.NullPointerException www.techworld.com

Upvotes: 3

Views: 3189

Answers (1)

hata
hata

Reputation: 12478

At least this code worked:

URL url;
try {
    url = new URL("http://www.techworld.com/security/rss");
    HttpURLConnection httpURLConnection;
    httpURLConnection = (HttpURLConnection) url.openConnection();
    httpURLConnection.connect();
    if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
        StringBuffer stringBuffer = new StringBuffer();
        try {
            String inputLine;
            while ((inputLine = bufferedReader.readLine()) != null) {
                stringBuffer.append(inputLine).append("\n");
            }
        } finally {
            bufferedReader.close();
        }

        System.out.println(stringBuffer.toString());
        }
} catch (IOException e) {
    e.printStackTrace();
}

I think your code tries to open connection twice. While the first connection is not closed, you try connect another myLink.openStream(). It may be better just using connection.getInputStream().

Upvotes: 2

Related Questions