0

I've got this code inside my main class:

  public class vurlDownloader extends AsyncTask<Void, Void, String> {

    @Override
    protected String doInBackground(Void... params) {

        HttpClient httpClient = new DefaultHttpClient();
        HttpContext localContext = new BasicHttpContext();
        HttpGet httpGet = new HttpGet("http://url/video.html");
        HttpResponse response = null;
        try {
            response = httpClient.execute(httpGet, localContext);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String result = "";

        BufferedReader reader = null;
        try {
            reader = new BufferedReader(
                    new InputStreamReader(
                            response.getEntity().getContent()
                    )
            );
        } catch (IOException e) {
            e.printStackTrace();
        }


        String line = null;
        try {
            while ((line = reader.readLine()) != null){
                result += line + "\n";
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return result;

    }

}

public String loadVurl(){
    String output = new vurlDownloader().execute().get();
    return output;
}

and in this line
String output = new vurlDownloader().execute().get();
Android Studio gives me strange reference (red underline): Unhandled exceptions: java.lang.InterruptedException, java.util.concurrent.Execution.Exception

I don't quite understand this, becouse I've got simillar situation as here: How to get a string back from AsyncTask? and for this person it works.

Greetings!

Community
  • 1
  • 1
wzieba
  • 414
  • 2
  • 6
  • 21

3 Answers3

4

get() throws java.lang.InterruptedException. You need to have a try catch and catch those

http://developer.android.com/reference/android/os/AsyncTask.html#get()

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.

But you should not use get as it blocks the ui thread waiting for the result. This makes AsyncTask no more Asynchronous.

Solution

 new vurlDownloader().execute()

And You can update ui in onPostExecute if Asynctask is an inner class or use interface as a callback to the Activity.

Check blackbel's answer @

How do I return a boolean from AsyncTask?

A suggestion : Follow java naming conventions rename vurlDownloader() with VurlDownloader(). Class name begins with caps

Edit:

To invoke

 vurlDownloader().execute();

Then

class vurlDownloader() extends AsyncTask<Void,Void,String>
{

    @Override
    protected String doInBackground(Void... params) {

         String _response= null;

                    try {
                        HttpClient httpClient = new DefaultHttpClient();
                        HttpContext localContext = new BasicHttpContext();
                        HttpGet httpGet = new HttpGet("http://informat.net.pl/krachapp/video.html");
                        HttpResponse response = null;
                        response = httpClient.execute(httpGet, localContext);
                         _response = EntityUtils.toString(response.getEntity());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }    



        return _response;
    }

    @Override
    protected void onPostExecute(String result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);
        Log.i("Result is",result);
    }

}
Community
  • 1
  • 1
Raghunandan
  • 132,755
  • 26
  • 225
  • 256
  • @Ragunandan Ok, I follow your thinking but I've got issue: when I write UI changes in `onPostExecute` there's problem with method `getSupportFragmentManager` which is from YouTubeAPI. It just `Cannot resolve method` – wzieba Feb 25 '14 at 10:59
  • That is not a method. its fragment manager from the support library – Raghunandan Feb 25 '14 at 11:00
  • @tuksiarz post the entire code and check the edit again – Raghunandan Feb 25 '14 at 11:03
1

Try to implement your AsyncTask this way and you can get Result string into onPostExecute() as onBackground(...) method return

private class vurlDownloader() extends AsyncTask<String, Void, String> {

@Override
protected String doInBackground(String... params) {
    try {
         String _result= null;

                try {
                    HttpClient httpClient = new DefaultHttpClient();
                    HttpContext localContext = new BasicHttpContext();
                    HttpGet httpGet = new HttpGet("http://informat.net.pl/krachapp/video.html");
                    HttpResponse response = null;
                    response = httpClient.execute(httpGet, localContext);
                     _result = EntityUtils.toString(response.getEntity());
                } catch (IOException e) {
                    e.printStackTrace();
                }    

    } catch (InterruptedException e) {
        Log.e("LongOperation", "Interrupted", e);
        return "Interrupted";
    }
    return _result;
}      

@Override
protected void onPostExecute(String result) {               
  system.out.print(result);

 }
}

And called as

 new vurlDownloader().execute()

Go to this for more information:http://www.vogella.com/tutorials/AndroidBackgroundProcessing/article.html

M D
  • 47,665
  • 9
  • 93
  • 114
  • 1
    I still don't know how to recive string "result" from this AsyncTask. `String output = new vurlDownloader().execute();` doen't work (it's not string, isn't it?) – wzieba Feb 25 '14 at 10:43
  • @tuksiarz you still go wrong. you directly called your `AsyncTask` like `new vurlDownloader().execute()` and `AsyncTask` internally returns back `Result` value into `onPostExecute()` – M D Feb 25 '14 at 10:45
  • @MD asynctask will not return value interally. The result of doInbackground computation is a param to `onPostExecute`. The ui can be updated in onPostExecute provided its a inner class of activity. If its in a difference class then you need to look for different way – Raghunandan Feb 25 '14 at 10:50
0

Add Post execute method in your async task

 @Override
 protected void onPostExecute(String result) {
       Log.d("RESULT", "Result : " + result);
       finalResult = result; // here finalResult is string variable declared at class level

 }

Add one other method that is return final result of async task.

  public String getFinalResult() {
        return finalResult;
  }

When you need final result you can use getFinalResult method to get.

Solution
  • 604
  • 4
  • 10
  • so I did: in `onCreate` method I've written `new vurlDownloader(); VideoURL = vurlDownloader.loadVurl();` and I've got message that I can't reference from static context. – wzieba Feb 25 '14 at 10:51
  • .loadVurl(); is getFinalResult() in this case – wzieba Feb 25 '14 at 10:52
  • After your async task execution complete you can call getFinalResult to retrieve result of async task. – Solution Feb 25 '14 at 11:23