-1

In my app, I fire an onItemClick(..) listner when a list view item is clicked. In that event, I load data from a webpage using the following code :-

try {
        HttpClient httpClient = new DefaultHttpClient();
        HttpContext localContext = new BasicHttpContext();
        HttpGet httpGet = new HttpGet("http://www.spartanjava.com");
        HttpResponse response = httpClient.execute(httpGet, localContext);
        String result = "";
        BufferedReader reader = new BufferedReader(
            new InputStreamReader(
              response.getEntity().getContent()
            )
          );
        String line = null;
        while ((line = reader.readLine()) != null){
          result += line + "\n";
        }
} catch (Exception e) {
    tv.setText("Error : "+e.getMessage());//tv is a textview
    Toast.makeText(getApplicationContext(), "No connection", Toast.LENGTH_LONG).show();
    e.printStackTrace();
}

I have included the following jars in the classpath :-

commons-codec-1.6.jar
commons-logging-1.1.3.jar
httpclient-4.3.3.jar
httpclient-cache-4.3.3.jar
httpcore-4.3.2.jar
httpmime-4.3.3.jar

I have the permission <uses-permission android:name="android.permission.INTERNET"/> in my AnroidManifext.xml file. The output which I receive is all that is in the catch-block. The textview is set with the value "Error : null" and the toast is fired. Any idea on how should I proceed?

Deval Khandelwal
  • 3,458
  • 1
  • 27
  • 38

2 Answers2

1

Maybe response.getEntity() returns null.

As you try to get a InputStream on the entity, through getContent(), without checking if the entity is null, it could trigger a NullPointerException.

EDIT

NetworkOnMainThreadException is thrown, you have to do network operation in a thread, like in this example : How to fix android.os.NetworkOnMainThreadException?

Community
  • 1
  • 1
ToYonos
  • 16,469
  • 2
  • 54
  • 70
1

Your Exception actually tells you exactly what you are doing wrong. You are not using another thread to perform NetworkOperations.

Your code that connects to the url should be executed inside an AsyncTasks doInBackground() method, off the UI-Thread.

For more info see android.os.NetworkOnMainThreadException

Community
  • 1
  • 1
Giru Bhai
  • 14,370
  • 5
  • 46
  • 74