-2

I am trying to exchange my authentication code for an access token. I am using an AsyncTaskRunner, however, I am getting a error:

java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference at java.net.URLEncoder.encode(URLEncoder.java:205).

Here is my request parameters:

CLIENT_ID = "1fb7c350-bb6a-5741-86b9-43afc2f1642f";
REDIRECT_URI = "https://xxxx.xxxxx.xxxx/rest/callback.html";
CLIENT_SECRET = "xxxxxxx";
GRANT_TYPE = "authorization_code";
ACCESS_TOKEN_URL = "https://xxxx.xxxxxx.com/oauth/token";

My AsyncTask class

private class AsyncTaskRunner extends AsyncTask<String, String, String> {
    @Override
    protected String doInBackground(String... params) {
        try {
            URL url = null;
            InputStream stream = null;
            HttpURLConnection urlConnection = null;
            try {
                url = new URL(ACCESS_TOKEN_URL);
                urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setRequestMethod("POST");
                urlConnection.setDoOutput(true);

                data = URLEncoder.encode("client_id", "UTF-8")
                        + "=" + URLEncoder.encode(CLIENT_ID, "UTF-8"); //*This line above is where the caused by exception is pointing to.*

                data += "&" + URLEncoder.encode("client_secret", "UTF-8") + "="
                        + URLEncoder.encode(CLIENT_SECRET, "UTF-8");
                data += "&" + URLEncoder.encode("grant_type", "UTF-8") + "="
                        + URLEncoder.encode(GRANT_TYPE, "UTF-8");
                data += "&" + URLEncoder.encode("code", "UTF-8") + "="
                        + URLEncoder.encode(authCode, "UTF-8");
                data += "&" + URLEncoder.encode("redirect_uri", "UTF-8") + "="
                        + URLEncoder.encode(REDIRECT_URI, "UTF-8");

                urlConnection.connect();

                OutputStreamWriter wr = new OutputStreamWriter(urlConnection.getOutputStream());
                wr.write(data);
                wr.flush();

                stream = urlConnection.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"), 8);
                String result = reader.readLine();
                accessToken = result;
                return accessToken;

            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (urlConnection != null) {
                    urlConnection.disconnect();
                }
            }

            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
                Log.i("Result", "SLEEP ERROR");
            }
            return null;
        } finally {
            Log.i("Result", "SLEEP ERROR");
        }
    }
}

And on my Send button:

authCode = sharedPreferences.getString("code", null);
params=new String[5];
CLIENT_ID = params[0];
CLIENT_SECRET = params[1];
GRANT_TYPE = params[2];
REDIRECT_URI = params[3];
authCode = params[4];
new AsyncTaskRunner().execute(params);

Here is my full logcat:

07-04 11:43:57.749 7157-8120/almac.com.cameratutorialtest E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #2
Process: almac.com.cameratutorialtest, PID: 7157
java.lang.RuntimeException: An error occurred while executing doInBackground()
    at android.os.AsyncTask$3.done(AsyncTask.java:325)
    at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
    at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
    at java.util.concurrent.FutureTask.run(FutureTask.java:242)
    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
    at java.lang.Thread.run(Thread.java:761)
    Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference
    at java.net.URLEncoder.encode(URLEncoder.java:205)
    at almac.com.cameratutorialtest.MainActivity$AsyncTaskRunner.doInBackground(MainActivity.java:275)
    at almac.com.cameratutorialtest.MainActivity$AsyncTaskRunner.doInBackground(MainActivity.java:256)
    at android.os.AsyncTask$2.call(AsyncTask.java:305)
    at java.util.concurrent.FutureTask.run(FutureTask.java:237)
    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243) 
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133) 
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607) 
    at java.lang.Thread.run(Thread.java:761) 

How is it getting null when it has been set above? and why is it not getting as far as retrieving the access token?

Empty Brain
  • 627
  • 8
  • 24
Aaron
  • 47
  • 11
  • Please *format* this horrible mess of a question. It Is highly unreadable. Also just pasting all your code is not making this question any more clear. Please tell us more. The stacktrace is nice, but we don't have the line numbers, which makes it pretty hard for us – Lino Jul 04 '18 at 10:54
  • may be your **`authCode`** is null – AskNilesh Jul 04 '18 at 10:55
  • sigh. Here's your error `Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference`. Fix that – Zun Jul 04 '18 at 10:57
  • sorry @Lino I edited it as I couldn't get line numbers in, I didn't paste all my code just what I thought was needed. and my authcode is not null I have debugged it and printed it many times and it has a value – Aaron Jul 04 '18 at 10:57
  • I can see that @ZUNJAE. That is why I am asking this question. – Aaron Jul 04 '18 at 10:59
  • `params=new String[5];` creates an array of nulls, and assigning values out of this array sets everything as null. – laalto Jul 04 '18 at 11:02
  • Why use such as low-level API to call the other server? Use some kind of web client so you can actually easily retrieve a response code and body and also set the data in a much nicer way. – Sebastiaan van den Broek Jul 04 '18 at 11:08
  • @SebastiaanvandenBroek I have been searching and using different APIs such as httpurlconnection and OkHttp. I found this one on here and it seems to be the only one that's actually trying to retrieve it. – Aaron Jul 04 '18 at 11:10
  • Alright, well I would at least have a look at checking for the response code, that would probably give you a hint to what's going wrong (after you fixed this null pointer according to the answer of course) – Sebastiaan van den Broek Jul 04 '18 at 11:16
  • could you please help with my latest post. I have tried using Retrofit: https://stackoverflow.com/questions/51187013/retrofit-not-retrieving-accesstoken – Aaron Jul 05 '18 at 08:52

1 Answers1

2

Replace

authCode = params[4];

with

params[4] = authCode

Right here

authCode = sharedPreferences.getString("code", null);
params=new String[5];
CLIENT_ID = params[0];
CLIENT_SECRET = params[1];
GRANT_TYPE = params[2];
REDIRECT_URI = params[3];
authCode = params[4];
new AsyncTaskRunner().execute(params);`

You're setting each variable to null which is not what you want, that's why you get a nullpointer error.

Zun
  • 1,553
  • 3
  • 15
  • 26
  • still the same error on the same line with the null object – Aaron Jul 04 '18 at 11:01
  • can you show proof that the error is still there? Take a screenshot including the new code and stacktrace. – Zun Jul 04 '18 at 11:02
  • okay no longer crashing thanks! but I still not got getting access token for some reason. – Aaron Jul 04 '18 at 11:05
  • Yeah that's an entirely different issue. Mark my answer as correct considering _it did solve your issue_ – Zun Jul 04 '18 at 11:06
  • Or create a new post or edit your current one, cause right now you have multiple issues and you're trying to fit it into one submission. – Zun Jul 04 '18 at 11:07
  • okay np thanks @ZUNJAE. Just quickly, does the asynctask code that I am using suffice for trying to retrieve the code though? – Aaron Jul 04 '18 at 11:08
  • I personally do not use `HttpURLConnection`. It results in a lot of boilerplate code. I recommend using Retrofit for network requests – Zun Jul 04 '18 at 11:10
  • Could you please see my latest post. I have tried using Retrofit! https://stackoverflow.com/questions/51187013/retrofit-not-retrieving-accesstoken – Aaron Jul 05 '18 at 08:52