0

I have a MainActivity in which I instantiate a class. This class contains basic data and two important methods: GetRequestAccessUrl(params) and getToken(string) which returns an AuthResponse.

The first method runs fine, the string is generated and processed in the application. However, the getToken-method involves networking and is therefore prohibited to run on the main thread and AsyncTask is recommended. The implementation of the latter method is as following:

public AuthResponse getToken(String code) {
    if (secrete == null) {
        throw new IllegalStateException("Application secrete is not set");
    }

    try {

        URI uri = new URI(TOKEN_URL);
        URL url = uri.toURL();

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();


        try {
            StringBuilder sb = new StringBuilder();
            sb.append("client_id=" + clientId);
            sb.append("&client_secret=" + secrete);
            sb.append("&code=" + code);

            conn.setRequestMethod("POST");
            conn.setRequestProperty("Accept", "application/json");
            conn.setDoOutput(true);

            OutputStream os = conn.getOutputStream();


            os.write(sb.toString().getBytes("UTF-8"));

            if (conn.getResponseCode() != 200) {
                throw new RuntimeException("Failed : HTTP error code : "
                        + conn.getResponseCode());
            }

            Reader br = new InputStreamReader((conn.getInputStream()));
            Gson gson = new Gson();
            return gson.fromJson(br, AuthResponse.class);

        } finally {
            conn.disconnect();
        }
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

In the MainActivity the entire class is created, the first method is called, some actions are executed and the the getToken-method should run. However I seem to be completely stuck on how to do this, or how to create a (working) AsyncTask regarding this method. Any help is appreciated.

Shishdem
  • 499
  • 1
  • 5
  • 19

3 Answers3

1
new YourAsyncTask ().execute(code);


private class YourAsyncTask extends AsyncTask<String, Integer, Integer> {
     protected Long doInBackground(String... codes) {
        AuthResponse res = getToken(codes[0]);
        doSthWithRes(res);
     }

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

     protected void onPostExecute(Integer result) {}
 }

This will probably work. Depending on what you wanna do with the AuthResponse. As you can see the ASyncTask is more of a batch processing in the background. I prefer just using a Standard Thread. Additionally you may want to process the AuthResponse in the UIThread. Here the Quick and dirty version:

/* It would be better to create a subclass of Runnable and pass the Code in the constructor*/
final String code = "testcode";
//Create the new Thread
Thread t  = new Thread(new Runnable() {
    @Override
    public void run() {
        final AuthResponse res = getToken(code);
        //RunOnUiThread is a method of the Activity
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                doSomethingWithResponse(res);
            }
        });
    }       
});
t.start()
xeed
  • 925
  • 8
  • 22
0

Try something like this

   new AsyncTask<String, void, AuthResponse>() {
    @Override
    protected String doInBackground(String... params) {
        String id = params[0];
        String secret = params[1];
        String code = params[2];

        //do  your stuff

        return myAuthResponse;
    }
    @Override
    protected void onPostExecute(AuthReponse result) {
        //do stuff with AuthResponse
    }
}.execute(clientId, clientSecret, code);

In onPostExecute you can handle the AuthResponse on the UIThread.

botzek13
  • 111
  • 6
0

I think that I answered this in the following thread : Java AsyncTask passing variable to main thread

A Http request is done in background in an Asyntask and the result is sent to the main activity thanks to a Callback. I gave a sample code on the answer.

Community
  • 1
  • 1
Jejefcgb
  • 390
  • 3
  • 14