从Android中的Asynctask返回布尔值

时间:2014-04-07 16:17:33

标签: java android android-asynctask status

我是android新手。我想要做的只是将URL传递给Asynctask,然后检查是否返回状态代码SC_OK。如果返回状态代码SC_OK,则该方法应返回true,如果有任何其他状态代码,则返回false。

class checking extends AsyncTask<String, Void, Boolean> {

    @Override
    protected Boolean doInBackground(String... params) {
        // TODO Auto-generated method stub
        Boolean a;
        HttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(l1);      
        HttpResponse response;
        try {
            response = client.execute(httpGet);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if (statusCode != HttpStatus.SC_OK) {                                   
                Toast.makeText(getApplicationContext(),"No", Toast.LENGTH_LONG).show();
                a= false;
            }
            else {
                Toast.makeText(getApplicationContext(),"Yes", Toast.LENGTH_LONG).show();
                a= true; 
            }
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        finally{
            return false;
        }              
    }

    @Override
    protected void onPostExecute(Boolean result) {

    }
}

2 个答案:

答案 0 :(得分:1)

将整个事物改为(盲编码):

class checking extends AsyncTask<String, Void, Boolean> {
    @Override
    protected Boolean doInBackground(String... params) {
        // TODO Auto-generated method stub
        Boolean a;
        HttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(l1);
        HttpResponse response;
        try {
            response = client.execute(httpGet);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if (statusCode != HttpStatus.SC_OK) {
                a = false;
            } else {
                a = true;
            }
            return a;
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return false;
    }
    @Override
    protected void onPostExecute(Boolean result) {
        Toast.makeText(getApplicationContext(), (result ? "Yes" : "No"), Toast.LENGTH_LONG).show();
    }
}

答案 1 :(得分:1)

您正在将本地布尔a设置为true,但之后永远不会返回该值。正如所写的那样,该方法将始终返回false