0

whenever I use the app switcher or the app gets paused in any other way then upon resuming it I will get a NullPointerException when trying to use findViewById in my fragment. The same happens when trying to use getActivity() or anything related to the Main activity. I've tried checking of the fragment is attached or not with isAdded() and it returns true but still gives the error. (Don't mind the way the code looks, I still need to clean it up)

All irrelevant classes and methods are not included (ex. Profanity class).

MainActivity onStart method (Launch activity)

@Override
public void onStart() {
    super.onStart();
    Profanity.downloadList();
    if (AskForPermissions()) {
        if (mAuth.getCurrentUser() != null) {
            mAuth.getCurrentUser().reload().addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
                    fragmentTransaction.replace(R.id.MainFragment, new LoginFragment()).commit();
                }
            }).addOnSuccessListener(new OnSuccessListener<Void>() {
                @Override
                public void onSuccess(Void aVoid) {
                    FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
                    fragmentTransaction.replace(R.id.MainFragment, new HomeFragment()).commit();
                }
            });
        } else {
            FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
            fragmentTransaction.replace(R.id.MainFragment, new LoginFragment()).commit();
        }
    } else {
        onStart();
    }
}

HomeFragment (The one that crashes, crash happens under Started() on the 4th line)

@SuppressWarnings("all")
@Override
public void onStart() {
    super.onStart();

    loadVariables();

    final String UUID = ((MainActivity) getActivity()).mAuth.getCurrentUser().getUid();
    User.UUID = UUID;
    if (User.userName == null || User.userName.equals("")) {
        Functions.loadUserData(UUID).addOnCompleteListener(new OnCompleteListener() {
            @Override
            public void onComplete(@NonNull Task task) {

                if (task.getResult() == null) {
                    final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                    builder.setTitle("Choose your username");

                    final EditText input = new EditText(getActivity());
                    input.setInputType(InputType.TYPE_CLASS_TEXT);
                    builder.setView(input);

                    builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                        }
                    });

                    final AlertDialog dialog = builder.create();
                    dialog.show();

                    dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (input.getText() != null && !input.getText().toString().equals("") && !input.getText().toString().equals(" ")) {
                                if (input.getText().toString().toCharArray().length > 16) {
                                    dialog.dismiss();
                                    Functions.showBottomMessage(getView(), "Your username must be maximum 16 characters.");
                                    dialog.show();
                                } else if (Profanity.contains(input.getText().toString())) {
                                    dialog.dismiss();
                                    Functions.showBottomMessage(getView(), "Please refrain from using restricted words in your username.");
                                    input.setText("");
                                    dialog.show();
                                } else {
                                    User.userName = input.getText().toString();
                                    dialog.dismiss();
                                    FirebaseReferences.users.child(User.UUID).child("name").setValue(User.userName);
                                    Functions.showBottomMessage(getView(), "Username saved.");
                                }
                            } else {
                                dialog.dismiss();
                                Functions.showBottomMessage(getView(), "Please enter a valid username.");
                                dialog.show();
                            }
                        }
                    });

                    Started();
                } else {

                    HashMap temp = (HashMap) task.getResult();

                    if (temp.containsKey("name")) {
                        User.userName = temp.get("name").toString();
                    } else {
                        final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                        builder.setTitle("Choose your username");

                        final EditText input = new EditText(getActivity());
                        input.setInputType(InputType.TYPE_CLASS_TEXT);
                        builder.setView(input);

                        builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        });

                        final AlertDialog dialog = builder.create();
                        dialog.show();

                        dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                if (input.getText() != null && !input.getText().toString().equals("") && !input.getText().toString().equals(" ")) {
                                    User.userName = input.getText().toString();
                                    dialog.dismiss();
                                    FirebaseReferences.users.child(UUID).child("name").setValue(input.getText().toString());
                                } else {
                                    dialog.dismiss();
                                    dialog.show();
                                }
                            }
                        });
                    }
                    if (temp.containsKey("place")) {
                        User.place = temp.get("place").toString();
                    }
                    if (temp.containsKey("ratedImages")) {
                        User.ratedImages = (ArrayList<String>) temp.get("ratedImages");
                    }
                    if (temp.containsKey("developer")) {
                        if (Boolean.valueOf(temp.get("developer").toString().toLowerCase()))
                            User.isDeveloper = true;
                    }

                    Started();
                }
            }
        });
    } else {
        Started();
    }
}

@SuppressWarnings("all")
private void Started() {
    mainImageProgressBar.setVisibility(View.VISIBLE);
    secondaryImageProgressBar.setVisibility(View.VISIBLE);
    CacheHandler.update(getActivity(), imageView, secondImageView, true);
    /*THIS IS THE FIRST CRASH POINT - */getView().findViewById(R.id.fabSendImage).setOnClickListener(getBtnSendImageOnClickListener());
    getView().findViewById(R.id.btnReportImage).setOnClickListener(btnReportImageOnClick);
}
Maddy
  • 4,525
  • 4
  • 33
  • 53
Devvix
  • 49
  • 1
  • 9
  • Possible duplicate of [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Milad Moosavi Nov 21 '17 at 12:13

2 Answers2

1

All view related code must be moved on to onCreateView(). So just place your code to onCreateView in case of fragment and onCreate in case of activity.

For more info just go through https://developer.android.com/guide/components/fragments.html

Suraj Nair
  • 1,729
  • 14
  • 14
0

Crashing because of getView(). Because its not able get the view.

You need to pass the view which hold the view with id R.id.fabSendImage and try calling the view.findViewById(R.id.fabSendImage) to initialize.

Durga M
  • 534
  • 5
  • 17
  • But why would this work before the application is paused and not after? Does it not automatically re-attach the view to the fragment? – Devvix Nov 21 '17 at 11:59
  • Just tried this but to load the view in code i'd need to pass a context and then it crashes when trying to get the context with a nullpointerexception. – Devvix Nov 21 '17 at 12:05
  • Don't worry, fixed it by moving my code to on create view. Thanks for the help anyway! :) – Devvix Nov 21 '17 at 14:28