com.cnm.cnmrc.fragment.vodtvch.TvchDetail.java Source code

Java tutorial

Introduction

Here is the source code for com.cnm.cnmrc.fragment.vodtvch.TvchDetail.java

Source

/*
 * Copyright (C) 2011 Chris Gao <chris@exina.net>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.cnm.cnmrc.fragment.vodtvch;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.cnm.cnmrc.MainActivity;
import com.cnm.cnmrc.R;
import com.cnm.cnmrc.adapter.TvchDetailAdapter;
import com.cnm.cnmrc.item.ItemTvchDetail;
import com.cnm.cnmrc.item.ItemTvchDetailList;
import com.cnm.cnmrc.parser.TvchDetailParser;
import com.cnm.cnmrc.popup.PopupTvReserving;
import com.cnm.cnmrc.receiver.AlarmReceiver;
import com.cnm.cnmrc.util.UiUtil;
import com.cnm.cnmrc.util.UrlAddress;
import com.cnm.cnmrc.util.Util;

public class TvchDetail extends Base implements View.OnClickListener {

    public TvchDetail newInstance(int selectedCategory, String title, boolean isFirstDepth, Bundle bundle) {
        mTvchDetail = new TvchDetail();
        Bundle args = new Bundle();
        args.putString("title", title);
        args.putBoolean("isFirstDepth", isFirstDepth);
        args.putBundle("bundle", bundle);
        mTvchDetail.setArguments(args);
        return mTvchDetail;
    }

    LinearLayout preventClickDispatching; //  ?  ?? ?? .

    ImageButton prev;
    ImageButton next;
    TextView titleDate; //  ? 

    String channelId;
    String channelNumber;
    String channelName;
    String dateIndex;

    List<ArrayFragment> fragments; // ?? ?
    private ViewPager mPager; //  ?
    private FragmentPagerAdapterClass pagerAdapter = null;

    TvchDetail mTvchDetail = null;

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

        preventClickDispatching = (LinearLayout) layout.findViewById(R.id.prevent_click_dispatching);
        preventClickDispatching.setOnClickListener(this);

        channelName = getArguments().getString("title");
        isFirstDepth = getArguments().getBoolean("isFirstDepth");

        Bundle bundle = getArguments().getBundle("bundle");
        channelId = bundle.getString("id");
        dateIndex = bundle.getString("dateIndex");

        // ,   
        prev = (ImageButton) layout.findViewById(R.id.date_pre); //? ? ?? 
        prev.setOnClickListener(this);
        prev.setVisibility(View.INVISIBLE);

        next = (ImageButton) layout.findViewById(R.id.date_next); //? ? ?? 
        next.setOnClickListener(this);

        //  ? , ?      ?.
        titleDate = (TextView) layout.findViewById(R.id.date);
        Date date = new Date(System.currentTimeMillis());
        titleDate.setText(Util.getMMDDE(date));

        fragments = new ArrayList<ArrayFragment>();
        fragments.add(new ArrayFragment(0, channelId));
        fragments.add(new ArrayFragment(1, channelId));
        fragments.add(new ArrayFragment(2, channelId));
        fragments.add(new ArrayFragment(3, channelId));
        fragments.add(new ArrayFragment(4, channelId));
        fragments.add(new ArrayFragment(5, channelId));
        fragments.add(new ArrayFragment(6, channelId));

        //        fragments.add(ArrayFragment.newInstance(0, channelId));
        //        fragments.add(ArrayFragment.newInstance(1, channelId));
        //        fragments.add(ArrayFragment.newInstance(2, channelId));
        //        fragments.add(ArrayFragment.newInstance(3, channelId));
        //        fragments.add(ArrayFragment.newInstance(4, channelId));
        //        fragments.add(ArrayFragment.newInstance(5, channelId));
        //        //fragments.add(ArrayFragment.newInstance(6, channelId));

        mPager = (ViewPager) layout.findViewById(R.id.pager); // ?
        pagerAdapter = new FragmentPagerAdapterClass(getActivity().getSupportFragmentManager(), fragments);
        mPager.setAdapter(pagerAdapter); //PagerAdapter 
        mPager.setOnPageChangeListener(new OnPageChangeListener() { //?? ?, gallery listview? onItemSelectedListener 
            //?? ?? ?
            @Override
            public void onPageSelected(int position) {
                Date date = new Date(System.currentTimeMillis());
                date = Util.getNextDAY(date, position);
                titleDate.setText(Util.getMMDDE(date));

                ((ArrayFragment) pagerAdapter.getItem(position)).showTvchDetail();

                if (position == 0)
                    prev.setVisibility(View.INVISIBLE);
                else
                    prev.setVisibility(View.VISIBLE);

                if (position == 6)
                    next.setVisibility(View.INVISIBLE);
                else
                    next.setVisibility(View.VISIBLE);
            }

            @Override
            public void onPageScrolled(int position, float positionOffest, int positionOffsetPixels) {
                // flicking? ? ? ?.
                //Log.i("hwang", "onPageScrolled");
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                // flicking? ? ?  ?. 
                // ?, ??? ??  ? ?  ?.
                // flicking?  ??  ? ?....
                // Log.v("hwang", "onPageScrollStateChanged");
            }
        });

        return layout;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();

        //      pagerAdapter = null;
        //      fragments = null;

        //  fragments null?.
        //      for(Fragment f : fragments) {
        //         getActivity().getSupportFragmentManager().beginTransaction().remove(f).commit();
        //      }

        // ----------------------------------------------------------------------------------------------
        // vod? ?? vodtopmenu fragment vod destory?  ??? vodtopmenu? ? destory .
        // ?  ???? ? fragment ? vod? ?  ? ? Activity?   .
        // ----------------------------------------------------------------------------------------------
        //        {
        //           Fragment f = getActivity().getSupportFragmentManager().findFragmentById(R.id.vod_tvch_panel);
        //           if (f != null) {
        //              getActivity().getSupportFragmentManager().beginTransaction().remove(f).commit();
        //           }
        //        }

    }

    @Override
    public void onStop() {
        // Fragment? Fragment  ?   Fragment remove .     ? Fragment  ?   .
        for (Fragment f : fragments) {
            getActivity().getSupportFragmentManager().beginTransaction().remove(f).commit();
        }

        super.onStop();
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

    }

    @Override
    public void onDetach() {
        super.onDetach();

    }

    @Override
    public void onClick(View v) {
        // sidebar  return.
        // 2013-12-06 comment later
        // 
        //if (UiUtil.isSlidingMenuOpening(getActivity())) return;

        // 2013-12-10
        // ?  .
        if (UiUtil.isSlidingMenuOpening(getActivity()))
            UiUtil.toggleSidebar(getActivity());

        int cur = mPager.getCurrentItem(); // ? ?
        switch (v.getId()) {
        case R.id.date_pre:
            if (cur > 0)
                mPager.setCurrentItem(cur - 1, true); //? ? ??
            else
                Toast.makeText(getActivity(), " ? ? .", Toast.LENGTH_SHORT).show(); // 
            break;

        case R.id.date_next:
            if (cur < fragments.size() - 1)
                mPager.setCurrentItem(cur + 1, true); //? ? ??
            else
                Toast.makeText(getActivity(), "  ? .", Toast.LENGTH_SHORT).show(); // 
            break;
        }
    }

    // -----------------------------------------
    // FragmentPager 
    // -----------------------------------------
    private class FragmentPagerAdapterClass extends FragmentPagerAdapter {
        private List<ArrayFragment> fragments;

        //??
        public FragmentPagerAdapterClass(FragmentManager fm, List<ArrayFragment> fragments) {
            //public FragmentPagerAdapterClass(FragmentManager fm, String channelId, String dateIndex) {
            super(fm);

            this.fragments = fragments;

        }

        /**
         *  ??  fragment .
         * ? (,  )? getView ? 
         * @param position - ??  ? ( 0 )
         * @return  fragment
         */
        @Override
        public Fragment getItem(int position) { //  position dataIndex ?.
            //if(position == 0) this.fragments.get(position).showTvchDetail();
            return fragments.get(position);
            // return ArrayFragment.newInstance(position, channelId, dateIndex);
        }

        //??  ? ? 
        @Override
        public int getCount() {
            return this.fragments.size();
        }

        // destroyItem  ?.
        //      @Override
        //      public void destroyItem(ViewGroup container, int position, Object object) {
        //          getActivity().getSupportFragmentManager().beginTransaction().remove((Fragment)object).commit();
        //        super.destroyItem(container, position, object);
        //      }

        //      @Override
        //      public void setPrimaryItem(ViewGroup container, int position, Object object) {
        //         // TODO Auto-generated method stub
        //         super.setPrimaryItem(container, position, object);
        //      }
        //
        //      @Override
        //      public void finishUpdate(ViewGroup container) {
        //         // TODO Auto-generated method stub
        //         super.finishUpdate(container);
        //      }
        //
        //      // instantiateItem? ? ? ? ?
        //      @Override
        //      public boolean isViewFromObject(View view, Object object) {
        //         // TODO Auto-generated method stub
        //         return view == object;
        //         // return super.isViewFromObject(view, object);
        //      }
        //      
        //      @Override
        //      public void restoreState(Parcelable state, ClassLoader loader) {
        //         // TODO Auto-generated method stub
        //         super.restoreState(state, loader);
        //      }
        //
        //      @Override
        //      public Parcelable saveState() {
        //         // TODO Auto-generated method stub
        //         return super.saveState();
        //      }
        //
        //      @Override
        //      public void startUpdate(ViewGroup container) {
        //         // TODO Auto-generated method stub
        //         super.startUpdate(container);
        //      }
        //
        //      @Override
        //      public void registerDataSetObserver(DataSetObserver observer) {
        //         // TODO Auto-generated method stub
        //         super.registerDataSetObserver(observer);
        //      }

    }

    // -----------------------------------------
    //    ?? ??  fragment ? ?
    // -----------------------------------------
    public class ArrayFragment extends Fragment {

        ListView listView;
        TvchDetailAdapter adapter;
        ArrayList<ItemTvchDetail> mResult = null;

        int position;
        String dateIndex; // " " ?.
        String channelId; // " ? id"  ?.

        //fragment ? static  ?? position? ? .
        //      static ArrayFragment newInstance(int position, String channelId) {
        //         ArrayFragment f = new ArrayFragment();    //? ?
        //         Bundle args = new Bundle();          // fragment? ?  ?  ?
        //         args.putInt("position", position);       //" " ?.
        //         args.putString("channelId", channelId); //" ? id" ?.
        //         f.setArguments(args);                //fragment?  .
        //         return f;                         //fragment 
        //      }

        ArrayFragment(int position, String channelId) {
            this.position = position;
            this.channelId = channelId;
        }

        //fragment  
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            //channelId = getArguments() != null ? getArguments().getString("channelId") : "";    // ?? " ? id" ?  ?
            //position = getArguments() != null ? getArguments().getInt("position") : 0;          // ?? " " ?  ?
            position++;
            dateIndex = String.valueOf(position);
        }

        String mTitle = "";
        String mTimePeriod = "";
        String mBroadcastingTime = "";
        long broadcastingTime = 0;
        int mPosition = 0;
        HashMap<String, String> map = new HashMap<String, String>(); // ? program id ?

        //fragment? UI ?
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            View layout = inflater.inflate(R.layout.tvch_detail_viewpager, container, false); //   ?? inflate .

            // listview
            listView = (ListView) layout.findViewById(R.id.listview);
            listView.setDivider(null);
            listView.setDividerHeight(0);
            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    // sidebar  return.
                    // 2013-12-06 comment later
                    // 
                    //if (UiUtil.isSlidingMenuOpening(getActivity())) return;

                    // 2013-12-10
                    // ?  .
                    if (UiUtil.isSlidingMenuOpening(getActivity()))
                        UiUtil.toggleSidebar(getActivity());

                    // position
                    mPosition = position;

                    // popup
                    mTitle = adapter.getItem(position).getTitle();
                    mBroadcastingTime = adapter.getItem(position).getBroadcastingTime();
                    Date temp = Util.toDate(mBroadcastingTime);
                    broadcastingTime = temp.getTime();

                    // ?  .
                    if (broadcastingTime < System.currentTimeMillis())
                        return;

                    //  ? ?? ?? 23:59 .
                    String time1 = adapter.getItem(position).getBroadcastingTime();
                    if (position == adapter.getCount() - 1) {
                        mTimePeriod = Util.getTvReservingLast(time1);
                    } else {
                        String time2 = adapter.getItem(position + 1).getBroadcastingTime();
                        mTimePeriod = Util.getTvReserving(time1, time2);
                    }

                    FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
                    PopupTvReserving popup = new PopupTvReserving(mTitle, mTimePeriod);
                    popup.show(ft, PopupTvReserving.class.getSimpleName());
                    popup.setInterceptor(new PopupTvReserving.Interceptor() {
                        @Override
                        public void onSetAlarm() {
                            // ? program id ?  . // ? db ???
                            if (map.containsKey(adapter.getItem(mPosition).getId())) {
                                Log.e("hwang", "already tv reserving (program id) : "
                                        + adapter.getItem(mPosition).getId());
                                return;
                            }

                            // 
                            Intent intent = new Intent(getActivity(), AlarmReceiver.class); // ? ? ? BR 
                            intent.putExtra("title", mTitle);
                            intent.putExtra("time", mTimePeriod);

                            PendingIntent sender = PendingIntent.getBroadcast(getActivity(),
                                    (int) System.currentTimeMillis(), intent, 0);
                            AlarmManager am = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);
                            //  . 10
                            //                     Calendar calendar = Calendar.getInstance();
                            //                     calendar.setTimeInMillis(System.currentTimeMillis());
                            //                     calendar.add(Calendar.SECOND, 10);
                            //                     am.set(AlarmManager.RTC, calendar.getTimeInMillis(), sender);

                            am.set(AlarmManager.RTC, broadcastingTime, sender);

                            // ? program id ?  .    .
                            map.put(adapter.getItem(mPosition).getId(), adapter.getItem(mPosition).getId());

                        }
                    });

                }

            });

            if (dateIndex.equals("1"))
                showTvchDetail();

            return layout;
        }

        private void showTvchDetail() {
            // check network and data loading
            if (Util.GetNetworkInfo(getActivity()) == 99) {
                Util.AlertShow(getActivity());
            } else {
                new VodSemiAsyncTask().execute();
            }
        }

        long elapsedTime;
        ItemTvchDetailList list;

        private class VodSemiAsyncTask extends AsyncTask<Void, Void, ArrayList<ItemTvchDetail>> {
            @Override
            protected void onPreExecute() {
                ((MainActivity) getActivity()).getMyProgressBar().show();
                super.onPreExecute();
            }

            protected ArrayList<ItemTvchDetail> doInBackground(Void... params) {
                String requestURL = UrlAddress.Channel.getGetChannelSchedule(channelId, dateIndex);
                TvchDetailParser parser = new TvchDetailParser(requestURL);

                elapsedTime = System.currentTimeMillis();
                parser.start();
                Log.i("hwang", "elapsedTime of vod semi : " + (System.currentTimeMillis() - elapsedTime));

                list = parser.getList();
                return parser.getList().getList();
            }

            // onPostExecute displays the results of the AsyncTask.
            @Override
            protected void onPostExecute(ArrayList<ItemTvchDetail> result) {
                mResult = result;

                if (mResult.size() == 0) {
                    Toast.makeText(getActivity(), "?? !", Toast.LENGTH_LONG).show();
                    ((MainActivity) getActivity()).getMyProgressBar().dismiss();
                    return;
                }

                if (mResult == null)
                    onCancelled();
                else {
                    Log.i("hwang", "search vod result count : " + mResult.size());

                    if (!list.getResultCode().equals("100")) {
                        String desc = Util.getErrorCodeDesc(list.getResultCode());
                        Toast.makeText(getActivity(), desc, Toast.LENGTH_LONG).show();
                    } else {
                        adapter = new TvchDetailAdapter(getActivity(), R.layout.list_item_tvch_detail, mResult);
                        listView.setAdapter(adapter);
                    }

                    ((MainActivity) getActivity()).getMyProgressBar().dismiss();
                }
            }

            @Override
            protected void onCancelled() {
                Util.onCancelled(getActivity());

                super.onCancelled();
            }
        }
    }

}