package com.credencys.goscoop.fragments; import android.app.Activity; import android.app.Dialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; 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.FragmentStatePagerAdapter; import android.support.v4.content.LocalBroadcastManager; import android.support.v4.content.res.ResourcesCompat; import android.support.v4.view.ViewPager; import android.util.Log; import android.view.GestureDetector; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.animation.AnimationUtils; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.ViewFlipper; import com.afollestad.materialdialogs.DialogAction; import com.afollestad.materialdialogs.MaterialDialog; import com.credencys.goscoop.GoScoop; import com.credencys.goscoop.R; import com.credencys.goscoop.activities.CreateArticle; import com.credencys.goscoop.activities.HomeScreen; import com.credencys.goscoop.customfunctions.CustomViewPager; import com.credencys.goscoop.datamodels.CelebrationItem; import com.credencys.goscoop.datamodels.Channels; import com.credencys.goscoop.datamodels.TabItem; import com.credencys.goscoop.interfaces.MaterialDialogListener; import com.credencys.goscoop.utils.AppPrefs; import com.credencys.goscoop.utils.ConnectionDetector; import com.credencys.goscoop.utils.StaticUtils; import com.credencys.goscoop.webresponses.channel.Channel; import com.credencys.goscoop.webservices.RestClient; import com.google.android.gms.analytics.HitBuilders; import com.google.android.gms.analytics.Tracker; import com.ogaclejapan.smarttablayout.SmartTabLayout; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import retrofit.Callback; import retrofit.RetrofitError; import retrofit.client.Response; /** * Created by credencys on 05/12/2015. */public class TopStoriesFrag extends Fragment { private ArrayList<Channels> mArrChnls; private List<CelebrationItem> mArrBdayItems; private CustomViewPager mViewPager; public ArrayList<TabItem> mFragTabItem; private int count; // private LinearLayout lytFlipper;// private ViewFlipper mLayBdayBash; private SmartTabLayout mTabLayout; private TextView mTvSelectedTabText; private String mChannelName; private RelativeLayout topStoriesLay; // private RelativeLayout rlytBday; private AllArticleFragment allArticleFragment; private ArticleListFragment articalListFragment; // private Dialog progressDialog; private FragmentStatePager mFragmentStatePager; private int prevIndex = 0; // GetData getData; public TopStoriesFrag() { } private void setupViewPager(int position) { // if (progressDialog.isShowing() && progressDialog != null)// progressDialog.dismiss(); FragmentManager fm = getChildFragmentManager(); // fm.setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out); mFragmentStatePager = new FragmentStatePager(fm); mViewPager.setAdapter(mFragmentStatePager); mViewPager.setCurrentItem(position, false); sendTabName(); } private class FragmentStatePager extends FragmentStatePagerAdapter { private Fragment fragment; public FragmentStatePager(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) { fragment = new AllArticleFragment(); // prevIndex = 0; if (position == 0) { fragment = new AllArticleFragment(); allArticleFragment = (AllArticleFragment) fragment; /*allArticleFragment.setOnPageScrollChangedListener(new OnPageScrollChangedListener() { @Override public void OnPageScrollChanged(int l, int t) {// Log.d("Scroller", "SCROLL >> I changed! || " + l + " || " + t); if (lytFlipper.getVisibility() == View.GONE && (t < prevIndex || t == 0)) { prevIndex = t; lytFlipper.setAnimation(AnimationUtils.loadAnimation(getActivity(), R.anim.slide_in_top)); lytFlipper.setVisibility(View.VISIBLE); } else if (lytFlipper.getVisibility() == View.VISIBLE && t > prevIndex) { prevIndex = t; lytFlipper.setVisibility(View.GONE); } } });*/ // return fragment; } else { mChannelName = mFragTabItem.get(position).getTitle(); fragment = new ArticleListFragment(); articalListFragment = (ArticleListFragment) fragment; Bundle b = new Bundle(); b.putString("position", position + ""); b.putString("id", mFragTabItem.get(position).getId()); b.putString("name", mFragTabItem.get(position).getTitle()); b.putString("showFab", mFragTabItem.get(position).showFab()); fragment.setArguments(b); } return fragment; } @Override public int getItemPosition(Object object) { return POSITION_NONE; } @Override public CharSequence getPageTitle(int position) { return mFragTabItem.get(position).getTitle(); } @Override public int getCount() { count = mFragTabItem.size(); return count; } } boolean _areLecturesLoaded = false; @Override public void setUserVisibleHint(boolean isVisibleToUser) { super.setUserVisibleHint(isVisibleToUser); Log.e("setUserVisibleHint","setUserVisibleHint"); /*if (isVisibleToUser && !_areLecturesLoaded) { if(articalListFragment!=null) { articalListFragment.mGetArticles(false); } _areLecturesLoaded = true; }*/ } @Override public void onAttach(Activity activity) { super.onAttach(activity); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mArrBdayItems = new ArrayList<>(); mArrChnls = new ArrayList<>(); mFragTabItem = new ArrayList<>(); // [START shared_tracker] // Obtain the shared Tracker instance. mTracker = ((GoScoop) getActivity().getApplication()).getDefaultTracker(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.top_events_frag, container, false); ((ImageView) getActivity().findViewById(R.id.xBtnSearch)).setVisibility(View.VISIBLE); topStoriesLay = (RelativeLayout) view.findViewById(R.id.xRelLayTopStoriesFrag); mViewPager = (CustomViewPager) view.findViewById(R.id.viewpager_home); mViewPager.setPageTransformer(false, new NoPageTransformer(getActivity())); mViewPager.setPagingEnabled(false); ((TextView) getActivity().findViewById(R.id.xTvHomeScreenTitle)).setText("goscoop for " + AppPrefs.getInstance(getActivity()).getOrgName().toLowerCase()); // lytFlipper = (LinearLayout) view.findViewById(R.id.lytFlipper);// mLayBdayBash = (ViewFlipper) view.findViewById(R.id.xBdayLayout);// mLayBdayBash.setVisibility(View.VISIBLE);// lytFlipper.setVisibility(View.VISIBLE); mTabLayout = (SmartTabLayout) view.findViewById(R.id.tabs); mTabLayout.setVisibility(View.GONE); mTabLayout.setOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { for (int i = 0; i < mFragTabItem.size(); i++) { String key; mTvSelectedTabText = (TextView) mTabLayout.getTabAt(i).findViewById(R.id.custom_text); if (i == position) { mTvSelectedTabText.setTextColor(Color.parseColor(AppPrefs.getInstance(getActivity()).getOthrCode("ls_hzmenu_selected_text_color"))); key = getString(R.string.font_reg); sendTabName(); } else { key = getString(R.string.font_reg); mTvSelectedTabText.setTextColor(Color.parseColor(AppPrefs.getInstance(getActivity()).getOthrCode("ls_hzmenu_text_color"))); } // StaticUtils.sSetProximaNova(getActivity(), mTvSelectedTabText, key); } } @Override public void onPageScrollStateChanged(int state) { } }); HomeScreen.FAB_CREATE_ART.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent createArticle = new Intent((HomeScreen) getActivity(), CreateArticle.class); createArticle.putExtra("chnl_name", mChannelName); startActivity(createArticle); } }); mSetTheme(); return view; } private static class NoPageTransformer implements ViewPager.PageTransformer { private Context context; public NoPageTransformer(Context context) { this.context = context; } public void transformPage(View view, float position) { view.startAnimation(AnimationUtils.loadAnimation(context, android.R.anim.fade_in)); /*if (position < 0) { view.setScrollX((int)((float)(view.getWidth()) * position)); } else if (position > 0) { view.setScrollX(-(int) ((float) (view.getWidth()) * -position)); } else { view.setScrollX(0); }*/ } } @Override public void onStart() { super.onStart(); if (ConnectionDetector.getInstance(getActivity()).isOnline()) { if (count <= 0 || HomeScreen.INTEREST_UPDATED) mGetChannelsForOrganization(); } else StaticUtils.showMsgDialogTitle(getActivity(),getActivity().getResources().getString(R.string.no_internet_title),getActivity().getResources().getString(R.string.no_internet_title)); } @Override public void onDestroyView() { super.onDestroyView(); } //******************************************* BIRTHDAY FLIPPER CONTENTS ************************************* /*class GetBdayFlipperData extends AsyncTask<String, Void, String> { @Override protected void onPreExecute() { } @Override protected String doInBackground(String... params) { String result; mArrBdayItems.clear(); try { DatabaseHandler dbHandle = DatabaseHandler.getInstance(getActivity()); Cursor mCur = dbHandle.sGetTableData("bday_slider"); if (mCur.getCount() > 0) { mCur.moveToFirst(); do { CelebrationItem data = new CelebrationItem(); data.setmId(mCur.getString(mCur.getColumnIndex("_id"))); data.setItemId(mCur.getString(mCur.getColumnIndex("_id_bday"))); data.setUsrName(mCur.getString(mCur.getColumnIndex("_name_bday_usr"))); data.setUsrImg(mCur.getString(mCur.getColumnIndex("_img_bday_usr"))); data.setBdate(mCur.getString(mCur.getColumnIndex("_date_bday_usr"))); data.setIsBday(mCur.getString(mCur.getColumnIndex("_is_bday"))); data.setCity(mCur.getString(mCur.getColumnIndex("bday_usr_city"))); data.setmDeparmentName(mCur.getString(mCur.getColumnIndex("bday_usr_department"))); mArrBdayItems.add(data); } while (mCur.moveToNext()); } mCur.close(); result = "success"; } catch (Exception e) { e.printStackTrace(); result = "error"; } return result; } @Override protected void onPostExecute(String result) { if (isAdded()) { AppPrefs.getInstance(getActivity()).saveBirthdayData(result);// setFlipperContent(result); } } }*/ private GestureDetector mGestureDetector; /*private void setFlipperContent(String result) { if (result.equalsIgnoreCase("success") && mArrBdayItems.size() > 0) { lytFlipper.setVisibility(View.VISIBLE); mLayBdayBash.setVisibility(View.VISIBLE); mLayBdayBash.setBackground(null); int end = mArrBdayItems.size(); for (int i = 0; i < end; i++) { final int pos = i; LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE); final View view = inflater.inflate(R.layout.bday_flipper, null); view.setBackground(null); mLayBdayBash.addView(view); rlytBday = (RelativeLayout) view.findViewById(R.id.rlytBday); rlytBday.setVisibility(View.VISIBLE); final CircularImageView image = (CircularImageView) view.findViewById(R.id.xIvProfPic); if (mArrBdayItems.get(i).getUsrImg().equalsIgnoreCase("")) image.setImageDrawable(ContextCompat.getDrawable(getActivity(), R.mipmap.profile_view_defaul)); else { Glide.with(this).load(mArrBdayItems.get(i).getUsrImg()).asBitmap().override(150, 150).centerCrop().placeholder(R.mipmap.profile_view_defaul).into(new BitmapImageViewTarget(image) { @Override protected void setResource(Bitmap resource) { RoundedBitmapDrawable circularBitmapDrawable = RoundedBitmapDrawableFactory.create(getActivity().getResources(), resource); circularBitmapDrawable.setCircular(true); image.setImageDrawable(circularBitmapDrawable); } }); } ImageView imgClose = (ImageView) view.findViewById(R.id.imgClose); imgClose.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { rlytBday.setVisibility(View.GONE); } }); rlytBday.setTag(mArrBdayItems.get(i)); rlytBday.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { CelebrationItem celebrationItem = (CelebrationItem) v.getTag(); System.out.println(" position " + celebrationItem.getItemId()); if (mViewPager.getCurrentItem() == 0) { allArticleFragment.getItemId(celebrationItem); } else { articalListFragment.getItemId(celebrationItem); Intent intent = new Intent("Load"); intent.putExtra("ID", celebrationItem); getActivity().sendBroadcast(intent); } lytFlipper.setVisibility(View.GONE); mLayBdayBash.setVisibility(View.GONE); } }); TextView mTvBdayName = (TextView) view.findViewById(R.id.xTvBdayName); mTvBdayName.setTextColor(Color.parseColor(AppPrefs.getInstance(getActivity()).getOthrCode("ls_cb_rowsection_username_text_color"))); TextView mTvBdate = (TextView) view.findViewById(R.id.xTvBdate); mTvBdate.setTextColor(Color.parseColor(AppPrefs.getInstance(getActivity()).getOthrCode("ls_cb_rowsection_username_text_color"))); if (StaticUtils.validateString(mArrBdayItems.get(i).getBdate())) { mTvBdate.setVisibility(View.VISIBLE); try { String datestr = mArrBdayItems.get(i).getBdate().toString().trim(); DateFormat formatter; Date convertedDate; //date formate of current string getting from server is yyyy-MM-dd HH:mm:SS //This function will convert this to 25th MArch; formatter = new SimpleDateFormat("dd/MM/yyyy"); convertedDate = (Date) formatter.parse(datestr); getFormattedDate(convertedDate); mTvBdate.setText(getFormattedDate(convertedDate)); } catch (ParseException e) { e.printStackTrace(); } } else { mTvBdate.setVisibility(View.GONE); } TextView txtProfessionCity = (TextView) view.findViewById(R.id.txtProfessionCity); txtProfessionCity.setText(mArrBdayItems.get(i).getmDeparmentName() + ", " + mArrBdayItems.get(i).getCity()); TextView txtEvent = (TextView) view.findViewById(R.id.txtEvent); txtEvent.setTextColor(Color.parseColor(AppPrefs.getInstance(getActivity()).getOthrCode("ls_cb_rowsection_title_text_color"))); ImageView xIvIconBday = (ImageView) view.findViewById(R.id.xIvIconBday); if (mArrBdayItems.get(i).isBday().equals("1")) { txtEvent.setText("birthday"); xIvIconBday.setImageResource(R.mipmap.birthday); } else if (mArrBdayItems.get(i).isBday().equals("2")) {//if(mArrBdayItems.get(i).isBday().equals("2")){ txtEvent.setText("anniversary"); xIvIconBday.setImageResource(R.mipmap.wedding); } else { txtEvent.setText("anniversary"); xIvIconBday.setImageResource(R.mipmap.wedding); } mTvBdayName.setText(mArrBdayItems.get(i).getUsrName()); mTvBdayName.setSelected(true); imgClose = (ImageView) view.findViewById(R.id.imgClose); imgClose.setTag(mArrBdayItems.get(i)); imgClose.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { CelebrationItem celebrationItem = (CelebrationItem) v.getTag(); System.out.println(" position " + celebrationItem.getItemId()); if (mViewPager.getCurrentItem() == 0) { allArticleFragment.getItemId(celebrationItem); } else { articalListFragment.getItemId(celebrationItem); } lytFlipper.setVisibility(View.GONE); mLayBdayBash.setVisibility(View.GONE); } }); } if (end > 1) { mLayBdayBash.setInAnimation(getActivity(), R.anim.slide_in_flipper); mLayBdayBash.setOutAnimation(getActivity(), R.anim.slide_out_flipper); mLayBdayBash.setFlipInterval(5000); mLayBdayBash.setAutoStart(true); mLayBdayBash.startFlipping(); } } else { lytFlipper.setVisibility(View.GONE); mLayBdayBash.setVisibility(View.GONE); } }*/ //************************************* GET CHANNELS FOR ORGANIZATION ********************************* private void mGetChannelsForOrganization() { if (mArrChnls.size() > 0) mArrChnls.removeAll(mArrChnls); // progressDialog = StaticUtils.callProgress(progressDialog, getActivity());// progressDialog.show(); RestClient.get().getChannels(AppPrefs.getInstance(getActivity()).getAuthCode(), AppPrefs.getInstance(getActivity()).getUid(), AppPrefs.getInstance(getActivity()).getOrgid(),AppPrefs.getInstance(getActivity()).getDepartmentId(), new Callback<Channel>() { @Override public void success(Channel example, Response response) { StaticUtils.printErr("Channel response :: " + example.getStatus()); if (isAdded()) { try { if (example.getStatus().equalsIgnoreCase("1")) { if (mFragTabItem != null && mFragTabItem.size() > 0) mFragTabItem.removeAll(mFragTabItem); HomeScreen.INTEREST_UPDATED = false; TabItem item = new TabItem(); item.setId("0"); item.setTitle(getString(R.string.top_stories)); mFragTabItem.add(item); for (int i = 0; i < example.getData().size(); i++) { Channels channels = new Channels(); TabItem item2 = new TabItem(); channels.setId(example.getData().get(i).getId()); channels.setTitle(example.getData().get(i).getChannelname().toString().toLowerCase().trim()); channels.setOrgId(example.getData().get(i).getOrganizationid()); channels.setOrgName(example.getData().get(i).getOrganization()); channels.setDesc(example.getData().get(i).getDescription()); channels.setModId(example.getData().get(i).getModeratorid()); channels.setModName(example.getData().get(i).getModeratedby()); channels.setStatus(example.getData().get(i).getStatus()); channels.setAllowCmnt(example.getData().get(i).getIsAllowComment()); channels.setDispAuthName(example.getData().get(i).getIsDisplayAuthorName()); channels.setShowDt(example.getData().get(i).getIsShowDateTime()); channels.setAccessToShare(example.getData().get(i).getIsAccessToShare()); channels.setHasDeptAccess(example.getData().get(i).getIsDepartmentAccess()); channels.setItemCrtdDt(example.getData().get(i).getCreated()); channels.setItemCrtdId(example.getData().get(i).getCreatedid()); channels.setItemCrtdBy(example.getData().get(i).getCreatedby()); channels.setUsrCanCreate(example.getData().get(i).getIsUserCreate()); mArrChnls.add(channels); item2.setId(example.getData().get(i).getId()); item2.setTitle(example.getData().get(i).getChannelname().toString().toLowerCase().trim()); item2.setShowFab(example.getData().get(i).getIsUserCreate()); mFragTabItem.add(item2); } int tabPosition = 0; try { for (int i = 0; i < mFragTabItem.size(); i++) { if (getArguments() != null) { if (getArguments().getString("channelid") != null) { if (getArguments().getString("channelid").equalsIgnoreCase(mFragTabItem.get(i).getId())) { tabPosition = i; } } } } } catch (Exception e) { e.printStackTrace(); } mTabLayout.setVisibility(View.VISIBLE); setupViewPager(tabPosition); mViewPager.setOffscreenPageLimit(0); mTabLayout.setViewPager(mViewPager); mTvSelectedTabText = (TextView) mTabLayout.getTabAt(tabPosition).findViewById(R.id.custom_text); mTvSelectedTabText.setTextColor(Color.parseColor(AppPrefs.getInstance(getActivity()).getOthrCode("ls_hzmenu_selected_text_color"))); // StaticUtils.sSetProximaNova(getActivity(), mTvSelectedTabText, getString(R.string.font_bold));// new GetBdayFlipperData().execute(); } else if (example.getStatus().equalsIgnoreCase("-1")) { // if (progressDialog.isShowing() && progressDialog != null)// progressDialog.dismiss(); if (isAdded()) StaticUtils.showMsgDialog(getActivity(), example.getMessage()); } else if (example.getStatus().equalsIgnoreCase("0")) { // if (progressDialog.isShowing() && progressDialog != null)// progressDialog.dismiss(); if (isAdded()) StaticUtils.showMsgDialog(getActivity(), example.getMessage()); } else { // if (progressDialog.isShowing() && progressDialog != null)// progressDialog.dismiss(); if (isAdded()) mAlertDialog(getString(R.string.err_title), getString(R.string.err_msg)); } } catch (Exception e) { e.printStackTrace(); // if (progressDialog.isShowing() && progressDialog != null)// progressDialog.dismiss(); if (isAdded()) mAlertDialog(getString(R.string.err_title), getString(R.string.srv_timeout)); } } } @Override public void failure(RetrofitError retrofitError) { // if (progressDialog.isShowing() && progressDialog != null)// progressDialog.dismiss(); if (isAdded()) mAlertDialog(getString(R.string.err_title), getString(R.string.srv_timeout)); } }); } private void mAlertDialog(final String title, final String text) { StaticUtils.showDialog(getActivity(), title, text, getString(R.string.btn_retry), getString(R.string.btn_cncl), false, new MaterialDialogListener() { @Override public void PositiveMethod(MaterialDialog dialog, DialogAction dialogAction) { dialog.dismiss(); if (ConnectionDetector.getInstance(getActivity()).isOnline()) { // progressDialog = StaticUtils.callProgress(progressDialog, getActivity());// progressDialog.show(); mGetChannelsForOrganization(); } else { mAlertDialog(title, text); } } @Override public void NegativeMethod(MaterialDialog dialog, DialogAction dialogAction) { dialog.dismiss(); } }); } private void mSetTheme() { // mLayBdayBash.setBackgroundColor(Color.parseColor(AppPrefs.getInstance(getActivity()).getOthrCode("ls_middleheader_bg_color"))); mTabLayout.setSelectedIndicatorColors(Color.parseColor(AppPrefs.getInstance(getActivity()).getOthrCode("ls_topheader_bg_color"))); topStoriesLay.setBackgroundColor(Color.parseColor(AppPrefs.getInstance(getActivity()).getOthrCode("ls_bg_color"))); mTabLayout.setBackground(new ColorDrawable(Color.parseColor(AppPrefs.getInstance(getActivity()).getOthrCode("ls_hzmenu_bg_color")))); } // Broad broad; /** * The {@link Tracker} used to record screen views. */ private Tracker mTracker; /** * Return the title of the currently displayed image. * * @return title of image */ private String getCurrentTabTitle() { int position = mViewPager.getCurrentItem(); return mFragTabItem.get(position).getTitle(); } /** * Record a screen view hit for the visible {@link TopStoriesFrag} displayed * inside {@link FragmentPagerAdapter}. */ private void sendTabName() { String name = getCurrentTabTitle(); Log.i("HOME SCREEN", "Setting screen name: " + name); mTracker.setScreenName("Home Screen~" + name); mTracker.send(new HitBuilders.ScreenViewBuilder().build()); } public String getFormattedDate(Date date) { Calendar cal = Calendar.getInstance(); cal.setTime(date); //2nd of march 2015 int day = cal.get(Calendar.DATE); switch (day % 10) { case 1: return new SimpleDateFormat("d'st' MMMM").format(date); case 2: return new SimpleDateFormat("d'nd' MMMM").format(date); case 3: return new SimpleDateFormat("d'rd' MMMM").format(date); default: return new SimpleDateFormat("d'th' MMMM").format(date); } } }
2)CustomViewPager
package com.credencys.goscoop.customfunctions; import android.content.Context; import android.support.v4.view.ViewPager; import android.util.AttributeSet; import android.view.MotionEvent; /** * Created by pranav on 13/9/16. */ public class CustomViewPager extends ViewPager { private boolean enabled; public CustomViewPager(Context context, AttributeSet attrs) { super(context, attrs); this.enabled = true; } @Override public boolean onTouchEvent(MotionEvent event) { if (this.enabled) { return super.onTouchEvent(event); } return false; } @Override public boolean onInterceptTouchEvent(MotionEvent event) { if (this.enabled) { return super.onInterceptTouchEvent(event); } return false; } public void setPagingEnabled(boolean b) { this.enabled = b; } }
3)ArticalListFragement
package com.credencys.goscoop.fragments; import android.app.Dialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.support.design.widget.CoordinatorLayout; import android.support.design.widget.FloatingActionButton; import android.support.v4.app.Fragment; import android.support.v4.content.LocalBroadcastManager; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.RelativeLayout; import android.widget.TextView; import com.afollestad.materialdialogs.DialogAction; import com.afollestad.materialdialogs.MaterialDialog; import com.credencys.goscoop.R; import com.credencys.goscoop.activities.HomeScreen; import com.credencys.goscoop.adapters.ArticalAdpter; import com.credencys.goscoop.customfunctions.ScrollAwareFABBehavior; import com.credencys.goscoop.datamodels.ArticleItem; import com.credencys.goscoop.interfaces.MaterialDialogListener; import com.credencys.goscoop.interfaces.PostDetailCallback; import com.credencys.goscoop.interfaces.PositionInFragment; import com.credencys.goscoop.utils.AppPrefs; import com.credencys.goscoop.utils.ConnectionDetector; import com.credencys.goscoop.utils.GetPostDetails; import com.credencys.goscoop.utils.StaticUtils; import com.credencys.goscoop.webresponses.articledetails.ArticlesDetails; import com.credencys.goscoop.webresponses.articles.Articles; import com.credencys.goscoop.webservices.RestClient; import java.util.ArrayList; import retrofit.Callback; import retrofit.RetrofitError; import retrofit.client.Response; /** * Created by credencys on 09/12/2015. */public class ArticleListFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener, PostDetailCallback, PositionInFragment { private int mPageNumber = 1; private RecyclerView mRecView; private ArrayList<ArticleItem> mArrArticles; private TextView mTvNoArticles; private String mTabId, mChannelName; // private GestureDetectorCompat gestureDetector; private SwipeRefreshLayout mRefreshLayout; // private GetPostDetails getPostDetails; private LinearLayoutManager layoutManager; private ArrayList<ArticleItem> alstArticalItem; private RelativeLayout rlytArtical; private Dialog progressDialog; private ArticalAdpter mAdapter; private boolean isVisible; private boolean isFirstTIme; private GetPostDetails getPostDetails; public ArticleListFragment() { // Required empty public constructor } @Override public void setMenuVisibility(final boolean visible) { super.setMenuVisibility(visible); isVisible = visible; if (visible) { // ... HomeScreen.CHANNEL_ID = getArguments().getString("id"); HomeScreen.CHANNEL_NAME = getArguments().getString("name"); HomeScreen.FRAGPOSITION = getArguments().getString("position"); if (getArguments() != null && getArguments().getString("showFab").equalsIgnoreCase("1")) { if (HomeScreen.FAB_CREATE_ART.getVisibility() == View.GONE) { CoordinatorLayout.LayoutParams p = (CoordinatorLayout.LayoutParams) HomeScreen.FAB_CREATE_ART.getLayoutParams(); p.setBehavior(new ScrollAwareFABBehavior(HomeScreen.CONTEXT_HOME)); HomeScreen.FAB_CREATE_ART.setLayoutParams(p); HomeScreen.FAB_CREATE_ART.show(); HomeScreen.FAB_CREATE_ART.setVisibility(View.VISIBLE); } } else { HomeScreen.FAB_CREATE_ART.hide(); HomeScreen.FAB_CREATE_ART.setVisibility(View.GONE); CoordinatorLayout.LayoutParams p = (CoordinatorLayout.LayoutParams) HomeScreen.FAB_CREATE_ART.getLayoutParams(); p.setBehavior(null); HomeScreen.FAB_CREATE_ART.setLayoutParams(p); } } } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mTabId = getArguments().getString("id"); mChannelName = getArguments().getString("name"); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment getPostDetails = new GetPostDetails(getActivity(), this); View convertView = inflater.inflate(R.layout.all_artical_list, container, false); if (HomeScreen.FAB_CREATE_ART == null) HomeScreen.FAB_CREATE_ART = (FloatingActionButton) getActivity().findViewById(R.id.fab); // gestureDetector = new GestureDetectorCompat(getActivity(), new RecyclerViewDemoOnGestureListener()); mRecView = (RecyclerView) convertView.findViewById(R.id.xListPosts); layoutManager = new LinearLayoutManager(getActivity()); layoutManager.setOrientation(LinearLayoutManager.VERTICAL); mRecView.setLayoutManager(layoutManager); mRefreshLayout = (SwipeRefreshLayout) convertView.findViewById(R.id.swipeRefreshLayout); mTvNoArticles = (TextView) convertView.findViewById(R.id.xTvNoPost); mTvNoArticles.setVisibility(View.GONE); alstArticalItem = new ArrayList<>(); alstArticalItem = new ArrayList<>(); rlytArtical = (RelativeLayout) convertView.findViewById(R.id.rlytArtical); mArrArticles = new ArrayList<>(); mRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_bright, android.R.color.holo_green_light, android.R.color.holo_orange_light, android.R.color.holo_red_light); mRefreshLayout.setOnRefreshListener(this); isFirstTIme = true; if (ConnectionDetector.getInstance(getActivity()).isOnline()) { mGetArticles(false); } else { StaticUtils.showMsgDialogTitle(getActivity(), getActivity().getResources().getString(R.string.no_internet_title), getActivity().getResources().getString(R.string.no_internet_title)); } return convertView; } //************************************* GET ARTICLES FOR CHANNELS ********************************* public void mGetArticles(final boolean isPaging) { if (progressDialog != null && progressDialog.isShowing()) { progressDialog.dismiss(); } if (isFirstTIme) { mRefreshLayout.setRefreshing(false); progressDialog = StaticUtils.callProgress(progressDialog, getActivity()); progressDialog.show(); } else { mRefreshLayout.setRefreshing(false); } RestClient.get().getArticles(AppPrefs.getInstance(getActivity()).getAuthCode(), AppPrefs.getInstance(getActivity()).getOrgid(), mTabId, Integer.toString(mPageNumber), AppPrefs.getInstance(getActivity()).getUid(), AppPrefs.getInstance(getActivity()).getDepartmentId(), new Callback<Articles>() { @Override public void success(final Articles example, Response response) { if (isAdded()) { Log.e("response ", " " + example.toString()); Log.v("TAG", "success..........."); if (progressDialog.isShowing() && progressDialog != null) progressDialog.dismiss(); if (mAdapter != null && isFirstTIme) { mArrArticles.clear(); alstArticalItem.clear(); } try { if (example.getStatus().equalsIgnoreCase("1")) { //REMOVE IN FINAL BUILD for (int i = 0; i < example.getData().size(); i++) { if (example.getData().size() > 0) { ArticleItem articles = new ArticleItem(); articles.setId(i); articles.setItemId(example.getData().get(i).getId()); articles.setTitle(example.getData().get(i).getArticletitle()); articles.setOrgId(example.getData().get(i).getOrganizationid()); articles.setOrgName(example.getData().get(i).getOrganization()); articles.setDesc(example.getData().get(i).getDescription()); articles.setModId(example.getData().get(i).getModeratorid()); articles.setModName(example.getData().get(i).getModeratedby()); articles.setStatus(example.getData().get(i).getStatus()); articles.setAllowCmnt(example.getData().get(i).getIsAllowComment()); articles.setDispAuthName(example.getData().get(i).getIsDisplayAuthorName()); articles.setShowDt(example.getData().get(i).getIsShowDateTime()); articles.setAccessToShare(example.getData().get(i).getIsAccessToShare()); articles.setHasDeptAccess(example.getData().get(i).getIsDepartmentAccess()); articles.setItemCrtdDt(example.getData().get(i).getCreated()); articles.setItemCrtdId(example.getData().get(i).getCreatedid()); articles.setItemCrtdBy(example.getData().get(i).getCreatedby()); articles.setChnlId(example.getData().get(i).getChannelid()); articles.setChnlName(example.getData().get(i).getChannel()); articles.setImgUrl(example.getData().get(i).getArticleimage()); articles.setImgThumbUrl(example.getData().get(i).getArticleThumbimage()); articles.setItemPostAnonym(example.getData().get(i).getIsPostAnonymous()); articles.setItemReviewRate(example.getData().get(i).getIsReviewRate()); articles.setIsRssFeed(example.getData().get(i).getIsRssFeed()); articles.setVideoUrl(example.getData().get(i).getIsVideoUrl()); articles.setmCreateImage(example.getData().get(i).getCreatedimage()); articles.setmTotalComments(example.getData().get(i).getTotalcomments()); Log.e("Comment", "Commentlist::" + example.getData().get(i).getTotalcomments()); String strURL = example.getData().get(i).getArticleimage(); if (alstArticalItem != null) { if (alstArticalItem.size() < 3) { if (strURL != null && strURL.length() > 0) { alstArticalItem.add(articles); } else { mArrArticles.add(articles); } } else { mArrArticles.add(articles); } } } else { StaticUtils.showMsgDialog(getActivity(), getResources().getString(R.string.no_artical_found)); } } mSetupPostList(); if (example.getStatus() != null && example.getData().size() > 0) { mRecView.setVisibility(View.VISIBLE); } else { if (mAdapter != null) { mAdapter.loading = true; mAdapter.notifyDataSetChanged(); } StaticUtils.showMsgDialog(getActivity(), getResources().getString(R.string.no_artical_found)); } } else if (example.getStatus().equalsIgnoreCase("-1")) { mSetupPostList(); if (isAdded()) { if (mAdapter != null) { mAdapter.loading = true; mAdapter.notifyDataSetChanged(); } mRefreshLayout.setRefreshing(false); } if (alstArticalItem.size() == 0 && mArrArticles.size() == 0) { getPosition(-2); } } else if (example.getStatus().equalsIgnoreCase("0")) { if (isAdded()) { if (mAdapter != null) { mAdapter.loading = true; mAdapter.notifyDataSetChanged(); } if (!isPaging) mRefreshLayout.setRefreshing(false); StaticUtils.showMsgDialog(getActivity(), example.getMessage()); } } else { if (isAdded()) { if (mAdapter != null) { mAdapter.loading = true; mAdapter.notifyDataSetChanged(); } if (!isPaging) mRefreshLayout.setRefreshing(false); StaticUtils.showMsgDialog(getActivity(), getString(R.string.err_msg)); } } } catch (Exception e) { e.printStackTrace(); if (isAdded()) { if (mAdapter != null) { mAdapter.loading = true; mAdapter.notifyDataSetChanged(); } if (!isPaging) mRefreshLayout.setRefreshing(false); StaticUtils.showMsgDialog(getActivity(), getString(R.string.err_msg)); } } } } @Override public void failure(RetrofitError retrofitError) { if (isAdded()) { if (progressDialog != null && progressDialog.isShowing()) { progressDialog.dismiss(); } if (!isPaging) mRefreshLayout.setRefreshing(false); try { mArrArticles.remove(mArrArticles.size() - 1); mAdapter.notifyItemRemoved(mArrArticles.size()); } catch (Exception e) { e.printStackTrace(); } StaticUtils.showMsgDialog(getActivity(), getString(R.string.srv_timeout)); } } }); } private void mSetupPostList() { if (mAdapter == null) { mAdapter = new ArticalAdpter(getActivity(), mRecView, mArrArticles, alstArticalItem, this); mRecView.setAdapter(mAdapter); mAdapter.loading = false; } else { mAdapter.notifyDataSetChanged(); mAdapter.loading = false; } mRefreshLayout.setRefreshing(false); mAdapter.setOnLoadMoreListener(new ArticalAdpter.OnLoadMoreListener() { @Override public void onLoadMore() { if (ConnectionDetector.getInstance(getActivity()).isOnline()) { if (!isFirstTIme) { mPageNumber++; mGetArticles(true); } } } }); isFirstTIme = false; } @Override public void onStart() { if (mAdapter != null) { Log.e("list onResume ", "onResume"); mAdapter.notifyDataSetChanged(); } super.onStart(); } @Override public void onRefresh() { if (mArrArticles != null) { isFirstTIme = true; mPageNumber = 1; mArrArticles.clear(); alstArticalItem.clear(); mAdapter = null; // mAdapter.loading = true;// mAdapter.notifyDataSetChanged(); mGetArticles(false); } else mRefreshLayout.setRefreshing(false); } @Override public void onTaskCompleted(String message) { if (!message.equalsIgnoreCase("success") && isAdded()) StaticUtils.showMsgDialog(getActivity(), getString(R.string.srv_timeout)); } @Override public void onTaskCompleted(String message, ArticlesDetails item) { } /* private class RecyclerViewDemoOnGestureListener extends GestureDetector.SimpleOnGestureListener { @Override public boolean onSingleTapConfirmed(MotionEvent e) { View view = mRecView.findChildViewUnder(e.getX(), e.getY()); int idx = mRecView.getChildAdapterPosition(view); if (idx != -1) { if (ConnectionDetector.getInstance(getActivity()).isOnline()) { getPostDetails.mCancelPrevious(); int position=0 if(mArrArticles.size()==1) position=0; else position=idx-1; getPostDetails.mGetArticleDetails(mArrArticles.get(position).getItemId(), mArrArticles.get(idx).getIsRssFeed(), mArrArticles.get(idx).getVideoUrl(), "activities.HomeScreen"); } else StaticUtils.showMsgDialog(getActivity(), getString(R.string.no_internet)); } return super.onSingleTapConfirmed(e); } public void onLongPress(MotionEvent e) { super.onLongPress(e); } }*/ private void mNoInternetDialog(final String title, final String text) { if (isAdded()) { StaticUtils.showDialog(getActivity(), title, text, getString(R.string.btn_retry), getString(R.string.btn_cncl), false, new MaterialDialogListener() { @Override public void PositiveMethod(MaterialDialog dialog, DialogAction dialogAction) { dialog.dismiss(); mPageNumber = 1; if (ConnectionDetector.getInstance(getActivity()).isOnline()) { // mProgView.setVisibility(View.VISIBLE);// mRelLayProgView.setVisibility(View.VISIBLE); mGetArticles(false); } else { StaticUtils.showMsgDialogTitle(getActivity(), getActivity().getResources().getString(R.string.no_internet_title), getActivity().getResources().getString(R.string.no_internet_title)); } } @Override public void NegativeMethod(MaterialDialog dialog, DialogAction dialogAction) { dialog.dismiss(); } }); } } @Override public void getPosition(int position) { if (position >= 0) { if (ConnectionDetector.getInstance(getActivity()).isOnline()) { getPostDetails.mCancelPrevious(); getPostDetails.mGetArticleDetails(mArrArticles.get(position).getItemId(), mArrArticles.get(position).getIsRssFeed(), mArrArticles.get(position).getVideoUrl(), "activities.HomeScreen"); } else { if (isAdded()) StaticUtils.showMsgDialogTitle(getActivity(), getActivity().getResources().getString(R.string.no_internet_title), getActivity().getResources().getString(R.string.no_internet_msg)); } } else if (position == -1) { mTvNoArticles.setVisibility(View.VISIBLE); mRecView.setVisibility(View.GONE); } else if (position == -2) { mTvNoArticles.setVisibility(View.VISIBLE); mTvNoArticles.bringToFront(); } else if (position == -3) { mTvNoArticles.setVisibility(View.GONE); mRecView.setVisibility(View.VISIBLE); } } public static final String BROADCAST_ACTION = "NotifyAdpter"; @Override public void onResume() { super.onResume(); LocalBroadcastManager.getInstance(getActivity()).registerReceiver(receiver, new IntentFilter(BROADCAST_ACTION)); } private BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { boolean notify = intent.getBooleanExtra("notify", false); Log.e("notify ", "" + notify); if (notify) { mAdapter.setAlstBirthday(); mAdapter.notifyDataSetChanged(); } } }; @Override public void onDestroy() { super.onDestroy(); if (isAdded()) LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(receiver); } }
No comments:
Post a Comment