setVisibility()方法在activity / fragment

时间:2018-01-18 18:43:53

标签: android multithreading httprequest

我在使用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)机制感到困惑。如果有人能指出我应该如何更改我的代码,我将不胜感激。

2 个答案:

答案 0 :(得分:1)

如果您确定要调用onSuccessResponse,请尝试在UI线程上设置可见性:

@Override
public void onSuccessResponse(Object result) {
    TextView tv = (TextView) findViewById(R.id.myTextView);

    YourActivity.runOnUiThread(new Runnable()
    {
        @Override
        public void run()
        {
            tv.setVisibility(View.VISIBLE);
        }
    });
}

答案 1 :(得分:0)

这是我的需要补充。我建议您使用此库https://github.com/loopj/android-async-http的其他方式,而不是使用AsyncTask

AsyncHttpClient client = new AsyncHttpClient();
client.get("https://www.google.com", new AsyncHttpResponseHandler() {

    @Override
    public void onStart() {
        // called before request is started
    }

    @Override
    public void onSuccess(int statusCode, Header[] headers, byte[] response) {
        // called when response HTTP status is "200 OK"
    }

    @Override
    public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {
        // called when response HTTP status is "4XX" (eg. 401, 403, 404)
    }

    @Override
    public void onRetry(int retryNo) {
        // called when request is retried
    }
});

您需要检查清单中的INTERNET权限

您的doInBackground()需要返回一个字符串

@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();
            }
        }
        return result; // You miss this return
    }