简体   繁体   中英

Fragment not attached to Activity, best solution?

I have an Activity with google map, and a fragment, with address (start/stop) fields in it.

When LocationManager return user's location first time, I'm try to update start field in addresses fragment.

But sometimes I get the exception: java.lang.IllegalStateException: Fragment CoordinatesFragment not attached to Activity

And I don't understand why. I know that there are method Fragment.isAdded() , wich I can use, but it seems not a best way to solve the problem.

Also sometimes I get this exception when try to restore state (in onRestoreInstanceState(Bundle state) i get data and in onMapLoaded() try to use)

private void setFragment(Fragment fragmentToSet, String tag) {

    FragmentManager manager = getSupportFragmentManager();
    FragmentTransaction transaction = manager.beginTransaction();
    Fragment fragment = manager.findFragmentByTag(tag);
    if (savedInstanceState == null) {
        if (fragment != null && !fragment.isAdded()) {
            transaction.replace(R.id.home_container, fragment, tag);
        } else if (fragmentToSet != null && !fragmentToSet.isAdded()) {
            transaction.replace(R.id.home_container, fragmentToSet, tag);
        }
    }else{
        transaction.replace(R.id.home_container, fragment, tag);
    }
    transaction.commitAllowingStateLoss();
    manager.executePendingTransactions();
}

Try using this function to set the fragment in your activity. Its working good for me. You can save the savedInstanceState from your activity's onCreate

If you could use RxJava 2, you could have the result of LocationManager in an Observable cached, and the Fragment could subscribe for the result.

If the result have arrived and the Fragment is not yet attached, the Fragment will recieve the result when it is attached. Else it will receive it instantly.

I recommend for you to learn how RxJava can be used to tackle such problems.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM