-6
 @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
        HttpClient httpclient = new DefaultHttpClient();
        HttpGet httpget = new HttpGet("http://domain.com");
        try {
            HttpResponse response = httpclient.execute(httpget);
            if(response != null) {
                String line = "";
                InputStream inputstream = response.getEntity().getContent();
                line = convertStreamToString(inputstream);
                Toast.makeText(getActivity(), line, Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(getActivity(), "Unable to complete your request", Toast.LENGTH_LONG).show();
            }
        } catch (ClientProtocolException e) {
            Toast.makeText(getActivity(), "Caught ClientProtocolException", Toast.LENGTH_SHORT).show();
        } catch (IOException e) {
            Toast.makeText(getActivity(), "Caught IOException", Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            Toast.makeText(getActivity(), "Caught Exception", Toast.LENGTH_SHORT).show();
        }
        //Log.i("DATA FROM MYSQL", output);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(inflater.getContext(), android.R.layout.simple_list_item_1,countries);
        setListAdapter(adapter);
        return super.onCreateView(inflater, container, savedInstanceState);
    }
    private static String convertStreamToString(InputStream is) {
        /*
         * To convert the InputStream to String we use the BufferedReader.readLine()
         * method. We iterate until the BufferedReader return null which means
         * there's no more data to read. Each line will appended to a StringBuilder
         * and returned as String.
         */
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

Every time i get "Caught Exception" output, whats wrong?

Rokas
  • 1,712
  • 2
  • 18
  • 35

1 Answers1

2

I bet the Exception you get is a NetworkingOnMainThreadException. Networking operations tend to take some time, and that's why it's forbidden to perform such actions on the main (ui) thread in Android. This would make the UI unresponsive, which leads to a very bad user experience.

Have a look at AsyncTask for gracefully moving the operation to a background thread.

FD_
  • 12,947
  • 4
  • 35
  • 62