-2

I have a problem with AsyncTask in android. In android programming I am beginner and I can't find any solution.

Here is my code

onCreate function

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    final Button submitButton = (Button) findViewById(R.id.get_ingredient);
    submitButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            new Task().execute();
        }
    });
}

and my private Task class with doInBackground

private class Task extends AsyncTask<Void, Void, Ingredient> {

    @Override
    protected Ingredient doInBackground(Void... params) {
        final String url = getString(R.string.base_uri);

        RestTemplate restTemplate = new RestTemplate();
        Map<String, Integer> param = new HashMap<String, Integer>();
        param.put("id", 1);
        Ingredient ingredient = restTemplate.getForObject(url + "/ingredient/{id}", Ingredient.class, param);

        return ingredient;
    }
}

And here is my errors:

02-03 16:13:47.010    2463-2476/pl.kyniu.app.cookbook E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
Process: pl.kyniu.app.cookbook, PID: 2463
java.lang.RuntimeException: An error occured while executing doInBackground()
        at android.os.AsyncTask$3.done(AsyncTask.java:300)
        at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
        at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
        at java.util.concurrent.FutureTask.run(FutureTask.java:242)
        at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
        at java.lang.Thread.run(Thread.java:841)
 Caused by: org.springframework.web.client.HttpClientErrorException: 401 Unauthorized
        at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:76)
        at org.springframework.web.client.RestTemplate.handleResponseError(RestTemplate.java:590)
        at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:546)
        at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:511)
        at org.springframework.web.client.RestTemplate.getForObject(RestTemplate.java:276)
        at pl.kyniu.app.cookbook.MainActivity$updateTask.doInBackground(MainActivity.java:97)
        at pl.kyniu.app.cookbook.MainActivity$updateTask.doInBackground(MainActivity.java:78)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
        at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)

What I'm doing wrong?

Kyniu
  • 41
  • 9
  • The stack trace has all the information you need: you're getting a "401 Unauthorized" error in your HTTP response. – corsair992 Feb 03 '15 at 22:07

1 Answers1

0

You are getting a 401 unauthorized http response. You will have to handle authentication before you can consume the rest api. Below is an example for http basic auth I pulled from http://docs.spring.io/spring-android/docs/current/reference/html/rest-template.html.

// Set the username and password for creating a Basic Auth request
HttpAuthentication authHeader = new HttpBasicAuthentication(username, password);
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setAuthorization(authHeader);
HttpEntity<?> requestEntity = new HttpEntity<Object>(requestHeaders);

// Create a new RestTemplate instance
RestTemplate restTemplate = new RestTemplate();

// Add the String message converter
restTemplate.getMessageConverters().add(new StringHttpMessageConverter());

try {
    // Make the HTTP GET request to the Basic Auth protected URL
    ResponseEntity<Message> response = restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class);
    return response.getBody();
} catch (HttpClientErrorException e) {
    Log.e(TAG, e.getLocalizedMessage(), e);
    // Handle 401 Unauthorized response
}
  • How would you handle the 401 response ? My task is supposed to return a ResponseEntity and apart from a null I don't know what to return to signal the 401 response back to the activity. Should I even signal it to the activity ? – Stephane Jun 16 '15 at 09:11
  • @stephane I imagine you'd want to notify the user so you'd probably need to let the activity know. Catch the exception and remember it. Then when back on the UI thread do something if the exception was caught. For reference: http://stackoverflow.com/a/1739676/3418711 – mathewdgardner Jun 17 '15 at 17:53