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
- get a URL and connect to a remote server
- 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();
}
}