1

Currently I'm coding an android project using Android Studio 3.1.2 and SDK 19.

When I refactored almost my whole code and replaced a lot of getContext() calls with requireContext() and getActivity() with requireActivity() i came across the problem, that the app crashes already at the launcher activity. I know that there are several posts related to the same problem of getting IllegalStateException: Fragment myFragment not attached to a contextbut they're all very project-specific so it doesn't actually show me the step i missed to do. So i hereby show you my example of code and pray for a merciful programmer that enlightens me, what I have to do, to solve this problem just in the suiting way.

This is my SplashActivity (the launcher activity):

public class SplashActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);

        Fragment fragmentToDisplay = null;
        if (!(getIntent().getBooleanExtra("isLaunch", true))) {
            fragmentToDisplay = new LoginFragment();
        } else {
            if (savedInstanceState == null) {
                fragmentToDisplay = new SplashFragment();
            }
        }
        if (fragmentToDisplay.isAdded()) {
            getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, fragmentToDisplay).commit();
        }
    }
}

This is the SplashFragment which gets loaded initially:

public class SplashFragment extends RequestingFragment {

    private Handler delayHandler = new Handler();

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View fragmentView = inflater.inflate(R.layout.fragment_splash, container, false);
        requestQueue = Volley.newRequestQueue(this.requireContext());
        requestParams.add(SessionHandler.getAppInstanceID(this.getContext()));
        startRequest(RequestOperation.SESSION_CHECK);
        onSuccess(new JSONObject(), "");
        return fragmentView;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        delayHandler.removeCallbacksAndMessages(null);
    }

    @Override
    public void onSuccess(final JSONObject json, String parsingKey) {
        delayHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                //parsing stuff
            }    
        }, 2000);
    }

    @Override
    public void onError() {
        showErrorDialog();
    }

    private void showErrorDialog() {
        //show a horrifying dialog
    }
}

I would be very thankful, if someone could explain to me, what in particular is causing the exception and how do I do it correctly. Thanks in advance.

procra
  • 535
  • 4
  • 29
  • https://stackoverflow.com/questions/28672883/java-lang-illegalstateexception-fragment-not-attached-to-activity – AskNilesh Oct 30 '18 at 09:04
  • For me, it was happening when I was moving to another fragment after detecting the OTP message by firebase. when the API response come(while manually entering OTP), i already moved to another fragment, so the previous fragment was not attached to the current activity anymore. I fixed it by just adding getActivity() !=null. – hushed_voice Oct 30 '18 at 09:17
  • @free_style i will try to wrap this around `requireActivity()` inside the `onSuccess()` of my SplashFragment. I don't use Firebase tho, but the request gets fired in the onCreateView method so maybe this is the smoking gun – procra Oct 30 '18 at 09:20
  • @free_style silly me, `requireActivity()` is a @NonNull method. Where did you add the null check in particular? – procra Oct 30 '18 at 09:26
  • @NileshRathod this post is not helping me, or i am just to foolish to understand it. But the user got a different exception as me, additionally i don't use `getActivity()` or `getContext()` anymore, but `requireActivity()` and `requireContext()` – procra Oct 30 '18 at 09:30
  • @Procra use this way to get context in fragment https://stackoverflow.com/a/52732620/7666442 – AskNilesh Oct 30 '18 at 09:32
  • @Procra Before you replace your fragment. – hushed_voice Oct 30 '18 at 09:35
  • @free_style can you provide a sample code as solution? It's hard for me to imagine what to write in particular – procra Oct 30 '18 at 09:37
  • 1
    requireActivity() will throw IllegalStateException("Fragment " + this + " not attached to an activity.").. so I guess u should use a try catch block and catch the exception – hushed_voice Oct 30 '18 at 09:44
  • 1
    @Procra i am thinking something like this. try{ requireActivity(); //move to fragment }catch (IllegalStateException e){ e.printStackTrace(); } – hushed_voice Oct 30 '18 at 09:47
  • @free_style can we discuss this in chat? the problem has maybe another root i didn't took care about. – procra Oct 30 '18 at 09:47
  • @Procra yeah sure – hushed_voice Oct 30 '18 at 09:50
  • dang what's the way to chat again!? – procra Oct 30 '18 at 09:50
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/182778/discussion-between-procra-and-free-style). – procra Oct 30 '18 at 09:52

0 Answers0