Question

I am new to Android and new to Stackoverflow!

I am just creating dummy app to learn http connection. while compiling i encountered an error in this line

HttpResponse getbackdata= http_client.execute(url_data);

I even searched in stackoverflow but mostly people out thr suggested to use Exception Handling to catch UnknownHostException . i did that. I dont know where i messed up with the code. It might be a minor error since i am beginner i will learn from it. Thanks in Advance.

 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);         

        try {
            HttpClient http_client=new DefaultHttpClient();
            URI url=new URI("http://www.mysite.com");
            HttpGet url_data=new HttpGet(url);

            HttpResponse getbackdata= http_client.execute(url_data);

            InputStreamReader in =new InputStreamReader(getbackdata.getEntity().getContent());
            BufferedReader br = new BufferedReader(in);

            StringBuffer sb=new StringBuffer("");
            String info="";
            String nl=System.getProperty("line.separator");

            while((info=br.readLine())!=null){
                sb.append(info.toString()+nl);
            }
            br.close();
            TextView output=(TextView) findViewById(R.id.display_output);
            output.setText(sb.toString());
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            Log.d("ARR_ERROR","UnknownHostException : "+e);
        }
         catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            Log.d("ARR_ERROR","ClientProtocolException : "+e);

        } catch (IOException e) {
            // TODO Auto-generated catch block
            Log.d("ARR_ERROR","IOException : "+e);
        }
         catch (URISyntaxException e) {
        // TODO Auto-generated catch block
        Log.d("ARR_ERROR","URISyntaxException : "+e);
    }


}
Was it helpful?

Solution 2

Let me guess, you are getting a NetworkOnMainThreadException, right? Use an AsyncTask for your network tasks. Don't do them on the UI thread.

OTHER TIPS

NOTE: You can't update your data on Main UI thread.

For that you have to use AsyncTask or Thread with Handler and update your data with runOnUiThread() method.

You can go with this also:

http://www.vogella.com/articles/AndroidBackgroundProcessing/article.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top