【发布时间】:2018-01-18 18:43:53
【问题描述】:
我在使用 AsyncTask 处理来自服务器的响应时遇到问题:
-> 我有活动。在 onResume() 方法中,我调用我的 AsyncTask 从服务器获取一些数据:
@Override
public void onResume() {
super.onResume();
//I convey instance of my activity to task, to serve response
HttpTask httpTask = new HttpTask(this);
httpTask.execute(url);
}
我的活动实现 ServiceCallable 来处理响应:
public interface ServiceCallable {
public void onSuccessResponse(Object result);
}
HttpTask的代码如下:
public class HttpTask extends AsyncTask<String, Integer, String> {
private String result = "";
private ServiceCallable caller;
public HttpTask(ServiceCallable caller) {
this.caller = caller;
}
@Override
protected String doInBackground(String... params) {
URL url;
HttpURLConnection conn = null;
try {
url = new URL(params[0]);
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod(httpRequestType);
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.connect();
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
result = readStream(conn.getInputStream());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (conn != null) {
conn.disconnect();
}
}
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
caller.onSuccessResponse(result);
}
}
然后在我的活动中,我实现了 onSuccessResponse() 方法来处理响应:
@Override
public void onSuccessResponse(Object result) {
//make something with result from service
//....
TextView tv = (TextView) findViewById(R.id.myTextView);
//this doesn't work:
tv.setVisibility(View.VISIBLE);
}
我不知道我做错了什么。我确定 httpRequest 工作正常,并且我的活动的 onSuccessResponse 方法被调用。我听说由于从其他线程调用 setVisibility 可能会出错。也许我与我的调用者(ServiceCallable)机制混淆了一些东西。如果有人能指出我应该如何更改我的代码,我将不胜感激。
【问题讨论】:
-
您究竟想要做什么,因为
this doesn't work: -
你有错误日志吗?
-
您可能需要在 UI 线程上设置可见性。
-
"您可能需要在 UI 线程上设置可见性。" -> 如何使用 AsyncTask 做到这一点?
-
"你有错误日志吗?" -> 没有错误日志:即使我将可见性设置为“View.VISIBLE”,我的文本视图仍然不可见。
标签: android multithreading httprequest