0

Problems are solved. The cause is that I forgot to give Internet permission to the application.

The basic function I want to implement is that

  1. get a URL and connect to a remote server
  2. get results from remote server and show the results on TextView

I use a asynctask to load results from remote server. However, I have been debugging the following codes for hours, and still get no clue where goes wrong. Can anyone help me out?

private class ReportLocationTask extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... urls) {

            try {
                return reportLoc(urls[0]);
            } catch (IOException e) {
                return getResources().getString(R.string.connection_error);
            } 
        }

        @Override
        protected void onPostExecute(String result) {

            mActivityIndicator.setVisibility(View.GONE);
            mReport.setText(result);
        }
    }

    private String reportLoc(String urlstring) throws IOException{

        URL url = new URL(urlstring);

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();



        try{
        InputStream in = new BufferedInputStream(conn.getInputStream());

        InputStreamReader is = new InputStreamReader(in);
        StringBuilder sb=new StringBuilder();
        BufferedReader br = new BufferedReader(is);
        String read = br.readLine();

        while(read != null) {
            //System.out.println(read);
            sb.append(read);
            read =br.readLine();

        }

        return sb.toString();
        }
        finally {
            conn.disconnect();
            }

    }
3
  • 2
    What is the error? post your logcat trace Commented May 30, 2013 at 15:40
  • Share your logcat results.. What exactly is the error? Commented May 30, 2013 at 16:43
  • Problems are solved. The cause is that I forgot to give Internet permission to the application. Thanks, guys. Commented May 31, 2013 at 3:15

1 Answer 1

1

you haven't specified a request method. i assume you want to GET the results from the server.

   HttpURLConnection conn = (HttpURLConnection ) url.openConnection();
   conn.setRequestMethod("GET");
   conn.setReadTimeout(10000); // millis
   conn.setConnectTimeout(15000); // millis
   conn.setDoOutput(true);

   conn.connect();
   int response = conn.getResponseCode();
   if (response == HttpStatus.SC_OK) {
       .....
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.