【发布时间】:2015-08-07 17:52:28
【问题描述】:
所以我试图通过 AsyncTask 类中的 HttpURLConnection 从服务器读取消息。问题是,当我发送从服务器读取数据的请求时,它只是一直显示 ProgresssDialog,就像它没有从服务器读取数据一样:
public class MainActivity extends Activity{
EditText name, password;
Button login;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = (EditText) findViewById(R.id.name);
password = (EditText) findViewById(R.id.password);
login = (Button) findViewById(R.id.login);
login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String serverURL = "http://192.168.1.1/my/text.php";
LongOperation longOperation = new LongOperation();
longOperation.execute(serverURL);
}
});
}
private class LongOperation extends AsyncTask<String, Void, Void> {
private String content;
private String error = null;
private ProgressDialog dialog = new ProgressDialog(MainActivity.this);
TextView uiUpdate = (TextView) findViewById(R.id.output);
@Override
protected void onPreExecute() {
uiUpdate.setText("Output : ");
dialog.setMessage("Downloading source..");
dialog.show();
}
@Override
protected Void doInBackground(String... urls) {
try {
URL url = new URL(urls[0]);
HttpURLConnection client = (HttpURLConnection)url.openConnection();
client.connect();
InputStream inputStream = client.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
content = bufferedReader.readLine();
bufferedReader.close();
inputStream.close();
client.disconnect();
} catch (IOException e) {
error = e.getMessage();
}
return null;
}
@Override
protected void onPostExecute(Void unused) {
dialog.dismiss();
if (error != null) {
uiUpdate.setText("Output : "+error);
} else {
uiUpdate.setText("Output : "+content);
}
}
在通过 HttpClient 连接到服务器之前我已经尝试过,所以这不是问题。谢谢!
【问题讨论】:
-
我在这里发表评论是因为它不是您问题的答案,而是一个建议。使用 Retrofit 进行 web api 调用。它会让您的生活更轻松。
-
为什么 onPostExecute 参数是点击监听器,但它被定义为 AsyncTask
-
你也应该在 asyncTask 中使用
@Override注解。这样你会注意到错误;-) -
用 Log 类做一些记录,看看是否调用了 onPostExecute。此外,Java 命名约定是实例以小写字母开头,使用 Dialog 代替 dialog 可能会让其他开发人员感到困惑。
-
@Lucas 的评论显示了问题所在。它永远不会进入您的 onPostExecute() 方法,因为它没有正确覆盖 AsyncTask 的 onPostExecute()。在每个覆盖方法之前添加
@Override是个好主意,这样IDE 会告诉您是否有问题。要修复它,只需将其定义为onPostExecute(Void unused)