错误:未报告的异常InterruptedException;必须被捕获或声明被抛出(调用AsyncTask)

时间:2014-02-03 11:45:06

标签: java android android-asynctask

这是我的类,它扩展了AsyncTask

public class JSONFunctions extends AsyncTask<Void, Void, String> {
    @Override
    protected String doInBackground(Void... urls) {
        String line = "";

        HttpClient httpclient = new DefaultHttpClient();
        HttpGet httpget = new HttpGet("http://appDev.milasevicius.com/server/homeresults.php");
        try {
            HttpResponse response = httpclient.execute(httpget);
            if(response != null) {
                InputStream inputstream = response.getEntity().getContent();
                line = convertStreamToString(inputstream);
            } else {
               line = "Unable to complete your request";
            }
        } catch (ClientProtocolException e) {
            line = "Caught ClientProtocolException";
        } catch (IOException e) {
            line = "Caught IOException";
        } catch (Exception e) {
            line = "Caught Exception";
        }

        return line;
    }

    protected void onProgressUpdate(Integer... progress) {
    }

    protected void onPostExecute(String result) {
    }
}

这是我的电话:

String output = new JSONFunctions().execute().get();

但是编译人员说

error: unreported exception InterruptedException; must be caught or declared to be thrown
抱歉我的愚蠢的问题,但如何解决这个问题?我是否正确地致电获得结果?

2 个答案:

答案 0 :(得分:1)

public final Result get ()

Added in API level 3
Waits if necessary for the computation to complete, and then retrieves its result.

Returns
The computed result.
Throws
CancellationException   If the computation was cancelled.
ExecutionException  If the computation threw an exception.
InterruptedException    If the current thread was interrupted while waiting.

get()抛出InterrruptedException。你的日志说你需要抓住它们。

此外,您不应该调用get()来阻止ui线程等待结果。你不应该阻止ui线程。

删除get()并调用new JSONFunctions().execute()

要在活动中获得结果,请使用界面

示例@

How do I return a boolean from AsyncTask?

答案 1 :(得分:0)

Javadoc

从.get()抛出的裸InterruptedException表示当前执行的线程             (调用.get()的那个在调用get()之前被中断,或者在.get()中被阻塞。         这与执行程序线程或其中一个任务被中断不同。      有人或              有些东西正在打扰你的&#34;主要&#34; thread - 或至少调用.get()的线程。

使用

new JSONFunctions().execute()

而不是

new JSONFunctions().execute().get();