java.lang.ClassCastException:MainActivity无法强制转换?

时间:2018-11-15 23:02:51

标签: java android

这是完整的日志

11-16 04:13:35.810 3555-3555/? E/AndroidRuntime: FATAL EXCEPTION: main
                                                 Process: com.steven.test, PID: 3555
                                                 java.lang.ClassCastException: com.steven.test.MainActivity cannot be cast to com.steven.test.providers.priceticker.currencylist.AllCurrencyListFragment$FavoritesListUpdater
                                                     at com.steven.test.providers.priceticker.currencylist.AllCurrencyListFragment.onAttach(AllCurrencyListFragment.java:182)
                                                     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1372)
                                                     at android.support.v4.app.FragmentTransition.addToFirstInLastOut(FragmentTransition.java:1188)
                                                     at android.support.v4.app.FragmentTransition.calculateFragments(FragmentTransition.java:1071)
                                                     at android.support.v4.app.FragmentTransition.startTransitions(FragmentTransition.java:115)
                                                     at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2380)
                                                     at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2338)
                                                     at android.support.v4.app.FragmentManagerImpl.execSingleAction(FragmentManager.java:2215)
                                                     at android.support.v4.app.BackStackRecord.commitNowAllowingStateLoss(BackStackRecord.java:649)
                                                     at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:145)
                                                     at android.support.v4.view.ViewPager.populate(ViewPager.java:1238)
                                                     at android.support.v4.view.ViewPager.populate(ViewPager.java:1086)
                                                     at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1616)
                                                     at android.view.View.measure(View.java:22091)
                                                     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6602)
                                                     at android.support.design.widget.CoordinatorLayout.onMeasureChild(CoordinatorLayout.java:739)
                                                     at android.support.design.widget.HeaderScrollingViewBehavior.onMeasureChild(HeaderScrollingViewBehavior.java:91)
                                                     at android.support.design.widget.AppBarLayout$ScrollingViewBehavior.onMeasureChild(AppBarLayout.java:1361)
                                                     at android.support.design.widget.CoordinatorLayout.onMeasure(CoordinatorLayout.java:809)
                                                     at android.view.View.measure(View.java:22091)
                                                     at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1632)
                                                     at com.duolingo.open.rtlviewpager.RtlViewPager.onMeasure(RtlViewPager.java:211)
                                                     at android.view.View.measure(View.java:22091)
                                                     at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:715)
                                                     at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:461)
                                                     at android.view.View.measure(View.java:22091)
                                                     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6602)
                                                     at android.support.design.widget.CoordinatorLayout.onMeasureChild(CoordinatorLayout.java:739)
                                                     at android.support.design.widget.HeaderScrollingViewBehavior.onMeasureChild(HeaderScrollingViewBehavior.java:91)
                                                     at android.support.design.widget.AppBarLayout$ScrollingViewBehavior.onMeasureChild(AppBarLayout.java:1361)
                                                     at android.support.design.widget.CoordinatorLayout.onMeasure(CoordinatorLayout.java:809)
                                                     at android.view.View.measure(View.java:22091)
                                                     at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:715)
                                                     at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:461)
                                                     at android.view.View.measure(View.java:22091)
                                                     at android.support.v4.widget.DrawerLayout.onMeasure(DrawerLayout.java:1059)
                                                     at android.view.View.measure(View.java:22091)
                                                     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6602)
                                                     at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
                                                     at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:141)
                                                     at android.view.View.measure(View.java:22091)
                                                     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6602)
                                                     at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
                                                     at android.view.View.measure(View.java:22091)
                                                     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6602)
                                                     at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
                                                     at android.view.View.measure(View.java:22091)
                                                     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6602)
11-16 04:13:35.811 3555-3555/? E/AndroidRuntime:     at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1514)
                                                     at android.widget.LinearLayout.measureVertical(LinearLayout.java:806)
                                                     at android.widget.LinearLayout.onMeasure(LinearLayout.java:685)
                                                     at android.view.View.measure(View.java:22091)
                                                     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6602)
                                                     at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
                                                     at com.android.internal.policy.DecorView.onMeasure(DecorView.java:725)
                                                     at android.view.View.measure(View.java:22091)
                                                     at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2447)
                                                     at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1529)
                                                     at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1786)
                                                     at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1417)
                                                     at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6934)
                                                     at android.view.Choreographer$CallbackRecord.run(Choreographer.java:979)
                                                     at android.view.Choreographer.doCallbacks(Choreographer.java:791)
                                                     at android.view.Choreographer.doFrame(Choreographer.java:726)
                                                     at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:965)
                                                     at android.os.Handler.handleCallback(Handler.java:790)
                                                     at android.os.Handler.dispatchMessage(Handler.java:99)
                                                     at android.os.Looper.loop(Looper.java:164)
                                                     at android.app.ActivityThread.main(ActivityThread.java:6578)
                                                     at java.lang.reflect.Method.invoke(Native Method)
                                                     at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:460)
                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)

这是我的活动:

开始并传递到另一个片段的片段-

public class CurrencyListTabsFragment extends Fragment implements ViewPager.OnPageChangeListener,
        FavoriteCurrencyListFragment.AllCoinsListUpdater, AllCurrencyListFragment.FavoritesListUpdater {

    private SectionsPagerAdapterCurrencyList mSectionsPagerAdapter;
    private View rootView;
    public ViewPager mViewPager;
    public static String baseImageURL = "";
    public static String SYMBOL = "SYMBOL";
    private Toolbar mToolbar;
    public final static String DAY = "24h";
    public final static String WEEK = "7d";
    public final static String HOUR = "1h";
    public final static String SORT_SETTING = "sort_setting";
    public Fragment context;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.activity_currency_list_tabs, container, false);
        context = this;
        mToolbar = rootView.findViewById(R.id.toolbar_currency_list);
        ((AppCompatActivity)getActivity()).setSupportActionBar(mToolbar);
        TabLayout tabLayout = rootView.findViewById(R.id.currency_list_tabs);
        mViewPager = rootView.findViewById(R.id.currency_list_tabs_container);

        mSectionsPagerAdapter = new SectionsPagerAdapterCurrencyList(getActivity().getSupportFragmentManager());
        mViewPager.setAdapter(mSectionsPagerAdapter);
        mViewPager.setOffscreenPageLimit(2);
        mViewPager.addOnPageChangeListener(this);

        tabLayout.setupWithViewPager(mViewPager);
        tabLayout.setSelectedTabIndicatorColor(Color.WHITE);

        return rootView;
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {

        Fragment fragment = mSectionsPagerAdapter.getFragment(position);
        if (fragment != null) {
            fragment.onResume();
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    public void removeFavorite(CMCCoin coin) {
        FavoriteCurrencyListFragment frag = (FavoriteCurrencyListFragment) mSectionsPagerAdapter.getFragment(1);
        if (frag != null) {
            frag.removeFavorite(coin);
        }
    }

    public void addFavorite(CMCCoin coin) {
        FavoriteCurrencyListFragment frag = (FavoriteCurrencyListFragment) mSectionsPagerAdapter.getFragment(1);
        if (frag != null) {
            frag.addFavorite(coin);
        }
    }

    public void allCoinsModifyFavorites(CMCCoin coin) {
        AllCurrencyListFragment frag = (AllCurrencyListFragment) mSectionsPagerAdapter.getFragment(0);
        if (frag != null) {
            frag.getAdapter().notifyDataSetChanged();
        }
    }

    public void performFavsSort() {
        FavoriteCurrencyListFragment frag = (FavoriteCurrencyListFragment) mSectionsPagerAdapter.getFragment(1);
        if (frag != null) {
            frag.performFavsSort();
        }
    }

    public void performAllCoinsSort() {
        AllCurrencyListFragment frag = (AllCurrencyListFragment) mSectionsPagerAdapter.getFragment(0);
        if (frag != null) {
            frag.performAllCoinsSort();
        }
    }

}

这是在“ onAttach”方法中引发错误的片段

public class AllCurrencyListFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener,
        SearchView.OnQueryTextListener {

    private SwipeRefreshLayout swipeRefreshLayout;
    private RecyclerView currencyRecyclerView;
    private AllCurrencyListAdapter adapter;
    private ArrayList<CMCCoin> currencyItemList;
    private ArrayList<CMCCoin> filteredList = new ArrayList<>();
    private MenuItem searchItem;
    private SearchView searchView;
    private View rootView;
    private Context mContext;
    public static String currQuery = "";
    ArrayList<CMCCoin> searchList;
    private HashMap<String, String> searchedSymbols = new HashMap<>();
    private HashMap<String, Integer> slugToIDMap = new HashMap<>();
    public static boolean searchViewFocused = false;
    private FavoritesListUpdater favsUpdateCallback;
    private SharedPreferences sharedPreferences;

    public interface FavoritesListUpdater {
        void removeFavorite(CMCCoin coin);
        void addFavorite(CMCCoin coin);
        void performFavsSort();
    }

    public AllCurrencyListFragment() {
    }

    public void performAllCoinsSort() {
        int sortType = sharedPreferences.getInt(SORT_SETTING, 1);
        sortList(adapter.getCurrencyList(), sortType);
        adapter.notifyDataSetChanged();
    }

    public void getQuickSearch() {
        CoinMarketCapService.getCMCQuickSearch(mContext, new afterTaskCompletion<CMCQuickSearch[]>() {
            @Override
            public void onTaskCompleted(CMCQuickSearch[] quickSearchNodeList) {
                slugToIDMap = new HashMap<>();
                Parcelable recyclerViewState;
                recyclerViewState = currencyRecyclerView.getLayoutManager().onSaveInstanceState();
                for (CMCQuickSearch node : quickSearchNodeList) {
                    slugToIDMap.put(node.getSlug(), node.getId());
                }
                if (searchViewFocused) {
                    for (CMCCoin coin: searchList) {
                        if (slugToIDMap.get(coin.getId()) != null) {
                            coin.setQuickSearchID(slugToIDMap.get(coin.getId()));
                        }
                    }
                    adapter.setCurrencyList(searchList);
                } else {
                    for (CMCCoin coin : currencyItemList) {
                        if (coin.getId() != null && slugToIDMap.get(coin.getId()) != null) {
                            coin.setQuickSearchID(slugToIDMap.get(coin.getId()));
                        }
                    }
                    adapter.setCurrencyList(currencyItemList);
                }
                int sortType = sharedPreferences.getInt(SORT_SETTING, 1);
                sortList(adapter.getCurrencyList(), sortType);
                adapter.notifyDataSetChanged();
                favsUpdateCallback.performFavsSort();
                currencyRecyclerView.getLayoutManager().onRestoreInstanceState(recyclerViewState);
                swipeRefreshLayout.setRefreshing(false);
            }
        }, new afterTaskFailure() {
            @Override
            public void onTaskFailed(Object o, Exception e) {
                Log.e("ERROR", "Server Error: " + e.getMessage());
                swipeRefreshLayout.setRefreshing(false);
            }
        }, true);
    }

    @Override
    public void onRefresh() {
        getCurrencyList();
    }

    public static AllCurrencyListFragment newInstance() {
        return new AllCurrencyListFragment();
    }

    public void getCurrencyList() {
        swipeRefreshLayout.setRefreshing(true);
        CoinMarketCapService.getAllCoins(mContext, new afterTaskCompletion<CMCCoin[]>() {
            @Override
            public void onTaskCompleted(CMCCoin[] cmcCoinList) {
                try {
                    if (searchViewFocused) { // Copy some code here to make the checks faster
                        searchedSymbols.clear();
                        searchList.clear();
                        for (CMCCoin coin : filteredList) {
                            searchedSymbols.put(coin.getSymbol(), coin.getSymbol());
                        }
                        for (CMCCoin coin : cmcCoinList) {
                            if (searchedSymbols.get(coin.getSymbol()) != null) {
                                searchList.add(coin);
                            }
                        }
                    } else {
                        currencyItemList.clear();
                        currencyItemList.addAll(Arrays.asList(cmcCoinList));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                getQuickSearch();
            }
        }, new afterTaskFailure() {
            @Override
            public void onTaskFailed(Object o, Exception e) {
                Log.e("ERROR", "Server Error: " + e.getMessage());
                swipeRefreshLayout.setRefreshing(false);
            }
        }, true);
    }

    @Override
    public void onResume() {
        super.onResume();
        getActivity().invalidateOptionsMenu();
    }

    @Override
    public void onAttach(Context context) {
        this.mContext = context;
        this.favsUpdateCallback = (FavoritesListUpdater) context;
        super.onAttach(context);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_all_currency_list, container, false);
        setHasOptionsMenu(true);
        DatabaseHelperSingleton db = DatabaseHelperSingleton.getInstance(mContext);
        sharedPreferences = getContext().getSharedPreferences(SHAREDPREF_SETTINGS, MODE_PRIVATE);
        searchList = new ArrayList<>();
        // Setup currency list
        currencyRecyclerView = rootView.findViewById(R.id.currency_list_recycler_view);
        HorizontalDividerItemDecoration divider = new HorizontalDividerItemDecoration.Builder(mContext).build();
        currencyRecyclerView.addItemDecoration(divider);
        LinearLayoutManager llm = new LinearLayoutManager(mContext);
        llm.setOrientation(LinearLayoutManager.VERTICAL);
        currencyRecyclerView.setLayoutManager(llm);
        currencyItemList = new ArrayList<>();
        adapter = new AllCurrencyListAdapter(favsUpdateCallback, currencyItemList, db, (AppCompatActivity) mContext, new CustomItemClickListener() {
            @Override
            public void onItemClick(int position, View v) {
                Intent intent = new Intent(mContext, CurrencyDetailsTabsActivity.class);
                intent.putExtra(GraphFragment.ARG_SYMBOL, adapter.getCurrencyList().get(position).getSymbol());
                intent.putExtra(GraphFragment.ARG_ID, adapter.getCurrencyList().get(position).getId());
                intent.putExtra(GraphFragment.COIN_OBJECT, adapter.getCurrencyList().get(position));
                mContext.startActivity(intent);
            }
        });
        currencyRecyclerView.setAdapter(adapter);
        // Setup swipe refresh layout
        swipeRefreshLayout = rootView.findViewById(R.id.currency_list_swipe_refresh);
        swipeRefreshLayout.setColorSchemeResources(R.color.myAccentColor);
        swipeRefreshLayout.setOnRefreshListener(this);
        swipeRefreshLayout.post(new Runnable() {
            @Override
            public void run() {
                swipeRefreshLayout.setRefreshing(true);
                getCurrencyList();
            }
        });
        return rootView;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch(item.getItemId()) {
            case R.id.sort_button:
                int sortType = sharedPreferences.getInt(SORT_SETTING, 1);
                new MaterialDialog.Builder(getActivity())
                        .title(R.string.sort_by)
                        .items(R.array.sort_options)
                        .dividerColorRes(R.color.myPrimaryColor)
                        .widgetColorRes(R.color.myPrimaryColor)
                        .buttonRippleColorRes(R.color.myPrimaryColor)
                        .itemsCallbackSingleChoice(sortType, new MaterialDialog.ListCallbackSingleChoice() {
                            @Override
                            public boolean onSelection(MaterialDialog dialog, View view, int which, CharSequence text) {
                                sortList(adapter.getCurrencyList(), which);
                                adapter.notifyDataSetChanged();
                                SharedPreferences.Editor editor = sharedPreferences.edit();
                                editor.putInt(SORT_SETTING, which);
                                editor.apply();
                                favsUpdateCallback.performFavsSort();
                                Toast toast = Toast.makeText(getContext(), "Sorting by: " + text, Toast.LENGTH_SHORT);
                                toast.show();
                                return true;
                            }
                        })
                        .show();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    @Override
    public boolean onQueryTextSubmit(String query) {
        return false;
    }

    @Override
    public boolean onQueryTextChange(String query) {
        currQuery = query;
        query = query.toLowerCase();
        filteredList.clear();
        for (CMCCoin coin : currencyItemList) {
            if (coin.getSymbol().toLowerCase().contains(query) || coin.getName().toLowerCase().contains(query)) {
                filteredList.add(coin);
            }
        }
        adapter.setCurrencyList(filteredList);
        return true;
    }

    private void showInputMethod(View view) {
        InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.showSoftInput(view, 0);
        }
    }

    @Override
    public void onPrepareOptionsMenu(Menu menu) {
        if (searchView != null && searchViewFocused) {
            ((AppCompatActivity)mContext).getSupportActionBar().setTitle("");
            searchView.requestFocusFromTouch();
            searchView.setIconified(false);
            searchView.setIconified(false);
            searchView.setQuery(currQuery, false);
            showInputMethod(rootView);
        }
    }


    @Override
    public void onCreateOptionsMenu(final Menu menu, MenuInflater inflater) {
        getActivity().getMenuInflater().inflate(R.menu.all_currency_list_tab_menu, menu);
        searchItem = menu.findItem(R.id.action_search);
        searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
        searchView.setOnQueryTextListener(this);
        // Detect SearchView icon clicks
        searchView.setOnSearchClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                searchViewFocused = true;
                setItemsVisibility(menu, searchItem, false);
            }
        });
        // Detect SearchView close
        searchView.setOnCloseListener(new SearchView.OnCloseListener() {
            @Override
            public boolean onClose() {
                searchViewFocused = false;
                setItemsVisibility(menu, searchItem, true);
                return false;
            }
        });
        if (searchViewFocused) ((AppCompatActivity)mContext).getSupportActionBar().setTitle("");
        super.onCreateOptionsMenu(menu, inflater);
    }

    private void setItemsVisibility(Menu menu, MenuItem exception, boolean visible) {
        for (int i = 0; i < menu.size(); ++i) {
            MenuItem item = menu.getItem(i);
            if (item != exception) item.setVisible(visible);
        }
        if (!visible) {
            ((AppCompatActivity)mContext).getSupportActionBar().setTitle("");
        } else {
            ((AppCompatActivity)mContext).getSupportActionBar().setTitle(getResources().getString(R.string.app_name));
        }
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        searchViewFocused = false;
    }

    public AllCurrencyListAdapter getAdapter() {
        return this.adapter;
    }
}

我试图四处寻找答案,但是甚至找不到一个,并且由于无法解决,此错误使我感到压力!当我尝试启动此片段时,应用程序崩溃。会提供任何帮助。

3 个答案:

答案 0 :(得分:0)

public void onAttach(Context context)中,传入的上下文似乎是com.steven.test.MainActivity类型,在您看来与com.steven.test.providers.priceticker.currencylist.AllCurrencyListFragment $ FavoritesListUpdate不兼容尝试将其投放到这里:

 this.favsUpdateCallback = (FavoritesListUpdater) context;

答案 1 :(得分:0)

我不知道你要做什么。

在您的代码中,您尝试投射

FavoritesListUpdater 

Context

,这就是导致错误的原因。  我认为您想将上下文强制转换为MainActivity吗?

    this.favsUpdateCallback = ((MainActivity) getActivity()).favsUpdateCallback ;

你想那样做吗?

答案 2 :(得分:0)

您需要拥有MainActivity ... implements AllCurrencyListFragment.FavoritesListUpdater

该片段将附着到一个活动,因此,at com.steven.test.providers.priceticker.currencylist.AllCurrencyListFragment.onAttach(AllCurrencyListFragment.java:182)(您用来加载此片段的Activity)必须实现该接口。

此外,Fragment不是Context对象的扩展

  

这是我的活动

您显示了两个片段...