0

I'm building an android aplication and I'm having some trouble with a helper class getting the aplication context. I have two activities that call a function of my helper class, both of them pass the aplication context but only one of them works, the other one gives me a NPE.

The activities are related, HomeActivity goes to ArCondicionadoActivity carrying some extras, a few lines after the function call.

Here is the helper class code:

public class AccessToken {

private SharedPreferences sharedPreferences;

private OkHttpClient client = new OkHttpClient();
private MediaType JSON = MediaType.parse("application/json; charset=utf-8");
private JSONObject jsonBodyParams = new JSONObject();
private JSONObject jsonBodyParamsRefresh = new JSONObject();

private Boolean loggedIn = false;

private String token;
private String refreshToken;

private String userID;

private FileInputStream FJWT;
private FileInputStream FID;
private FileInputStream FJWR;
private FileOutputStream FOST;

public Boolean validaLogin(Context context) throws IOException {

    FJWT = context.openFileInput("JWToken");
    InternalFileReader IFT = new InternalFileReader();
    token = IFT.readFile(FJWT);
    Log.i("tokenlidoT", token);

    FJWR = context.openFileInput("JWRefreshToken");
    InternalFileReader IFR = new InternalFileReader();
    refreshToken = IFR.readFile(FJWR);
    Log.i("tokenlidoR", refreshToken);



    FID = context.openFileInput("UID");
    InternalFileReader IFU = new InternalFileReader();
    userID = IFU.readFile(FID);
    Log.i("UIDLido", userID);



    OkHttpClient.Builder builder = new OkHttpClient.Builder();
    builder.connectTimeout(30, TimeUnit.SECONDS);
    builder.readTimeout(30, TimeUnit.SECONDS);
    builder.writeTimeout(30, TimeUnit.SECONDS);
    client = builder.build();

    if (token!=null){
        try {
            jsonBodyParams.put("token", token);
            Log.i("tokenLidoInternal", token);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestBody loginBody = RequestBody.create(JSON, jsonBodyParams.toString());
        Request request = new Request.Builder()
                .url(context.getResources().getString(R.string.verify_url))
                .header("Content-Type", "application/json")
                .post(loginBody)
                .build();
        Log.i("request", String.valueOf(request.headers()));
        Log.i("request", String.valueOf(jsonBodyParams.toString()));
        Log.i("request", String.valueOf(request));
        Response response = null;

        try {
            response = client.newCall(request).execute();
        } catch (IOException e) {
            Log.i("INITIRESPONSE", "FAIL");
            e.printStackTrace();
        }
        Log.i("INITRESPONSE", String.valueOf(response));
        Log.i("INITRESPONSE", String.valueOf(response.isSuccessful()));

        if (!response.isSuccessful()) {

            if (refreshToken!=null){
                try {
                    jsonBodyParamsRefresh.put("refresh", refreshToken);
                    Log.i("refreshTokenLido", refreshToken);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                RequestBody refreshBody = RequestBody.create(JSON, jsonBodyParamsRefresh.toString());
                Request requestRefresh = new Request.Builder()
                        .url(context.getResources().getString(R.string.verify_url_refresh_token))
                        .header("Content-Type", "application/json")
                        .post(refreshBody)
                        .build();
                Log.i("requestRefresh", String.valueOf(requestRefresh.headers()));
                Log.i("requestRefresh", String.valueOf(jsonBodyParamsRefresh.toString()));
                Log.i("requestRefresh", String.valueOf(requestRefresh));
                Response responseRefresh = null;

                try {
                    responseRefresh = client.newCall(requestRefresh).execute();
                } catch (IOException e) {
                    Log.i("INITIRESPONSEREFRESH", "FAIL");
                    e.printStackTrace();
                }
                Log.i("INITIRESPONSEREFRESH", String.valueOf(responseRefresh));
                Log.i("INITIRESPONSEREFRESH", String.valueOf(responseRefresh.isSuccessful()));

                if (!responseRefresh.isSuccessful()){
                    loggedIn = false;
                    Log.i("RESULT", "response not successfull");
                    throw new IOException("Unexpected code " + responseRefresh);
                }else {
                    Log.i("RESULTREFRESH", "refresh response successfull");
                    JSONObject responseBodyJson = null;

                    try {
                        responseBodyJson = new JSONObject(responseRefresh.body().string());
                    } catch (JSONException | IOException e) {
                        e.printStackTrace();
                    }

                    try {
                        assert responseBodyJson != null;
                        FOST = context.openFileOutput("JWToken", Context.MODE_PRIVATE);
                        String stringToken = responseBodyJson.getString("accessToken");
                        FOST.write(stringToken.getBytes());
                        FOST.close();
                    } catch (IOException e) {
                        Log.i("IOE", "refreshAccess");
                        e.printStackTrace();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    loggedIn = true;
                }
                responseRefresh.close();

            }else {
                Log.i("RESULT", "refresh token non-existent");
                loggedIn = false;
            }



        } else {
            Log.i("RESULT", "response successfull");
            loggedIn = true;
        }
        response.close();

    } else {
        loggedIn = false;
        Log.i("RESULT", "token non-existent");
    }

    return loggedIn;
}

public String validaLoginTokenReturn(Context context) throws IOException {

    FJWT = context.openFileInput("JWToken");
    InternalFileReader IFT = new InternalFileReader();
    token = IFT.readFile(FJWT);
    Log.i("tokenlidoT", token);
    FJWR = context.openFileInput("JWRefreshToken");
    InternalFileReader IFR = new InternalFileReader();
    refreshToken = IFR.readFile(FJWR);
    Log.i("tokenlidoR", refreshToken);
    FID = context.openFileInput("UID");
    InternalFileReader IFU = new InternalFileReader();
    userID = IFU.readFile(FID);
    Log.i("UIDLido", userID);
    OkHttpClient.Builder builder = new OkHttpClient.Builder();
    builder.connectTimeout(30, TimeUnit.SECONDS);
    builder.readTimeout(30, TimeUnit.SECONDS);
    builder.writeTimeout(30, TimeUnit.SECONDS);
    client = builder.build();
    if (token!=null){
        try {
            jsonBodyParams.put("token", token);
            Log.i("tokenLidoInternal", token);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestBody loginBody = RequestBody.create(JSON, jsonBodyParams.toString());
        Request request = new Request.Builder()
                .url(context.getResources().getString(R.string.verify_url))
                .header("Content-Type", "application/json")
                .post(loginBody)
                .build();
        Log.i("request", String.valueOf(request.headers()));
        Log.i("request", String.valueOf(jsonBodyParams.toString()));
        Log.i("request", String.valueOf(request));
        Response response = null;
        try {
            response = client.newCall(request).execute();
        } catch (IOException e) {
            Log.i("INITIRESPONSE", "FAIL");
            e.printStackTrace();
        }
        Log.i("INITRESPONSE", String.valueOf(response));
        Log.i("INITRESPONSE", String.valueOf(response.isSuccessful()));
        if (!response.isSuccessful()) {
            if (refreshToken!=null){
                try {
                    jsonBodyParamsRefresh.put("refresh", refreshToken);
                    Log.i("refreshTokenLido", refreshToken);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                RequestBody refreshBody = RequestBody.create(JSON, jsonBodyParamsRefresh.toString());
                Request requestRefresh = new Request.Builder()
                        .url(context.getResources().getString(R.string.verify_url_refresh_token))
                        .header("Content-Type", "application/json")
                        .post(refreshBody)
                        .build();
                Log.i("requestRefresh", String.valueOf(requestRefresh.headers()));
                Log.i("requestRefresh", String.valueOf(jsonBodyParamsRefresh.toString()));
                Log.i("requestRefresh", String.valueOf(requestRefresh));
                Response responseRefresh = null;
                try {
                    responseRefresh = client.newCall(requestRefresh).execute();
                } catch (IOException e) {
                    Log.i("INITIRESPONSEREFRESH", "FAIL");
                    e.printStackTrace();
                }
                Log.i("INITIRESPONSEREFRESH", String.valueOf(responseRefresh));
                Log.i("INITIRESPONSEREFRESH", String.valueOf(responseRefresh.isSuccessful()));
                if (!responseRefresh.isSuccessful()){
                    Log.i("RESULT", "response not successfull");
                    throw new IOException("Unexpected code " + responseRefresh);
                }else {
                    Log.i("RESULTREFRESH", "refresh response successfull");
                    JSONObject responseBodyJson = null;
                    try {
                        responseBodyJson = new JSONObject(responseRefresh.body().string());
                    } catch (JSONException | IOException e) {
                        e.printStackTrace();
                    }
                    try {
                        assert responseBodyJson != null;
                        FOST = context.openFileOutput("JWToken", Context.MODE_PRIVATE);
                        String stringToken = responseBodyJson.getString("accessToken");
                        token = stringToken;
                        FOST.write(stringToken.getBytes());
                        FOST.close();
                    } catch (IOException e) {
                        Log.i("IOE", "refreshAccess");
                        e.printStackTrace();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                responseRefresh.close();
            }else {
                Log.i("RESULT", "refresh token non-existent");
            }
        } else {
            Log.i("RESULT", "response successfull");
        }
        response.close();
    } else {

        Log.i("RESULT", "token non-existent");
    }
    return token;
}

}

Here are the calls (only the parts of the activities previous to the point where the call is actually made), first the one that works (HomeActivity):

 String tokenLido = "randomTokenForTesting";

airConditioningButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            new HomeActivity.getParamAirConditioning().execute(tokenLido);

        }
    });

private class getParamAirConditioning extends AsyncTask<String, Void, Response> {

    @Override
    protected void onPreExecute() {
        loadingDialog = ProgressDialog.show(HomeActivity.this,
                "Please wait...", "Getting data from server");
        loadingDialog.setCancelable(false);
    }

    protected Response doInBackground(String... params) {

        String token = params[0];

        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        OkHttpClient client = new OkHttpClient();

        JSONObject jsonBodyParams = new JSONObject();

        try {
            jsonBodyParams.put("acID", "1");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        try {
            token = accessToken.validaLoginTokenReturn(HomeActivity.this);
        } catch (IOException e) {
            e.printStackTrace();
        }

And now the one that doesn't (ArCondicionadoActivity):

String tokenLido = "randomTokenForTesting";
String temperatura= "randomTemperatureForTesting";
String fanSpeed= "randomFanSpeedForTesting";
String humidity= "randomHumidityForTesting";

confirma.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {


            new ArCondicionadoActivity.acUpdateServer().execute(tokenLido, temperatura, fanSpeed, humidity);

        }
    });

private class acUpdateServer extends AsyncTask<String, Void, Response> {

    @Override
    protected void onPreExecute() {
        loadingDialog = ProgressDialog.show(ArCondicionadoActivity.this,
                "Please wait...", "Updating data to server");
        loadingDialog.setCancelable(false);
    }

    protected Response doInBackground(String... params) {

        String token = params[0];
        String temperaturaUpdate = params[1];
        String acFanSpeedUpdate = params[2];
        String humidityUpdate = params[3];


        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        OkHttpClient client = new OkHttpClient();

        JSONObject jsonBodyParams = new JSONObject();


        try {
            jsonBodyParams.put("acID", "1");
            jsonBodyParams.put("acIsTurnedOn", "1");
            jsonBodyParams.put("acTemp", temperaturaUpdate);
            jsonBodyParams.put("acFanSpeed", acFanSpeedUpdate);
            jsonBodyParams.put("acHumidity", humidityUpdate);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        try {
            token = accessToken.validaLoginTokenReturn(ArCondicionadoActivity.this);
        } catch (IOException e) {
            e.printStackTrace();
        }

My stack is as follows:

08-29 21:08:06.631 10098-10529/com.example.giovanni.tcc E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #4
                                                                      Process: com.example.giovanni.tcc, PID: 10098
                                                                      java.lang.RuntimeException: An error occurred while executing doInBackground()
                                                                          at android.os.AsyncTask$3.done(AsyncTask.java:318)
                                                                          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 'java.lang.String com.example.giovanni.tcc.Security.AccessToken.validaLoginTokenReturn(android.content.Context)' on a null object reference
                                                                          at com.example.giovanni.tcc.ArCondicionadoActivity$acUpdateServer.doInBackground(ArCondicionadoActivity.java:313)
                                                                          at com.example.giovanni.tcc.ArCondicionadoActivity$acUpdateServer.doInBackground(ArCondicionadoActivity.java:277)
                                                                          at android.os.AsyncTask$2.call(AsyncTask.java:304)
                                                                          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) 

I appreciate any insight into what I'm doing wrong there in the second one.

And sorry about some of the names being in portuguese, hope it doesn't get too much in the way =P

  • That Exception isn't coming from the `Context`. `accessToken` is null. – Mike M. Aug 30 '17 at 00:51
  • 1
    oh...yeah, that was the issue...the initialization of accessToken was missing in that activity. Got it right on every other, so now everything works fine. Thank you very much. – Giovanni Pigola Aug 30 '17 at 01:33

0 Answers0