0

This is my class that extends 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) {
    }
}

And this is my call:

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

But compilator says that

error: unreported exception InterruptedException; must be caught or declared to be thrown

sorry for my noobish question, but how to fix that? And am I doing right call to get result?

Rokas
  • 1,712
  • 2
  • 18
  • 35

2 Answers2

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() throws InterrruptedException. Your log says you need to catch those.

Also you should not call get() coz its blocks the ui thread waiting fro the result. You should not block the ui thread.

Remove get() and invoke as new JSONFunctions().execute().

To get the result in the activity use a interface

Example @

How do I return a boolean from AsyncTask?

Community
  • 1
  • 1
Raghunandan
  • 132,755
  • 26
  • 225
  • 256
0

Javadoc

A bare InterruptedException being thrown from .get() indicates that the current thread of execution (the one calling .get()) was interrupted before calling get(), or while blocked in .get(). This is not the same thing as an executor thread or one of its tasks being interrupted. Someone or something is interrupting your "main" thread -- or at least the thread calling .get().

Use

new JSONFunctions().execute()

instead of

new JSONFunctions().execute().get();
Nambi
  • 11,944
  • 3
  • 37
  • 49