4

SCOPE

I am making an application for my college fest which shows events for 4 particular fixed dates. I have a main_activity which has a linearlayout on which each and every fragment is displayed. Now a I have a Fragment "ScheduleFragment".

ScheduleFragment consists of a ViewPager and a FragmentStatePagerAdapter which make it possible to toggle through 4 dates.

The ViewPager has 4 pages representing 4 dates and these 4 pages come from 4 references of a same fragment i.e "ScheduleListSubFragment"

From here a user selects an Event and can view the eventDescription which is contained in "EventDescriptionFragment"

PROBLEM

The flow goes well. User come across ScheduleFragment, then toggles to the appropriate date and selects an event.

Now when he goes back from the EventDescriptionFragment to ScheduleFragment (I will later tell how I am doing this), the ViewPager shows blank view. And when we swipe to the next date, the events for the next date comes, and we swipe back to previous date, the events for previous date are back.

I debugged my application and came to know that when we go back to ScheduleFragment, then viewpager is not creating new fragment instances for ScheduleListSubFragment unless I scroll the viewpager.

So, I guess ViewPager is enable to bring that particular reference (of ScheduleListSubFragment) which was being viewed by the user.

How am I going back to ScheduleFragment? I have created a stack in main_activity. When a user selects an event, I push the current reference of ScheduleFragment into the stack. And when back is pressed, I pop that reference and place it on the screen.

CODE *ScheduleFragment* import com.Nit_kkr.updates.app.adapters.ScheduleFragmentAdapter; import com.viewpagerindicator.PageIndicator; import com.viewpagerindicator.TitlePageIndicator; import com.viewpagerindicator.TitlePageIndicator.IndicatorStyle;

        import android.os.Bundle;
        import android.support.v4.app.Fragment;
        import android.support.v4.view.ViewPager;
        import android.view.LayoutInflater;
        import android.view.View;
        import android.view.ViewGroup;
        import android.widget.TextView;
        import android.widget.Toast;

        public class ScheduleFragment extends Fragment{
            ScheduleFragmentAdapter mAdapter;
            ViewPager mPager;
            PageIndicator mIndicator;
            TitlePageIndicator indicator;




            @Override
            public void onViewStateRestored(Bundle savedInstanceState) {
        //      Toast.makeText(getActivity(), " onViewStateRestored()", Toast.LENGTH_SHORT).show();
                super.onViewStateRestored(savedInstanceState);
            }

            @Override
            public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                mAdapter = new ScheduleFragmentAdapter(getActivity().getSupportFragmentManager());
                mAdapter.notifyDataSetChanged();
            }

            @Override
            public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
                View v = inflater.inflate(R.layout.scheduled_list, null);
                prepareSlidingPager(v);

                return v;
            }

            private void prepareSlidingPager(View v)
            {

                    mPager = (ViewPager)v.findViewById(R.id.pager);

                    mPager.setOffscreenPageLimit(4);
                    mPager.setAdapter(mAdapter);

                    mIndicator = (TitlePageIndicator)v.findViewById(R.id.indicator);
                    indicator = (TitlePageIndicator) mIndicator;
                    mIndicator.setViewPager(mPager);

                    final float density = getResources().getDisplayMetrics().density;
                    indicator.setBackgroundColor(0x18AF0000);
                    indicator.setFooterColor(0xFFAA2222);

                    //indicator.setFooterColor(0xFFAA33);

                    indicator.setFooterLineHeight(2 * density); //1dp
                    indicator.setFooterIndicatorHeight(3 * density); //3dp
                    indicator.setFooterIndicatorStyle(IndicatorStyle.Underline);

                    indicator.setTextColor(0xAA000000);
                    indicator.setSelectedColor(0xFF000000);
                    indicator.setSelectedBold(true);
            }


            public static ScheduleFragment newInstance()
            {
                ScheduleFragment frag = new ScheduleFragment();
                return frag;
            }
        }

ScheduleListSubFragment:

            public class ScheduleListSubFragment extends Fragment implements OnItemClickListener{

                long startDate;
                long endDate;


                private ListView eventlist;
                private listadapter adapter;
                private List events;
                private MyDB db;



                @Override
                public void onAttach(Activity activity) {
                    Toast.makeText(getActivity(), " onAttatch()------------------sublist schedule", Toast.LENGTH_SHORT).show();
                    super.onAttach(activity);
                }

                @Override
                public void onCreate(Bundle savedInstanceState) {
                    super.onCreate(savedInstanceState);

                    db=new MyDB(this.getActivity());

                    Toast.makeText(getActivity(), " onCreate()------------------sublist schedule", Toast.LENGTH_SHORT).show();

                }

                @Override
                public View onCreateView(LayoutInflater inflater, ViewGroup container,
                        Bundle savedInstanceState) {

                    //Toast.makeText(getActivity(), " onCreateView()------------------sublist schedule", Toast.LENGTH_SHORT).show();

                    View v = inflater.inflate(R.layout.eventslist_subfragment_layout, null);

                    eventlist=(ListView)v.findViewById(R.id.Event_list);
                    eventlist.setOnItemClickListener(this);

                    fetcheventdata(getArguments().getLong("start_time"), getArguments().getLong("end_time"));
                    return v;

                }

                public static ScheduleListSubFragment newInstance(long starttime, long endtime)
                {
                    ScheduleListSubFragment frag = new ScheduleListSubFragment();
                    Bundle bundle = new Bundle();

                    bundle.putLong("start_time", starttime);
                    bundle.putLong("end_time", endtime);
                    frag.setArguments(bundle);

                    return frag;
                }



                 private void fetcheventdata(long starttime, long endtime)
                    {

                        db.open();
                        events=db.getEvents_bycategory_bytime(null, starttime, endtime);
                        db.close();
                        if(events!=null)
                        {
                        adapter=new listadapter(getActivity(), android.R.layout.simple_expandable_list_item_1, events);
                        eventlist.setAdapter(adapter);

                        adapter.notifyDataSetChanged();
                        }
                        else
                            Toast.makeText(getActivity(), "No Events Yet", Toast.LENGTH_LONG);

                        //Toast.makeText(getActivity(), events.size(), Toast.LENGTH_LONG).show();



                    }


                 private class listadapter extends ArrayAdapter<Event>
                    {
                        private List items;

                        public listadapter(Context context, int textViewResourceId,
                                List objects){
                            super(context, textViewResourceId, objects);
                            items=new ArrayList();
                            items=objects;

                        }

                        @Override
                        public View getView(int position, View convertView, ViewGroup parent) {

                            View v=convertView;

                            if(v==null)
                            {
                                LayoutInflater vi=(LayoutInflater)getActivity().getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
                                v=vi.inflate(R.layout.upcominglist, null);

                            }

                            Event event=(Event)items.get(position);
                            if(event!=null)
                            {
                                TextView name=(TextView)v.findViewById(R.id.Name);
                                TextView venue=(TextView)v.findViewById(R.id.Venue);
                                TextView time=(TextView)v.findViewById(R.id.time);


                                name.setTypeface(Utils.getHeroFace(getActivity().getAssets()));
                                venue.setTypeface(Utils.getHeroFace(getActivity().getAssets()));

                                name.setTextColor(getResources().getColor(R.color.black));
                                venue.setTextColor(getResources().getColor(R.color.darkgrey));
                                time.setTextColor(getResources().getColor(R.color.black));


                                //ImageView favouriteicon=(ImageView)v.findViewById(R.id.fav_status_image);
            //                  ImageView remindericon=(ImageView)v.findViewById(R.id.reminder_status_image);

                                name.setText(event.getName());
                                time.setText(Html.fromHtml("<b>"+event.getEvent_time()+"</b><br></br>"+event.getEvent_date()));
                                venue.setText(event.getVenue());


                            }
                            return v;
                        }

                    }


                 @Override
                    public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long arg3) {
                        eventnotifierapp app=(eventnotifierapp)getActivity().getApplication();
                        app.crntEvent=(Event) events.get(pos);
                        //startActivity(new Intent(this.getActivity(), EventDescription.class));

                        EventDescriptionFragment frag = EventDescriptionFragment.NewInstance();
                        ((MainActivity)getActivity()).OpenNextFragment(frag);

                    }

            }

ScheduleFragmentAdapter:

    public class ScheduleFragmentAdapter extends FragmentStatePagerAdapter{
        String cat_name;

        protected static final String[] CONTENT = new String[] { "Thursday, Feb 20", 
            "Friday, Feb 21", "Saturday, Feb 22", "Sunday, Feb 23", };

        private int mCount = CONTENT.length;

        public ScheduleFragmentAdapter(FragmentManager fm) {
            super(fm);


        }

        @Override
        public Fragment getItem(int position) {
            if(position == 0)
                return ScheduleListSubFragment.newInstance(day1start, day1end);
            if(position == 1)
                return ScheduleListSubFragment.newInstance(day2start, day2end);
            if(position == 2)
                return ScheduleListSubFragment.newInstance(day3start, day3end);
            else 
                return ScheduleListSubFragment.newInstance(day4start, day4end);
        }

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

        @Override
        public CharSequence getPageTitle(int position) {
          return CONTENT[position % CONTENT.length];
        }
    }

Research I did some digging on stackOverFlow, and found some related queries, which were not exactly the same, but couldnt arrive at a solution

Any Kind of Help, is highly appreciated.

gaurav414u
  • 812
  • 13
  • 22

1 Answers1

3

Hi just get your code Running , what help me to resolve your problem is : 1. Do use getChildFragmentManager() on initializing your Adapter like :

fragadapter = new myfragmentAdapter(getChildFragmentManager());

this will give you run time Error right?? that so because on back pressed button application do not have your fragment context(as per my opinion) so do add your fragment in back stack like :

public void addpagerfragment(View v)
    {
        pagerFragment frag = pagerFragment.NewInstance();
        crrntfrag = frag;

        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.replace(R.id.container, frag).addToBackStack(null);
        ft.commit();

    }
Manish
  • 1,259
  • 3
  • 11
  • 20
  • ohhh... I see. I had no idea in this respect because I am maintaining fragment stack myself. – gaurav414u Jul 23 '14 at 11:49
  • Why isn't my method working? As I guess, I am doing everything right and indeed I am maintaining the stack(if You look at the code). – gaurav414u Jul 23 '14 at 11:50
  • yes i know you are maintaining Stack, and everything else is also right.. and sorry to say this but i didn't figure out what is going wrong. i just tried what i think might causing the problem,will let you know the exact problem when i understand it ;) – Manish Jul 23 '14 at 11:56
  • what happen in your code is : you're adding fragments in your Stack and when user press back button you are replacing the current fragment from previous fragment. Now in case of view Pager when we use it inside nested fragments , we have to use ChildFragmentManager() for proper flow(Plz don't ask why?? i'm still searching for proper reason). Now when we click back button, our context of that fragment is destroyed and a similar new fragment is added in the view.thats why we are getting NO activity error. for more clarification read this: https://code.google.com/p/android/issues/detail?id=42601 – Manish Jul 23 '14 at 12:25
  • Thanks manish. For now, IT is the solution. Cheers. If you found something, let me know. – gaurav414u Jul 23 '14 at 12:26
  • @Manish i m also getting same issue ? i m using fragmetnts and inside that fragmetn named as (Profile )viewpager+tablayout that contains 3 tabs and fragment for each tab same issue once i went to any new screen from fragmetn button click and return back my fragment (Profile ) then my tabs and its fragments are not attaching again and i on page change i m getting ur fragment is not attached with anya ctiivity how to resolve – Erum Aug 19 '15 at 13:07