Ошибка при Destroy`е Activity с Фрагментами

242
31 августа 2017, 18:05

Очень редкий баг, но его надо поправить. (Пришел по багтрекеру после месяца использования пользователями)

 UnknownException
at app.v4.support.android.FragmentManagerImpl.enqueueAction(FragmentManager.java:1864)
at app.v4.support.android.BackStackRecord.commitInternal(BackStackRecord.java:650)
at app.v4.support.android.BackStackRecord.commitAllowingStateLoss(BackStackRecord.java:614)
at manager.glide.bumptech.com.RequestManagerRetriever.getSupportRequestManagerFragment(RequestManagerRetriever.java:187)
at manager.glide.bumptech.com.SupportRequestManagerFragment.onAttach(SupportRequestManagerFragment.java:116)
at app.v4.support.android.Fragment.onAttach(Fragment.java:1222)
at app.v4.support.android.FragmentManagerImpl.moveToState(FragmentManager.java:1231)
at app.v4.support.android.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1528)
at app.v4.support.android.FragmentManagerImpl.moveToState(FragmentManager.java:1595)
at app.v4.support.android.BackStackRecord.executeOps(BackStackRecord.java:758)
at app.v4.support.android.FragmentManagerImpl.executeOps(FragmentManager.java:2363)
at app.v4.support.android.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2149)
at app.v4.support.android.FragmentManagerImpl.optimizeAndExecuteOps(FragmentManager.java:2103)
at app.v4.support.android.FragmentManagerImpl.execPendingActions(FragmentManager.java:2013)
at app.v4.support.android.FragmentManagerImpl.dispatchDestroy(FragmentManager.java:2949)
at app.v4.support.android.Fragment.performDestroy(Fragment.java:2430)
at app.v4.support.android.FragmentManagerImpl.moveToState(FragmentManager.java:1442)
at app.v4.support.android.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1528)
at app.v4.support.android.FragmentManagerImpl.moveToState(FragmentManager.java:1595)
at app.v4.support.android.FragmentManagerImpl.dispatchDestroy(FragmentManager.java:2951)
at app.v4.support.android.FragmentController.dispatchDestroy(FragmentController.java:271)
at app.v4.support.android.FragmentActivity.onDestroy(FragmentActivity.java:390)
at app.v7.support.android.AppCompatActivity.onDestroy(AppCompatActivity.java:209)
at relaxfm.ru.ideast.MainActivity.onDestroy(MainActivity.java:316)
at app.android.Activity.performDestroy(Activity.java:6200)
at app.android.Instrumentation.callActivityOnDestroy(Instrumentation.java:1141)
at app.android.ActivityThread.performDestroyActivity(ActivityThread.java:3765)
at app.android.ActivityThread.handleDestroyActivity(ActivityThread.java:3796)
at app.android.ActivityThread.access$1400(ActivityThread.java:151)
at app.android.ActivityThread$H.handleMessage(ActivityThread.java:1367)
at os.android.Handler.dispatchMessage(Handler.java:102)
at os.android.Looper.loop(Looper.java:135)
at app.android.ActivityThread.main(ActivityThread.java:5348)
at reflect.lang.java.Method.invoke(Native Method)
at reflect.lang.java.Method.invoke(Method.java:372)
at os.internal.android.com.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:947)
at os.internal.android.com.ZygoteInit.main(ZygoteInit.java:742)
lang.java.RuntimeException: (Unable to destroy activity {ru.vkpm.comedy/ideast.ru.relaxfm.MainActivity}: java.lang.IllegalStateException: Activity has been destroyed)
at app.android.ActivityThread.performDestroyActivity(ActivityThread.java:3778)
at app.android.ActivityThread.handleDestroyActivity(ActivityThread.java:3796)
at app.android.ActivityThread.access$1400(ActivityThread.java:151)
at app.android.ActivityThread$H.handleMessage(ActivityThread.java:1367)
at os.android.Handler.dispatchMessage(Handler.java:102)
at os.android.Looper.loop(Looper.java:135)
at app.android.ActivityThread.main(ActivityThread.java:5348)
at reflect.lang.java.Method.invoke(Native Method)
at reflect.lang.java.Method.invoke(Method.java:372)
at os.internal.android.com.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:947)
at os.internal.android.com.ZygoteInit.main(ZygoteInit.java:742)

Показывает что ошибка происходит в методе onDestroy. Но мой onDestroy выглядит так:

@Override
protected void onDestroy() {
    super.onDestroy();
    stopService(new Intent(this,PlayerService.class));
}

Код всей Activity:

public class MainActivity extends AppCompatActivity implements MaterialTabListener {
    private ViewPager pager;
    private ViewPagerAdapter pagerAdapter;
    MaterialTabHost tabHost;
    Toolbar toolbar;
    ArrayList<Integer>   fragmentsInToolbar;
    ArrayList<Drawable>   tabsDrawable;
    ArrayList<String>     tabsInToolbarTitle;
    private AdView mAdView;
    ArrayList<String>     fragmentsNameInNavigationDrawer;
    ArrayList<Drawable>   iconsInNavigationDrawer;

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        toolbar = (Toolbar) this.findViewById(R.id.toolbar);
        toolbar.setTitleTextColor(Color.WHITE);

        this.setSupportActionBar(toolbar);
        fragmentsInToolbar = new ArrayList<>();
        tabsDrawable  = new ArrayList<>();
        tabsInToolbarTitle = new ArrayList<>();
        iconsInNavigationDrawer = new ArrayList<>();
        fragmentsNameInNavigationDrawer = new ArrayList<>();
        startService(new Intent(this,PlayerService.class).putExtra(StaticValues.isAutoStartTag,false));
        fragmentsInToolbar.add(StaticValues.TAG_TAB_STREAM);   //Добавляем главный фрагмент.
        tabsDrawable.add(getResources().getDrawable(R.drawable.efir_white));
        tabsInToolbarTitle.add(getResources().getString(R.string.efir_tab_name));
        getSupportActionBar().setTitle(tabsInToolbarTitle.get(0));

        Glide.with(this).load(getResources().getIdentifier(ConfigClass.AppName+"_bg", "drawable", getPackageName()))
                .diskCacheStrategy(DiskCacheStrategy.RESULT).into(new SimpleTarget<GlideDrawable>() {
            @Override
            public void onResourceReady(GlideDrawable resource, GlideAnimation<? super GlideDrawable> glideAnimation) {
                findViewById(R.id.root_layout_main).setBackground(resource);
            }
        });
        if(ConfigClass.isNews) {
            if (ConfigClass.isNewsInToolbar) {
                fragmentsInToolbar.add(StaticValues.TAG_TAB_NEWS);
                tabsDrawable.add(getResources().getDrawable(R.drawable.news_white));
                tabsInToolbarTitle.add(getResources().getString(R.string.news_tab_name));
            }else {
                fragmentsNameInNavigationDrawer.add(getResources().getString(R.string.news_tab_name));
                iconsInNavigationDrawer.add(getResources().getDrawable(R.drawable.news_black));
            }

        }
        if(ConfigClass.isNovelties){
            if(ConfigClass.isNoveltiesInToolbar){
                fragmentsInToolbar.add(StaticValues.TAG_TAB_NOVELTIES);
                tabsDrawable.add(getResources().getDrawable(R.drawable.novatels_white));
                tabsInToolbarTitle.add(getResources().getString(R.string.novelties_tab_name));
            }else {
                fragmentsNameInNavigationDrawer.add(getResources().getString(R.string.novelties_tab_name));
                iconsInNavigationDrawer.add(getResources().getDrawable(R.drawable.novatels_black));
            }
        }
        if(ConfigClass.isProgramms){
            if(ConfigClass.isProgrammsInToolbar){
                fragmentsInToolbar.add(StaticValues.TAG_TAB_PROGRAMMS);
                tabsDrawable.add(getResources().getDrawable(R.drawable.programs_white));
                tabsInToolbarTitle.add(getResources().getString(R.string.programms_tab_name));
            }else {
                fragmentsNameInNavigationDrawer.add(getResources().getString(R.string.programms_tab_name));
                iconsInNavigationDrawer.add(getResources().getDrawable(R.drawable.programs_black));
            }
        }

        if(ConfigClass.isAction) {
            if (ConfigClass.isActionInToolbar) {
                fragmentsInToolbar.add(StaticValues.TAG_TAB_ACTIONS);
                tabsDrawable.add(getResources().getDrawable(R.drawable.action_white));
                tabsInToolbarTitle.add(getResources().getString(R.string.action_tab_name));
            }else {
                fragmentsNameInNavigationDrawer.add(getResources().getString(R.string.action_tab_name));
                iconsInNavigationDrawer.add(getResources().getDrawable(R.drawable.action_black));
            }
        }
        if(ConfigClass.isAlarm) {
            if (ConfigClass.isAlarmInToolbar) {
                fragmentsInToolbar.add(StaticValues.TAG_TAB_ALARM);
                tabsDrawable.add(getResources().getDrawable(R.drawable.alarm_white));
                tabsInToolbarTitle.add(getResources().getString(R.string.alarm_tab_name));
            }else {
                fragmentsNameInNavigationDrawer.add(getResources().getString(R.string.alarm_tab_name));
                iconsInNavigationDrawer.add(getResources().getDrawable(R.drawable.alarm_black));
            }
        }
        if(ConfigClass.isWhatIsSong) {
            if (ConfigClass.isWhatIsSongInToolbar) {
                fragmentsInToolbar.add(StaticValues.TAG_TAB_WHATISSONG);
                tabsDrawable.add(getResources().getDrawable(R.drawable.whatissong_white));
                tabsInToolbarTitle.add(getResources().getString(R.string.whatIsSong_tab_name));
            }else {
                fragmentsNameInNavigationDrawer.add(getResources().getString(R.string.whatIsSong_tab_name));
                iconsInNavigationDrawer.add(getResources().getDrawable(R.drawable.whatissong_black));
            }
        }
        if(ConfigClass.isChart) {
            if (ConfigClass.isChartInToolbar) {
                fragmentsInToolbar.add(StaticValues.TAG_TAB_CHART);
                tabsDrawable.add(getResources().getDrawable(R.drawable.chart_white));
                tabsInToolbarTitle.add(getResources().getString(R.string.chart_tab_name));
            }else {
                fragmentsNameInNavigationDrawer.add(getResources().getString(R.string.chart_tab_name));
                iconsInNavigationDrawer.add(getResources().getDrawable(R.drawable.ic_queue_music_black_24dp));
            }
        }
        setUpNavigationDrawer();

        tabHost = (MaterialTabHost) this.findViewById(R.id.tabHost);
        pager = (ViewPager) this.findViewById(R.id.pager);
        pagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
        pager.setAdapter(pagerAdapter);
        pager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                // when user do a swipe the selected tab change
                tabHost.setSelectedNavigationItem(position);
                getSupportActionBar().setTitle(tabsInToolbarTitle.get(position));
            }
        });
        // insert all tabs from pagerAdapter data
        for (int i = 0; i < pagerAdapter.getCount(); i++) {
            tabHost.addTab(
                    tabHost.newTab()
                            .setIcon(getIcon(i))
                            .setTabListener(this)
            );
        }
        mAdView = new AdView(this);
        mAdView.setAdSize(AdSize.BANNER);
        mAdView.setAdUnitId(ConfigClass.bannerScreenAdMob);
        AdRequest adRequest = new AdRequest.Builder()
                .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
                .build();
        mAdView.loadAd(adRequest);
        ((LinearLayout)findViewById(R.id.adView)).addView(mAdView);

    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
    }
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        int item = pager.getCurrentItem();
        // Проверяем ориентацию экрана
        pagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
        pager.setAdapter(pagerAdapter);
        pager.setCurrentItem(item);
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
        } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR);
        }
    }
    @Override
    public void onTabSelected(MaterialTab tab) {
        pager.setCurrentItem(tab.getPosition());
        /*tab.*/
    }
    @Override
    public void onTabReselected(MaterialTab tab) {
    }
    @Override
    public void onTabUnselected(MaterialTab tab) {
    }
    private class ViewPagerAdapter extends FragmentStatePagerAdapter {
        public ViewPagerAdapter(FragmentManager fm) {
            super(fm);
        }
        @Override
        public void restoreState(Parcelable state, ClassLoader loader) {
            try{
                super.restoreState(state, loader);
            }catch (NullPointerException e){
            }
        }
        public Fragment getItem(int num) {
            switch (fragmentsInToolbar.get(num)) {
                case StaticValues.TAG_TAB_STREAM:
                    return StreamFragment.getInstance();
                case StaticValues.TAG_TAB_NEWS:
                    return NewsFragment.getInstance();
                case StaticValues.TAG_TAB_NOVELTIES:
                    return NoveltiesFragment.getInstanse();
                case StaticValues.TAG_TAB_PROGRAMMS:
                    return ProgrammsFragment.getInstanse();
                case StaticValues.TAG_TAB_ACTIONS:
                    return ActionFragment.getInstance();
                case StaticValues.TAG_TAB_ALARM:
                    return AlarmClockFragment.getInstance();
                case StaticValues.TAG_TAB_WHATISSONG:
                    return WhatIsSongFragment.getInstanse();
                case StaticValues.TAG_TAB_CHART:
                    return ChartFragment.getInstanse();
                default:
                    return null;
            }
        }

        @Override
        public int getCount() {
            return fragmentsInToolbar.size();
        }
        @Override
        public CharSequence getPageTitle(int position) {
            return "tab";
        }
    }
    /*
    * It doesn't matter the color of the icons, but they must have solid colors
    */
    private Drawable getIcon(int position) {
        return tabsDrawable.get(position);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopService(new Intent(this,PlayerService.class));
    }

    private long mLastPressed;
    @Override
    public void onBackPressed() {
        long currentTime = System.currentTimeMillis();
        if (currentTime - mLastPressed > 2000) {
            Toast.makeText(this,
                    "Нажмите кнопку Назад еще раз, чтобы выйти",
                    Toast.LENGTH_SHORT).show();
            mLastPressed = currentTime;
        } else {
            super.onBackPressed();
        }
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if(id == R.id.contact_Activity){
            Intent intent = new Intent(this,UniversalActivity.class);
            intent.putExtra(StaticValues.FRAGMENT_TAG, getResources().getString(R.string.contact_tab_name));
            startActivity(intent);
        }
        if(id == R.id.about_company) {
            Intent intent = new Intent(this,UniversalActivity.class);
            intent.putExtra(StaticValues.FRAGMENT_TAG, getResources().getString(R.string.tab_about_company));
            startActivity(intent);
        }

        return super.onOptionsItemSelected(item);
    }
    private void setUpNavigationDrawer(){
        if( fragmentsNameInNavigationDrawer.size() == 0){
            return;
        }
        final Drawer result = new DrawerBuilder()
                .withActivity(this)
                .withToolbar(toolbar)
                .withHeader(R.layout.header_navigation_drawer)
                .build();

        ImageView header = (ImageView)result.getHeader().findViewById(R.id.header_navigation_drawer);
        if(ConfigClass.AppName.equals("avtoradio")){
            Glide.with(this).load(R.drawable.avtoradio_header).diskCacheStrategy(DiskCacheStrategy.RESULT).skipMemoryCache(true).into(header);
        }
        if(ConfigClass.AppName.equals("relaxfm")){
            Glide.with(this).load(R.drawable.relaxfm_header).diskCacheStrategy(DiskCacheStrategy.RESULT).skipMemoryCache(true).into(header);
        }
        if(ConfigClass.AppName.equals("humor")){
            Glide.with(this).load(R.drawable.humor_header).diskCacheStrategy(DiskCacheStrategy.RESULT).skipMemoryCache(true).into(header);
        }
        if(ConfigClass.AppName.equals("comedy")){
            Glide.with(this).load(R.drawable.comedy_header).diskCacheStrategy(DiskCacheStrategy.RESULT).skipMemoryCache(true).into(header);
        }
        if(ConfigClass.AppName.equals("energy")){
            Glide.with(this).load(R.drawable.energy_header).diskCacheStrategy(DiskCacheStrategy.RESULT).skipMemoryCache(true).into(header);
        }
        if(ConfigClass.AppName.equals("romantika")){
            Glide.with(this).load(R.drawable.romantika_header).diskCacheStrategy(DiskCacheStrategy.RESULT).skipMemoryCache(true).into(header);
        }
        for(int i = 0; i< fragmentsNameInNavigationDrawer.size();i++){
            result.addItem(new PrimaryDrawerItem().withName( fragmentsNameInNavigationDrawer.get(i))
                    .withIcon(iconsInNavigationDrawer.get(i)).withTag( fragmentsNameInNavigationDrawer.get(i))
                    .withSelectedColor(getResources().getColor(R.color.white))
                    .withSelectedTextColorRes(R.color.black)
            );
            result.addItem(new DividerDrawerItem());
        }
        result.setOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {
            @Override
            public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {

                Intent intent = new Intent(getApplicationContext(),UniversalActivity.class);
                if(result.isDrawerOpen()){
                    result.closeDrawer();
                }
                if(drawerItem.getTag().toString().equals(getResources().getString(R.string.action_tab_name))){
                    intent.putExtra(StaticValues.FRAGMENT_TAG, getResources().getString(R.string.action_tab_name ));
                }
                if(drawerItem.getTag().toString().equals(getResources().getString(R.string.alarm_tab_name))){
                    intent.putExtra(StaticValues.FRAGMENT_TAG, getResources().getString(R.string.alarm_tab_name ));
                }
                if(drawerItem.getTag().toString().equals(getResources().getString(R.string.chart_tab_name))){
                    intent.putExtra(StaticValues.FRAGMENT_TAG, getResources().getString(R.string.chart_tab_name));
                }
                if(drawerItem.getTag().toString().equals(getResources().getString(R.string.contact_tab_name))){
                    intent.putExtra(StaticValues.FRAGMENT_TAG, getResources().getString(R.string.contact_tab_name));
                }
                if(drawerItem.getTag().toString().equals(getResources().getString(R.string.news_tab_name))){
                    intent.putExtra(StaticValues.FRAGMENT_TAG, getResources().getString(R.string.news_tab_name));
                }
                if(drawerItem.getTag().toString().equals(getResources().getString(R.string.programms_tab_name))){
                    intent.putExtra(StaticValues.FRAGMENT_TAG, getResources().getString(R.string.programms_tab_name));
                }
                if(drawerItem.getTag().toString().equals(getResources().getString(R.string.whatIsSong_tab_name))){
                    intent.putExtra(StaticValues.FRAGMENT_TAG, getResources().getString(R.string.whatIsSong_tab_name));
                }
                startActivity(intent);
                return true;
            }
        });
    }
}
READ ALSO
Как написать правила для proguard?

Как написать правила для proguard?

Мне нужно было сделать имплементация proguard в проекте как было до

368
Не скрывается блок в bootstrap (hidden-md hidden-lg)

Не скрывается блок в bootstrap (hidden-md hidden-lg)

Есть блок с 4 элементами в сетке bootstrap которые отличаются по содержанию, а значит и по высотеФидл

355
Разместить div в конце строки (обтекание)

Разместить div в конце строки (обтекание)

Как разместить div в конце последней строки текста произвольной длины?

287
Можно ли совместить html и картинки в один файл?

Можно ли совместить html и картинки в один файл?

У меня есть html документ, который содержит примерно 20 картинокВсе эти файлы лежат в одной папке

448