无法处理AsyncTask调用的方法中的异常

时间:2017-07-05 15:34:41

标签: java android exception asynchronous

我似乎无法正确处理异常。这是我的异步方法:

private class PostData extends AsyncTask<String, Void, Void>
    {
        String response;
        protected void onPreExecute()
        {
            apply.setText("APPLYING...");
        }
        @Override
        protected Void doInBackground(String... params) {

            try {
                SendHTTPData sendHTTPData = new SendHTTPData();
                response = sendHTTPData.sendData(params);
            }
            catch(Exception e)
            {
                Log.e("someTag", "Caught exception after doinbackground");
                response = "ERROR!";
            }
                return null;
        }
        protected void onPostExecute()
        {
            apply.setText(response);
        }
}

现在,每当调用sendData方法时,它都会返回“ERROR”或“APPLIED”字符串,但是当网页关闭时,会生成例外的ConnectException和SQLite异常,然后我的按钮被卡住了在“申请”状态。

我想在sendData方法出错时将按钮文本设置为“ERROR”。

以下是我的sendHTTPData类:

public class SendHTTPData {

    public String sendData(String...)
    {
        String POST_DATA = "switch=" + sw + ...
            try {
                URL update = new URL(Utils.WEB_URL+path+"?"+POST_DATA);
                BufferedReader in = new BufferedReader(
                        new InputStreamReader(update.openStream()));

                String inputLine;
                while ((inputLine = in.readLine()) != null) {}
                in.close();
                Log.w("someTag", "DONE GET RESPONSE");
                if(inputLine=="1")
                    return "APPLIED";
                else
                    return "ERROR";
            }
            catch (Exception e) {
                Log.e("someTag", "ERROR BC OF EXCEPTION");
                return "ERROR";
            }

        }
}

1 个答案:

答案 0 :(得分:2)

您的onPostExecute不正确,因此可能永远不会被调用它看起来应该是

@Override
protected void onPostExecute(Void param)
{
    apply.setText(response);
}

理想情况下,您应该将响应发送到onPostExecute,因为您使用它的所有内容应该是这样的

private class PostData extends AsyncTask<String, Void, String>
    {
        protected void onPreExecute()
        {
            apply.setText("APPLYING...");
        }
        @Override
        protected String doInBackground(String... params) {
            String response;
            try {
                SendHTTPData sendHTTPData = new SendHTTPData();
                response = sendHTTPData.sendData(params);
            }
            catch(Exception e)
            {
                Log.e("someTag", "Caught exception after doinbackground");
                response = "ERROR!";
            }
                return response;
        }
        @Override
        protected void onPostExecute(String response)
        {
            apply.setText(response);
        }
}