ClassCastException将RecyclerView添加到ViewPager

时间:2016-04-07 15:40:43

标签: java android android-fragments android-viewpager android-recyclerview

我正在创建一个应用程序,列出2天功能的不同事件。我打算在ViewPager中显示两天的事件,每个事件包含一个RecyclerView。

我的代码收到了ClassCastException。有人可以建议一个可能的解决办法吗?

以下是文件: -

Day1EventFragment.java

package com.execube.volantis.views;

import android.content.Intent;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.execube.volantis.R;
import com.execube.volantis.model.Events;

import java.util.ArrayList;

import xyz.hanks.library.SmallBang;

/**
 * Created by Prateek Phoenix on 4/4/2016.
 */
public class Day1EventFragment extends Fragment {

    private static String day1events[]={"Vocal light music group","Movie clip recreation", "Battle of bands", "Western Group Dance",
            "Indian Group Dance", "RAMP", "Techcharades","Karaoke","Web designing","Online treasure hunt", "Rangoli", "On spot photography"
            , "Slow drag", "Kannada dumb charades","Kannada anthyakshari", "Gaanchaali bidi kannada maathaadi",
            "Vocal classical music solo prelims", "Vocal light music solo Prelims", "Antichess", "Mini Militia", "FIFA", "Counterstrike"};



    private  static  String[] day1description ={ "6 in team. Max 2 entries per college. Karaoke allowed. Filmic and non-filmic allowed. Original composition allowed",
            "6 in team. 2-minute video clip will be provided. 5+2 minute is given to recreate. Most comic scene will be rewarded. No vulgarity",
            "3-10 in a team. 15+5 minutes (including setup) is given. No restriction on genre. 5-piece drum kit, mics, cable and amplifier will be provided",
            "6+6 in a team. 5+2 minutes is given. Carry ID card. Report 2 hours prior to event",
            "8+4 in a team. 5+3 minutes is given. Any theme is allowed. Report 2 hours prior to the event. Should submit a video of their prior performances",
            "Open theme. 12+2 in a team. 6+2 minutes is given. Report 3 hours before event. Carry ID cards. Audio track to be given 1 hour in prior. No use of water, fire, pet, animal skin….",
            "3 in team. Tech version of dumb charades. 1 member mimes other 2 guesses. Multiple rounds",
            "Solo event. Western instruments to be used.  5+1 minute is given. 2 rounds. 6 contestants will be shortlisted to 2nd round",
            "2 in team. 3-hour time is given. Systems will be provided",
            "2 in team. First round is written. Second round is on computer. Google imaging NOT allowed",
            "Individual event. 1 hour is given. Colors and rangoli powder will be provided",
            "Individual event. Topic is given on-spot. 2-hour time is given. Photos to be taken at RNSIT. On board editing allowed (Photoshop/post-processing not allowed)",
            "Carry your own bikes (boys) and scooty (girls). Last one reaching the line wins. Multiple rounds",
            "3 in team. Standard dumb charades rules apply. No speaking. 1 will mime other 2 guess",
            "Team of 2 members wherein the prelims will be written round. Top scoring teams will be selected for finals. Coordinator's decision is final",
            "It's a solo event where the topic will be given on the spot. 5 min preparation time. Speak in Kannada for 2 min but the timer stops as soon as you omit a Non-Kannada word. Judge's decision is final",
            "Solo event. Time limit of 2+1 min. Any form of Hindustani or Carnatic classical music. No karaoke. 15 singers shall move on to the 2nd round",
            "Solo event.  Time limit of 2+1 min. No karaoke. Indian or non-filmic song can be sung. No Western music. Top 15 singers shall move on to second round. Indian filmic or non-filmic songs can be sung",
            "Solo event wherein standard rules of anti-chess apply. Matches are knockout. Time limit may or may not be present, depending on the event coordinator",
            "Team consisting of 4 members. Match duration is 7 min. Team with maximum wins after allotted time will proceed. It will be direct elimination. Unlimited entries for the event",
            "Solo event with difficulty level being legendary, 4mins per half. Elimination based on number of goals scored per team. Penalty shootout in case of a draw. No time will be allotted for practicing. Gamers can get their own joysticks and keyboards",
            "Team of 5 members. Round will be a race to 5 wins in the 1000$ map. Direct elimination. Consequent rounds will be on de_dust2, de_train and de_inferno. No practice session. Gamers can get their own Mouse or joystick"};



    //UPDATE THE TIMINGS TO THE CURRENT 24 HOUR FORMAT
    private static String timings[]={"09:00","09:00","09:00","09:00",
            "10:00","10:00","10:00","10:00",
            "10:00","10:00","10:00","11:00",
            "11:00","11:00","11:00","13:00",
            "13:00","14:00","14:00","14:00",
            "16:30","19:30"};

    private String day1venue[]={"Main stage", "Main stage", "Main stage”", "Main stage",
            "Main stage", "Main stage", "Edusat hall", "Edusat hall",
            "EEE lab", "Mech Lab", "Street", "Street", "Street",
            "CS/IS block", "CS/IS block", "CS/IS block", "EC blk lvl1",
            "EC blk lvl1", "MCA/CS/IS lab", "MCA/CS/IS lab", "MCA/CS/IS lab", "MCA/CS/IS lab"};


    private String[] day1coordinator_no= {"9448260823", "7411179295", "9902643437", "9060991914",
            "9886080813", "9611831671", "9986464852", "8971205200",
            "9686684184", "805062998", "9980764095", "9448131963",
            "8792329243", "9739310656", "9739310656", "9739310656",
            "7022153497", "8722580150", "9880833798", "8884834111", "8277024701", "8904471865"};

    private ArrayList<Events> mEvents;
    private RecyclerView mRecyclerView;
    private EventAdapter mEventAdapter;




    @Override
    public void onCreate(Bundle savedInstanceState) {
        mEvents=new ArrayList<>();
        for (int i=0;i<day1events.length;i++)
        {
            Events event= new Events();

            event.setEvent(day1events[i]);
            event.setVenue(day1venue[i]);
            event.setTime(timings[i]);
            event.setDetails(day1description[i]);
            event.setFavourite(false);
            event.setPhoneNumber(day1coordinator_no[i]);
            mEvents.add(event);
        }


        super.onCreate(savedInstanceState);

    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.day1_fragment_event_list, container, false);
        mRecyclerView=(RecyclerView)view.
                findViewById(R.id.day1_event_list_recyclerview);

        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        updateUI();


        return view;
    }

    private void updateUI() {

        mEventAdapter=new EventAdapter(mEvents);
        mRecyclerView.setAdapter(mEventAdapter);
    }



    private class EventHolder extends RecyclerView.ViewHolder {

        private TextView mEventTileTextView;
        private TextView mEventDetailsTextView;
        private TextView mVenueTextView;
        private TextView mTimeTextView;
        private SmallBang mSmallBang;
        private ImageView mFavouriteView;
        private ImageView mPhoneDialerView;

        private Events mEvent;

        public EventHolder(View itemView) {

            super(itemView);

            mEventTileTextView = (TextView) itemView.findViewById(R.id.event_title_textview);
            mEventDetailsTextView = (TextView) itemView.findViewById(R.id.event_details_text_view);
            mVenueTextView = (TextView) itemView.findViewById(R.id.venue_textview);
            mTimeTextView = (TextView) itemView.findViewById(R.id.time_textview);
            mPhoneDialerView=(ImageView)itemView.findViewById(R.id.phonedial_imageview);

            mFavouriteView = (ImageView) itemView.findViewById(R.id.favourite_view);

            Typeface robotoMonoMedium = Typeface.createFromAsset(itemView.getContext().getAssets(), "fonts/RobotoMono-Medium.ttf");
            Typeface robotoMonoRegular = Typeface.createFromAsset(itemView.getContext().getAssets(), "fonts/RobotoMono-Regular.ttf");


            mEventTileTextView.setTypeface(robotoMonoMedium);
            mEventDetailsTextView.setTypeface(robotoMonoMedium);
            mVenueTextView.setTypeface(robotoMonoRegular);
            mTimeTextView.setTypeface(robotoMonoMedium);




        }

        public void bindData(final Events event) {
            mEvent = event;
            mEventTileTextView.setText(mEvent.getEvent());
            mVenueTextView.setText(mEvent.getVenue());
            mTimeTextView.setText(mEvent.getTime());
            mEventDetailsTextView.setText(mEvent.getDetails());
            mFavouriteView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mEvent.isFavourite()) {
                        unlike(v);
                    } else {
                        like(v);
                    }
                }
            });

            mPhoneDialerView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent callIntent = new Intent(Intent.ACTION_DIAL);
                    String number= "tel:"+mEvent.getPhoneNumber().toString();
                    callIntent.setData(Uri.parse(number));
                    startActivity(callIntent);
                }
            });

        }

        private void unlike(View v) {

            mEvent.setFavourite(false);
            mFavouriteView.setImageResource(R.drawable.ic_favorite_black_18dp);


        }

        private void like(View v) {
            mEvent.setFavourite(true);

            mFavouriteView.setImageResource(R.drawable.ic_favorite_red_18dp);

        }
    }


    private class EventAdapter extends RecyclerView.Adapter<EventHolder> {

        private ArrayList<Events> mEvents;

        public EventAdapter(ArrayList<Events> events) {
            mEvents = events;
        }

        @Override
        public EventHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            LayoutInflater inflater = LayoutInflater.from(getActivity());
            View view = inflater.inflate(R.layout.events_item, parent, false);

            return new EventHolder(view);

        }

        @Override
        public void onBindViewHolder(EventHolder holder, int position) {

            Events events = mEvents.get(position);
            holder.bindData(events);

        }

        @Override
        public int getItemCount() {
            return mEvents.size();
        }
    }
}

Day2EventFragment.java

 package com.execube.volantis.views;

    import android.content.Intent;
    import android.graphics.Typeface;
    import android.net.Uri;
    import android.os.Bundle;
    import android.support.annotation.Nullable;
    import android.support.v4.app.Fragment;
    import android.support.v7.widget.LinearLayoutManager;
    import android.support.v7.widget.RecyclerView;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.ImageView;
    import android.widget.TextView;

    import com.execube.volantis.R;
    import com.execube.volantis.model.Events;

    import java.util.ArrayList;

    import xyz.hanks.library.SmallBang;

    /**
     * Created by Prateek Phoenix on 4/7/2016.
     */
    public class Day2EventFragment extends Fragment {




        private static String day2events[]={"Gaanchaali bidi kannada maathaadi",
                "Vocal classical music solo prelims", "Vocal light music solo Prelims", "Antichess","Vocal light music group","Movie clip recreation", "Battle of bands", "Western Group Dance",
                "Indian Group Dance", "RAMP", "Techcharades","Karaoke","Web designing","Online treasure hunt", "Rangoli", "On spot photography"
                , "Slow drag", "Kannada dumb charades","Kannada anthyakshari", "Mini Militia", "FIFA", "Counterstrike"};


     //UPDATE THE TIMINGS TO THE CURRENT 24 HOUR FORMAT
        private static String timings[]={"09:00","09:00","09:00","09:00",
                "10:00","10:00","10:00","10:00",
                "10:00","10:00","10:00","11:00",
                "11:00","11:00","11:00","13:00",
                "13:00","14:00","14:00","14:00",
                "16:30","19:30"};

        private String day2venue[]={"EC blk lvl1",
                "EC blk lvl1", "MCA/CS/IS lab", "MCA/CS/IS lab", "MCA/CS/IS lab", "MCA/CS/IS lab",
                "Main stage", "Main stage", "Main stage”", "Main stage",
                "Main stage", "Main stage", "Edusat hall", "Edusat hall",
                "EEE lab", "Mech Lab", "Street", "Street", "Street",
                "CS/IS block", "CS/IS block", "CS/IS block", };


        private String[] day2coordinator_no= {"9448260823", "7411179295", "9902643437", "9060991914",
                "9886080813", "9611831671", "9986464852", "8971205200",
                "9686684184", "805062998", "9980764095", "9448131963",
                "8792329243", "9739310656", "9739310656", "9739310656",
                "7022153497", "8722580150", "9880833798", "8884834111", "8277024701", "8904471865"};

        private ArrayList<Events> mEvents;
        private RecyclerView mRecyclerView;
        private EventAdapter mEventAdapter;




        @Override
        public void onCreate(Bundle savedInstanceState) {
            mEvents=new ArrayList<>();
            for (int i=0;i< day2events.length;i++)
            {
                Events event= new Events();

                event.setEvent(day2events[i]);
                event.setVenue(day2venue[i]);
                event.setTime(timings[i]);
                event.setDetails("Enjoy Pantheon 2016. Play it safe. Live ong and Prodper. Here is some Random Text.");
                event.setFavourite(false);
                event.setPhoneNumber(day2coordinator_no[i]);
                mEvents.add(event);
            }


            super.onCreate(savedInstanceState);

        }


        @Nullable
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            View view=inflater.inflate(R.layout.day2_fragment_event_list, container, false);
            mRecyclerView=(RecyclerView)view.
                    findViewById(R.id.day2_event_list_recyclerview);

            mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
            updateUI();


            return view;
        }

        private void updateUI() {

            mEventAdapter=new EventAdapter(mEvents);
            mRecyclerView.setAdapter(mEventAdapter);
        }



        private class EventHolder extends RecyclerView.ViewHolder {

            private TextView mEventTileTextView;
            private TextView mEventDetailsTextView;
            private TextView mVenueTextView;
            private TextView mTimeTextView;
            private SmallBang mSmallBang;
            private ImageView mFavouriteView;
            private ImageView mPhoneDialerView;

            private Events mEvent;

            public EventHolder(View itemView) {

                super(itemView);

                mEventTileTextView = (TextView) itemView.findViewById(R.id.event_title_textview);
                mEventDetailsTextView = (TextView) itemView.findViewById(R.id.event_details_text_view);
                mVenueTextView = (TextView) itemView.findViewById(R.id.venue_textview);
                mTimeTextView = (TextView) itemView.findViewById(R.id.time_textview);
                mPhoneDialerView=(ImageView)itemView.findViewById(R.id.phonedial_imageview);

                mFavouriteView = (ImageView) itemView.findViewById(R.id.favourite_view);

                Typeface robotoMonoMedium = Typeface.createFromAsset(itemView.getContext().getAssets(), "fonts/RobotoMono-Medium.ttf");
                Typeface robotoMonoRegular = Typeface.createFromAsset(itemView.getContext().getAssets(), "fonts/RobotoMono-Regular.ttf");


                mEventTileTextView.setTypeface(robotoMonoMedium);
                mEventDetailsTextView.setTypeface(robotoMonoMedium);
                mVenueTextView.setTypeface(robotoMonoRegular);
                mTimeTextView.setTypeface(robotoMonoMedium);




            }

            public void bindData(final Events event) {
                mEvent = event;
                mEventTileTextView.setText(mEvent.getEvent());
                mVenueTextView.setText(mEvent.getVenue());
                mTimeTextView.setText(mEvent.getTime());
                mEventDetailsTextView.setText(mEvent.getDetails());
                mFavouriteView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (mEvent.isFavourite()) {
                            unlike(v);
                        } else {
                            like(v);
                        }
                    }
                });

                mPhoneDialerView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent callIntent = new Intent(Intent.ACTION_DIAL);
                        String number= "tel:"+mEvent.getPhoneNumber().toString();
                        callIntent.setData(Uri.parse(number));
                        startActivity(callIntent);
                    }
                });

            }

            private void unlike(View v) {

                mEvent.setFavourite(false);
                mFavouriteView.setImageResource(R.drawable.ic_favorite_black_18dp);


            }

            private void like(View v) {
                mEvent.setFavourite(true);

                mFavouriteView.setImageResource(R.drawable.ic_favorite_red_18dp);

            }
        }


        private class EventAdapter extends RecyclerView.Adapter<EventHolder> {

            private ArrayList<Events> mEvents;

            public EventAdapter(ArrayList<Events> events) {
                mEvents = events;
            }

            @Override
            public EventHolder onCreateViewHolder(ViewGroup parent, int viewType) {
                LayoutInflater inflater = LayoutInflater.from(getActivity());
                View view = inflater.inflate(R.layout.events_item, parent, false);

                return new EventHolder(view);

            }

            @Override
            public void onBindViewHolder(EventHolder holder, int position) {

                Events events = mEvents.get(position);
                holder.bindData(events);

            }

            @Override
            public int getItemCount() {
                return mEvents.size();
            }
        }








    }

EventPagerFragment.java

package com.execube.volantis.views;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.execube.volantis.R;

/**
 * Created by Prateek Phoenix on 4/7/2016.
 */
public class EventPagerFragment extends Fragment{

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
     View view= inflater.inflate(R.layout.fragment_event_viewpager,container,false);

        ViewPager viewPager= (ViewPager) view.findViewById(R.id.viewPager);
        TabLayout tabLayout=(TabLayout)view.findViewById(R.id.tabLayout);

        final Day1EventFragment day1EventFragment= new Day1EventFragment();
        final Day2EventFragment day2EventFragment= new Day2EventFragment();


        viewPager.setAdapter(new FragmentPagerAdapter(getChildFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
               return position==0?day1EventFragment:day2EventFragment;
            }

            @Override
            public int getCount() {
                return 2;
            }

            @Override
            public CharSequence getPageTitle(int position) {
                return position==0?"DAY 1":"DAY 2";
            }
        });

        tabLayout.setupWithViewPager(viewPager);


        return  view;

    }
}

EventActivity.java

/**
 * Created by Prateek Phoenix on 4/7/2016.
 */
public class EventActivity extends FragmentActivity {

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


        FragmentManager fm= getSupportFragmentManager();
        android.support.v4.app.Fragment fragment=fm.findFragmentById(R.id.event_activity_container);

        if(fragment==null)
        {
            fragment=new EventPagerFragment();

            fm.beginTransaction()
                    .add(R.id.event_activity_container,fragment)
                    .addToBackStack(null)
                    .commit();

        }
    }
}

Logcat消息

04-07 21:25:43.961 29352-29352/com.execube.volantis E/AndroidRuntime: FATAL EXCEPTION: main
  Process: com.execube.volantis, PID: 29352
  java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.execube.volantis/com.execube.volantis.views.Day1EventFragment}: java.lang.ClassCastException: com.execube.volantis.views.Day1EventFragment cannot be cast to android.app.Activity
      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2363)
      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2535)
      at android.app.ActivityThread.access$900(ActivityThread.java:154)
      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1380)
      at android.os.Handler.dispatchMessage(Handler.java:102)
      at android.os.Looper.loop(Looper.java:148)
      at android.app.ActivityThread.main(ActivityThread.java:5490)
      at java.lang.reflect.Method.invoke(Native Method)
      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
   Caused by: java.lang.ClassCastException: com.execube.volantis.views.Day1EventFragment cannot be cast to android.app.Activity
      at android.app.Instrumentation.newActivity(Instrumentation.java:1078)
      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2353)
      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2535) 
      at android.app.ActivityThread.access$900(ActivityThread.java:154) 
      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1380) 
      at android.os.Handler.dispatchMessage(Handler.java:102) 
      at android.os.Looper.loop(Looper.java:148) 
      at android.app.ActivityThread.main(ActivityThread.java:5490) 
      at java.lang.reflect.Method.invoke(Native Method) 
      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 

1 个答案:

答案 0 :(得分:0)

而不是

class SignUpAdmin(admin.ModelAdmin):
    list_display = ["__unicode__", "timestamp", "updated"]
    form = SignUp
    # class Meta:
    #   model = SignUp

    admin.site.register(SignUp, SignUpAdmin)

使用

android.support.v4.app.Fragment fragment=fm.findFragmentById(R.id.event_activity_container);

if(fragment==null)