将android活动上下文传递给类函数时的NPE

时间:2017-08-30 00:34:56

标签: java android nullpointerexception

我正在构建一个android应用程序,并且我在帮助程序类获取应用程序上下文时遇到了一些麻烦。 我有两个调用我的帮助器类的函数的活动,它们都传递了应用程序上下文但只有一个有效,另一个给了我一个NPE。

活动是相关的,HomeActivity转到ArCondicionadoActivity,带有一些额外功能,在函数调用后几行。

这是助手类代码:

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;
}

}

以下是调用(仅实际调用点之前的活动部分),首先是有效的调用(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();
        }

现在是那个没有(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();
        }

我的堆栈如下:

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) 

我很欣赏在第二部分我在那里做错的任何见解。

对于一些葡萄牙语的名字感到抱歉,希望它没有太多的方式= P

0 个答案:

没有答案