<|start_filename|>app/src/main/java/com/YC2010/MyClass/model/LectureSectionObject.java<|end_filename|>
package com.YC2010.MyClass.model;

import android.os.Parcel;
import android.os.Parcelable;

/**
 * Created by Danny on 2015/10/17.
 */
public class LectureSectionObject implements Parcelable {
    private String number;
    private String section;
    private String time;
    private String professor;
    private String location;
    private String capacity;
    private String total;
    private boolean isOnline;

    public LectureSectionObject(String number, String section, String time, String professor, String location, String capacity, String total, boolean isOnline) {
        this.number = number;
        this.section = section;
        this.time = time;
        this.professor = professor;
        this.location = location;
        this.capacity = capacity;
        this.total = total;
        this.isOnline = isOnline;
    }

    public LectureSectionObject() {}

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(number);
        dest.writeString(section);
        dest.writeString(time);
        dest.writeString(professor);
        dest.writeString(location);
        dest.writeString(capacity);
        dest.writeString(total);
        dest.writeByte((byte) (isOnline ? 1 : 0));
    }

    public LectureSectionObject(Parcel src) {
        this.number = src.readString();
        this.section = src.readString();
        this.time = src.readString();
        this.professor = src.readString();
        this.location = src.readString();
        this.capacity = src.readString();
        this.total = src.readString();
        this.isOnline = src.readByte() != 0;
    }

    public static final Creator CREATOR = new Creator() {
        @Override
        public LectureSectionObject createFromParcel(Parcel source) {
            return new LectureSectionObject(source);
        }

        @Override
        public LectureSectionObject[] newArray(int size) {
            return new LectureSectionObject[size];
        }
    };

    public void setNumber(String number) {
        this.number = number;
    }

    public void setCapacity(String capacity) {
        this.capacity = capacity;
    }

    public void setLocation(String location) {
        this.location = location;
    }

    public void setTime(String time) {
        this.time = time;
    }

    public void setSection(String section) {
        this.section = section;
    }

    public void setTotal(String total) {
        this.total = total;
    }

    public void setProfessor(String professor) {
        this.professor = professor;
    }

    public void setIsOnline(boolean isOnline) {
        this.isOnline = isOnline;
    }

    public String getNumber() {
        return number;
    }

    public String getSection() {
        return section;
    }

    public String getTime() {
        return time;
    }

    public String getProfessor() {
        return professor;
    }

    public String getLocation() {
        return location;
    }

    public String getCapacity() {
        return capacity;
    }

    public String getTotal() {
        return total;
    }

    public boolean isOnline() {
        return isOnline;
    }
}


<|start_filename|>app/src/main/java/com/YC2010/MyClass/utils/Constants.java<|end_filename|>
package com.YC2010.MyClass.utils;

import com.YC2010.MyClass.model.Reminder_item;

import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.UUID;

/**
 * Created by Danny on 2015/6/27.
 */

public class Constants {
    public static String UWAPIROOT = "https://api.uwaterloo.ca/v2/";
    public static List<Reminder_item> holiday_2015;
    public static List<Reminder_item> sample_reminder;

    public static String lectureSectionObjectListKey = "LEC_OBJECTS";
    public static String testObjectListKey = "TST_OBJECTS";
    public static String tutorialObjectListKey = "TUT_OBJECTS";
    public static String finalObjectListKey = "FINAL_OBJECTS";

    // default term value
    public static Integer defaultCurTermNum = 1161;
    public static String defaultCurTermName = "Winter 2016 (Current)";
    public static Integer defaultNextTermNum = 1165;
    public static String defaultNextTermName = "Spring 2016 (Next)";

    // temporarily hardcoded
    // Note: month off by one because of unix time standard
    public static GregorianCalendar nextTermStartDate = new GregorianCalendar(2016, 4, 2);



    public static List<Reminder_item> get_sample_reminder(){
        sample_reminder = new ArrayList<>();
        Reminder_item tmp = new Reminder_item(UUID.randomUUID().toString(),
                "Final end","", 2015, 7, 15, "d");
        sample_reminder.add(tmp);
        tmp = new Reminder_item(UUID.randomUUID().toString(),
                "Next term start","", 2015, 8, 14, "d");
        sample_reminder.add(tmp);
        tmp = new Reminder_item(UUID.randomUUID().toString(),
                "First penalty end","", 2015, 9, 3, "d");
        sample_reminder.add(tmp);
        tmp = new Reminder_item(UUID.randomUUID().toString(),
                "Late fee for fall","", 2015, 7, 28, "d");
        sample_reminder.add(tmp);

        return sample_reminder;
    }

    public static List<Reminder_item> get_holidays(){
        holiday_2015 = new ArrayList<>();
        Reminder_item tmp = new Reminder_item(UUID.randomUUID().toString(),
                "Civic Holiday","", 2015, 7, 3, "d");
        holiday_2015.add(tmp);
        tmp = new Reminder_item(UUID.randomUUID().toString(),
                "Labour Day","", 2015, 8, 7, "d");
        holiday_2015.add(tmp);
        tmp = new Reminder_item(UUID.randomUUID().toString(),
                "Thanksgiving","", 2015, 9, 12, "d");
        holiday_2015.add(tmp);
        tmp = new Reminder_item(UUID.randomUUID().toString(),
                "Christmas","", 2015, 11, 25, "d");
        holiday_2015.add(tmp);

        tmp = new Reminder_item(UUID.randomUUID().toString(),
                "Boxing Day","", 2015, 11, 28, "d");
        holiday_2015.add(tmp);

        return holiday_2015;
    }
}


<|start_filename|>app/src/main/java/com/YC2010/MyClass/ui/adapters/FinalsListAdapter.java<|end_filename|>
package com.YC2010.MyClass.ui.adapters;

import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.YC2010.MyClass.model.FinalObject;
import com.YC2010.MyClass.utils.Constants;
import com.YC2010.MyClass.R;

import java.util.ArrayList;

public class FinalsListAdapter extends BaseAdapter {
    ArrayList<FinalObject> mArrayList;
    Context mContext;
    LayoutInflater mLayoutInflater;

    public FinalsListAdapter(Context context, int textViewResourceId, Bundle bundle) {
        mLayoutInflater = LayoutInflater.from(context);
        mArrayList = bundle.getParcelableArrayList(Constants.finalObjectListKey);
        mContext = context;
        Log.d("SectionListAdapter", "Course name is " + bundle.getString("courseName"));
    }

    @Override
    public FinalObject getItem(int i) {
        return mArrayList.get(i);
    }

    @Override
    public int getCount() {
        return mArrayList != null ? mArrayList.size() : 0;
    }

    @Override
    public long getItemId(int arg0) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        //Log.d("SectionListAdapter", "enter getView");
        View v = convertView;

        v = mLayoutInflater.inflate(R.layout.section_item, null);


        Log.d("SectionListAdapter", "position is " + position);

        TextView date = (TextView) v.findViewById(R.id.section_item_capacity);
        TextView sec = (TextView) v.findViewById(R.id.section_item_lec);
        TextView loc = (TextView) v.findViewById(R.id.section_item_loc);
        TextView time = (TextView) v.findViewById(R.id.section_item_time);

        FinalObject finalInfo = getItem(position);

        sec.setText(finalInfo.getSection());

        if (!finalInfo.isOnline()) {
            time.setText(finalInfo.getTime());
            loc.setText(finalInfo.getLocation());
            date.setText(finalInfo.getDate());
        }

        return v;
    }

}

<|start_filename|>app/src/main/java/com/YC2010/MyClass/callbacks/SimpleItemTouchHelperCallback.java<|end_filename|>
/*
 * Copyright (C) 2015 <NAME>
 *
 * 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.YC2010.MyClass.callbacks;

import android.support.design.widget.Snackbar;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.view.View;

import com.YC2010.MyClass.ui.adapters.ItemTouchHelperAdapter;


public class SimpleItemTouchHelperCallback extends ItemTouchHelper.Callback {

    private final ItemTouchHelperAdapter mAdapter;
    private final View mView;

    public SimpleItemTouchHelperCallback(ItemTouchHelperAdapter adapter, View view) {
        mAdapter = adapter;
        mView = view;
    }

    @Override
    public boolean isLongPressDragEnabled() {
        return true;
    }

    @Override
    public boolean isItemViewSwipeEnabled() {
        return true;
    }

    @Override
    public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
        int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
        int swipeFlags = ItemTouchHelper.START | ItemTouchHelper.END;
        return makeMovementFlags(dragFlags, swipeFlags);
    }

    @Override
    public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder,
                          RecyclerView.ViewHolder target) {
        return true;
    }

    @Override
    public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
        mAdapter.onItemDismiss(viewHolder.getAdapterPosition());


        // show snackBar Event updated
        Snackbar.make(mView, "Event Removed", Snackbar.LENGTH_SHORT)
                .show();
    }

}


<|start_filename|>app/src/main/java/com/YC2010/MyClass/ui/fragments/ReminderFragment.java<|end_filename|>
package com.YC2010.MyClass.ui.fragments;

import android.app.AlertDialog;
import android.app.Fragment;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.util.Log;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TimePicker;

import com.YC2010.MyClass.R;
import com.YC2010.MyClass.callbacks.AsyncTaskCallbackInterface;
import com.YC2010.MyClass.callbacks.SimpleItemTouchHelperCallback;
import com.YC2010.MyClass.data.CoursesDBHandler;
import com.YC2010.MyClass.data.ReminderDBHandler;
import com.YC2010.MyClass.data.fetchtasks.FinalsFetchTask;
import com.YC2010.MyClass.model.CourseInfo;
import com.YC2010.MyClass.model.Reminder_item;
import com.YC2010.MyClass.ui.activities.MainActivity;
import com.YC2010.MyClass.ui.adapters.ItemTouchHelperAdapter;
import com.YC2010.MyClass.ui.adapters.Reminder_Adapter;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * Created by Jason on 2015-05-25.
 */
public class ReminderFragment extends Fragment {
    private RecyclerView mRecyclerView;
    private RecyclerView.Adapter mAdapter;
    private RecyclerView.LayoutManager mLayoutManager;
    private ItemTouchHelper mItemTouchHelper;

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

    }

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

        //return inflater.inflate(R.layout.fragment_reminder, container, false);

        // Inflate the layout for this fragment
        View rootView = inflater.inflate(R.layout.fragment_reminder, container, false);

        // Make this {@link Fragment} listen for changes in both FABs.
        //FloatingActionButton fab1 = (FloatingActionButton) rootView.findViewById(R.id.fab_1);
        //fab1.setOnCheckedChangeListener(this);

        // RecyclerView:
        mRecyclerView = (RecyclerView) rootView.findViewById(R.id.reminder_recycler_view);

        // use this setting to improve performance if you know that changes
        // in content do not change the layout size of the RecyclerView
        mRecyclerView.setHasFixedSize(true);

        // use a linear layout manager
        mLayoutManager = new LinearLayoutManager(getActivity());
        mRecyclerView.setLayoutManager(mLayoutManager);

        // get reminder from db
        ReminderDBHandler db = new ReminderDBHandler(getActivity());
        List<Reminder_item> myDataset = db.getAllReminders();


        // specify an adapter (see also next example)
        mAdapter = new Reminder_Adapter(myDataset, getActivity());

        mAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
            @Override
            public void onChanged() {
                super.onChanged();
                Log.d("CoursesFragment", "Data set changed");
            }
        });

        mRecyclerView.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), mRecyclerView, new ClickListener() {
            @Override
            public void onClick(final View view, final int position) {
                Log.d("mRecyclerView", "enter onclick");
                // 1. Instantiate an AlertDialog.Builder with its constructor
                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

                // 2. Chain together various setter methods to set the dialog characteristics
                builder.setTitle(R.string.edit_Event_dialog_title);
                builder.setView(R.layout.dialog_add_event);


                builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        // User clicked confirm button
                    }
                });
                builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        // User clicked cancel button

                    }
                });
                builder.setNeutralButton(R.string.delete, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        // User clicked delete button
                        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                        builder.setTitle("Delete this reminder?");

                        builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {

                                RecyclerView recyclerView = (RecyclerView) getActivity().findViewById(R.id.reminder_recycler_view);
                                Reminder_Adapter adapter = (Reminder_Adapter) recyclerView.getAdapter();
                                adapter.removeAt(position);

                                // show snackBar
                                Snackbar.make(view, "Event Removed", Snackbar.LENGTH_SHORT)
                                        .show();
                            }
                        });
                        builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                // nothing
                            }
                        });
                        AlertDialog confirmation = builder.create();

                        confirmation.show();
                        confirmation.getButton(confirmation.BUTTON_NEGATIVE).setTextColor(getResources().getColor(R.color.myPrimaryColor));
                        confirmation.getButton(confirmation.BUTTON_POSITIVE).setTextColor(getResources().getColor(R.color.myPrimaryColor));
                    }
                });
                // 3. Get the AlertDialog from create()
                final AlertDialog dialog = builder.create();
                dialog.show();


                // button for picking date
                // create date picker dialog
                final Button pick_date = (Button) dialog.findViewById(R.id.dateBtn);

                // fetch data from reminder db
                final ReminderDBHandler db = new ReminderDBHandler(getActivity());

                //int year, month, day, hour, minute;

                pick_date.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(final View v) {
                        AlertDialog.Builder datePicker_builder = new AlertDialog.Builder(v.getContext());
                        datePicker_builder.setView(R.layout.dialog_add_event_date_picker);


                        datePicker_builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                // User clicked cancel button

                            }
                        });
                        final AlertDialog DatePicker_Dialog;
                        DatePicker_Dialog = datePicker_builder.create();
                        DatePicker_Dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);


                        DatePicker_Dialog.setButton(DatePicker_Dialog.BUTTON_POSITIVE, v.getContext().getResources().getString(R.string.ok), new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                final DatePicker mDatePicker = (DatePicker) DatePicker_Dialog.findViewById(R.id.datePicker);

                                // saving into to SharedPreferences
                                SharedPreferences new_event_dialog_buffer = v.getContext().getSharedPreferences("new_event_dialog_buffer", 0);
                                SharedPreferences.Editor buffer_editor = new_event_dialog_buffer.edit();
                                buffer_editor.putInt("year", mDatePicker.getYear());
                                buffer_editor.putInt("month", mDatePicker.getMonth());
                                // Counting of months in the Calendar class is zero based,
                                // so when we display, we add by one
                                Log.d("buffer_editor", "Month is : " + mDatePicker.getMonth() + 1);
                                buffer_editor.putInt("day", mDatePicker.getDayOfMonth());
                                buffer_editor.apply();

                                int month = mDatePicker.getMonth() + 1;
                                String date = mDatePicker.getYear() + "-" + month + "-" + mDatePicker.getDayOfMonth();
                                //editor.putString("new_event_dialog_buffer", date);

                                //editor.apply();
                                pick_date.setText(date);
                                pick_date.setTextSize(22);
                            }
                        });

                        DatePicker_Dialog.show();
                        DatePicker_Dialog.getButton(DatePicker_Dialog.BUTTON_NEGATIVE).setTextColor(v.getContext().getResources().getColor(R.color.myPrimaryColor));
                        DatePicker_Dialog.getButton(DatePicker_Dialog.BUTTON_POSITIVE).setTextColor(v.getContext().getResources().getColor(R.color.myPrimaryColor));

                    }
                });


                // button for picking time
                // create date picker dialog
                final Button pick_time = (Button) dialog.findViewById(R.id.TimeBtn);
                pick_time.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(final View v) {
                        AlertDialog.Builder timePicker_builder = new AlertDialog.Builder(v.getContext());
                        timePicker_builder.setView(R.layout.dialog_add_event_time_picker);
                        timePicker_builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                // User clicked cancel button

                            }
                        });
                        final AlertDialog TimePicker_Dialog = timePicker_builder.create();
                        TimePicker_Dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);

                        TimePicker_Dialog.setButton(TimePicker_Dialog.BUTTON_POSITIVE, v.getContext().getString(R.string.ok), new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                final TimePicker mTimePicker = (TimePicker) TimePicker_Dialog.findViewById(R.id.timePicker);

                                // saving info to SharedPreferences
                                SharedPreferences new_event_dialog_buffer = v.getContext().getSharedPreferences("new_event_dialog_buffer", 0);
                                SharedPreferences.Editor buffer_editor = new_event_dialog_buffer.edit();
                                buffer_editor.putInt("hour", mTimePicker.getCurrentHour());
                                buffer_editor.putInt("minute", mTimePicker.getCurrentMinute());
                                buffer_editor.apply();
                                //hour = mTimePicker.getCurrentHour();
                                //minute = mTimePicker.getCurrentMinute();
                                String minute = "" + mTimePicker.getCurrentMinute();
                                if (mTimePicker.getCurrentMinute() < 10) minute = "0" + minute;
                                String time = mTimePicker.getCurrentHour() + " : " + minute;

                                //editor.putString("new_event_dialog_buffer", time);
                                //editor.apply();
                                pick_time.setText(time);
                                pick_time.setTextSize(32);
                            }
                        });

                        TimePicker_Dialog.show();
                        TimePicker_Dialog.getButton(TimePicker_Dialog.BUTTON_NEGATIVE).setTextColor(v.getContext().getResources().getColor(R.color.myPrimaryColor));
                        TimePicker_Dialog.getButton(TimePicker_Dialog.BUTTON_POSITIVE).setTextColor(v.getContext().getResources().getColor(R.color.myPrimaryColor));
                    }
                });
                dialog.getButton(dialog.BUTTON_NEGATIVE).setTextColor(getResources().getColor(R.color.myPrimaryColor));
                dialog.getButton(dialog.BUTTON_POSITIVE).setTextColor(getResources().getColor(R.color.myPrimaryColor));
                dialog.getButton(dialog.BUTTON_NEUTRAL).setTextColor(getResources().getColor(R.color.fab_color_1));

                // insert into database

                final EditText event_name = (EditText) dialog.findViewById(R.id.event_name);
                final EditText event_location = (EditText) dialog.findViewById(R.id.event_location);

                dialog.getButton(dialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
                    public void onClick(View view) {
                        // User clicked confirm button
                        SharedPreferences new_event_dialog_buffer = view.getContext().getSharedPreferences("new_event_dialog_buffer", 0);
                        SharedPreferences.Editor buffer_editor = new_event_dialog_buffer.edit();
                        Log.d("FAB", "Month is : " + new_event_dialog_buffer.getInt("month", 0));
                        Log.d("FAB", "Day is : " + new_event_dialog_buffer.getInt("day", 0));
                        db.addReminder(new Reminder_item(
                                UUID.randomUUID().toString(),
                                event_name.getText().toString(),
                                event_location.getText().toString(),
                                new_event_dialog_buffer.getInt("year", 0),
                                new_event_dialog_buffer.getInt("month", 0),
                                new_event_dialog_buffer.getInt("day", 0),
                                new_event_dialog_buffer.getInt("hour", 0),
                                new_event_dialog_buffer.getInt("minute", 0),
                                "c"
                        ));
                        buffer_editor.clear().apply();

                        MainActivity mainActivity = (MainActivity) getActivity();
                        RecyclerView recyclerView = (RecyclerView) mainActivity.findViewById(R.id.reminder_recycler_view);

                        if (recyclerView != null) {
                            Reminder_Adapter adapter = (Reminder_Adapter) recyclerView.getAdapter();
                            adapter.updateView();
                        }

                        dialog.dismiss();

                        // show snackBar Event updated
                        Snackbar.make(view, "Event Updated", Snackbar.LENGTH_SHORT)
                                .show();

                    }
                });
            }

            @Override
            public void onLongClick(final View view, final int position) {
                Log.d("mRecyclerView", "enter onlongclick");

                // vibrate
                Vibrator v = (Vibrator) getActivity().getSystemService(Context.VIBRATOR_SERVICE);
                v.vibrate(10);

                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                builder.setTitle("Delete this reminder?");

                builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                        RecyclerView recyclerView = (RecyclerView) getActivity().findViewById(R.id.reminder_recycler_view);
                        Reminder_Adapter adapter = (Reminder_Adapter) recyclerView.getAdapter();
                        adapter.removeAt(position);

                        // show snackBar
                        Snackbar.make(view, "Event Removed", Snackbar.LENGTH_SHORT)
                                .show();
                    }
                });
                builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        // nothing
                    }
                });
                AlertDialog confirmation = builder.create();

                confirmation.show();
                confirmation.getButton(confirmation.BUTTON_NEGATIVE).setTextColor(getResources().getColor(R.color.myPrimaryColor));
                confirmation.getButton(confirmation.BUTTON_POSITIVE).setTextColor(getResources().getColor(R.color.myPrimaryColor));
            }
        }));

        mRecyclerView.setAdapter(mAdapter);
        ItemTouchHelper.Callback callback =
                new SimpleItemTouchHelperCallback((ItemTouchHelperAdapter) mAdapter, rootView);
        mItemTouchHelper  = new ItemTouchHelper(callback);
        mItemTouchHelper.attachToRecyclerView(mRecyclerView);

        return rootView;
    }

    public static interface ClickListener {
        public void onClick(View view, int position);

        public void onLongClick(View view, int position);
    }

    static class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {

        private GestureDetector gestureDetector;
        private ClickListener clickListener;

        public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final ClickListener clickListener) {
            this.clickListener = clickListener;
            gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
                @Override
                public boolean onSingleTapUp(MotionEvent e) {
                    return true;
                }

                @Override
                public void onLongPress(MotionEvent e) {
                    View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
                    if (child != null && clickListener != null) {
                        clickListener.onLongClick(child, recyclerView.getChildLayoutPosition(child));
                    }
                }
            });
        }

        @Override
        public boolean onInterceptTouchEvent(final RecyclerView rv, MotionEvent e) {

            final View child = rv.findChildViewUnder(e.getX(), e.getY());
            if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
                //Log.d("onInterceptTouchEvent", "before delay");
                // delay 100ms for displaying ripple effect
                Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    public void run() {
                        //write the code here which you want to run after 500 milliseconds
                        //Log.d("onInterceptTouchEvent", "delayed");
                        clickListener.onClick(child, rv.getChildLayoutPosition(child));
                    }
                }, 200);
            }

            return false;
        }

        @Override
        public void onTouchEvent(RecyclerView rv, MotionEvent e) {
        }

        @Override
        public void onRequestDisallowInterceptTouchEvent(boolean bool) {
        }
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        getActivity().getMenuInflater().inflate(R.menu.reminder_menu, menu);
        super.onCreateOptionsMenu(menu, inflater);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.Import_final_setting){
            try {
                // get courses
                CoursesDBHandler db = new CoursesDBHandler(getActivity());
                List<CourseInfo> myCourses = db.getAllCourses(getActivity().getSharedPreferences("TERMS", getActivity().MODE_PRIVATE).getInt("CURRENT_TERM", 0));
                db.close();
                List <String> course_names = new ArrayList<>();
                List <String> course_secs = new ArrayList<>();
                for (int i = 0; i < myCourses.size(); i++) {
                    course_names.add(myCourses.get(i).getCourseName());
                    course_secs.add(myCourses.get(i).getCourseSec());
                }

                FinalsFetchTask finalsFetchTask = new FinalsFetchTask(getActivity(), new AsyncTaskCallbackInterface() {
                    @Override
                    public void onOperationComplete(Bundle bundle) {
                        RecyclerView recyclerView = (RecyclerView) getActivity().findViewById(R.id.reminder_recycler_view);
                        if (recyclerView != null) {
                            Reminder_Adapter adapter = (Reminder_Adapter) recyclerView.getAdapter();
                            adapter.updateView();
                        }

                        // show snackBar
                        Snackbar.make(getView(), "Final exams imported", Snackbar.LENGTH_SHORT)
                                .show();
                    }
                });
                finalsFetchTask.execute(course_names, course_secs);




            }
            catch (Exception e) {
                e.printStackTrace();
            }
        }


        return super.onOptionsItemSelected(item);
    }


}


<|start_filename|>app/src/main/java/com/YC2010/MyClass/data/fetchtasks/CatalogNumFetchTask.java<|end_filename|>
package com.YC2010.MyClass.data.fetchtasks;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;

import com.YC2010.MyClass.callbacks.AsyncTaskCallbackInterface;
import com.YC2010.MyClass.data.Connections;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;

/**
 * Created by Danny on 2015/6/27.
 */
public class CatalogNumFetchTask extends AsyncTask<String, Void, Bundle> {

    private Activity mActivity;
    AsyncTaskCallbackInterface mAsyncTaskCallbackInterface;
    private ArrayList<String> mCatalogNum_arraylist = new ArrayList<>();
    private String mSubject;
    public CatalogNumFetchTask(String subject, AsyncTaskCallbackInterface asyncTaskCallbackInterface) {
        mAsyncTaskCallbackInterface = asyncTaskCallbackInterface;
        mSubject = subject;
    }

    @Override
    protected Bundle doInBackground(String...params) {
        Bundle result = new Bundle();
        fetchCourse(result);

        return result;
    }

    private Bundle fetchCourse(Bundle bundle) {
        try{
            String url = Connections.getCatalogNumURL(mSubject);

            JSONObject jsonObject = Connections.getJSON_from_url(url);
            JSONArray subject_array = jsonObject.getJSONArray("data");
            Log.d("SubjectFetchTask", "subject array is " + subject_array.length());

            for(int i = 0; i < subject_array.length(); i++){
                JSONObject subject = subject_array.getJSONObject(i);
                mCatalogNum_arraylist.add(i,mSubject + " " +  subject.getString("catalog_number"));
            }

            bundle.putStringArrayList("CatalogNum_arraylist", mCatalogNum_arraylist);

            return bundle;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return bundle;
    }

    @Override
    protected void onPostExecute(Bundle bundle) {
        mAsyncTaskCallbackInterface.onOperationComplete(bundle);
    }


}


<|start_filename|>app/src/main/java/com/YC2010/MyClass/data/fetchtasks/SearchFetchTask.java<|end_filename|>
package com.YC2010.MyClass.data.fetchtasks;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;

import com.YC2010.MyClass.R;
import com.YC2010.MyClass.data.Connections;
import com.YC2010.MyClass.data.CoursesDBHandler;
import com.YC2010.MyClass.utils.Constants;
import com.YC2010.MyClass.callbacks.AsyncTaskCallbackInterface;
import com.YC2010.MyClass.model.FinalObject;
import com.YC2010.MyClass.model.LectureSectionObject;
import com.YC2010.MyClass.model.TestObject;
import com.YC2010.MyClass.model.TutorialObject;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;

/**
 * Created by Danny on 2015/6/27.
 */
public class SearchFetchTask extends AsyncTask<String, Void, Bundle> {

    private Activity mActivity;
    private AsyncTaskCallbackInterface mAsyncTaskCallbackInterface;

    private ArrayList<LectureSectionObject> lectures = new ArrayList<>();
    private ArrayList<TutorialObject> tutorials = new ArrayList<>();
    private ArrayList<TestObject> tests = new ArrayList<>();
    private ArrayList<FinalObject> finals = new ArrayList<>();

    public SearchFetchTask(Activity activity, AsyncTaskCallbackInterface asyncTaskCallbackInterface) {
        this.mActivity = activity;
        mAsyncTaskCallbackInterface = asyncTaskCallbackInterface;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected Bundle doInBackground(String...params) {
        Bundle result = new Bundle();

        fetchCourse(result, params[0]);

        return result;
    }

    private Bundle fetchCourse(Bundle bundle, String input) {

        try{
            bundle.putBoolean("valid_return", false);

            // get schedule JSONBObject
            Log.d("SearchFetchTask", "term is " + mActivity.getSharedPreferences("TERMS", mActivity.MODE_PRIVATE).getInt("TERM_NUM", 0));
            String schedule_url = Connections.getScheduleURL(input, mActivity.getSharedPreferences("TERMS", mActivity.MODE_PRIVATE).getInt("TERM_NUM", 0));
            JSONObject schedulesObject = Connections.getJSON_from_url(schedule_url);

            // check valid data return
            if (schedulesObject == null) {
                Log.d("SearchFetchTask", "WARNING - schedulesObject is NULL");
                return bundle;
            }

            if (!schedulesObject.getJSONObject("meta").getString("status").equals("200")) {
                Log.d("SearchFetchTask", schedulesObject.toString());
                return bundle;
            }

            bundle.putBoolean("valid_return", true);
            JSONArray data = schedulesObject.getJSONArray("data");

            for(int i = 0; i < data.length(); i++){
                JSONObject section = data.getJSONObject(i);
                JSONObject first_class = section.getJSONArray("classes").getJSONObject(0);
                JSONObject date = first_class.getJSONObject("date");
                JSONObject loc = first_class.getJSONObject("location");

                String section_str = section.getString("section");
                String section_type = section_str.substring(0, 3);
                String sectionNumber = section_str.substring(section_str.length() - 3);

                boolean isOnline = sectionNumber.equals("081");

                Log.d("SearchFetchTask", "section_type is <" + section_type + ">");

                CoursesDBHandler db = new CoursesDBHandler(mActivity);

                switch (section_type) {
                    case "LEC":
                    case "STU":
                        JSONArray professors = first_class.getJSONArray("instructors");
                        String prof = "";

                        if (professors != null && professors.length() > 0) {
                            prof = professors.getString(0);
                        }

                        // check if is in db
                        if(db.IsInDB(section.getString("class_number"))){
                            bundle.putBoolean("course_taken", true);
                            bundle.putString("course_taken_num",section.getString("class_number"));
                        }

                        LectureSectionObject lecture = new LectureSectionObject();
                        lecture.setNumber(section.getString("class_number"));
                        lecture.setIsOnline(isOnline);

                        if (!isOnline) {
                            String weekdays = date.getString("weekdays");
                            String startTime = date.getString("start_time");
                            String endTime = date.getString("end_time");

                            if (!weekdays.equals("null") && !startTime.equals("null") && !endTime.equals("null")) {
                                lecture.setTime(date.getString("weekdays") + " " +
                                        date.getString("start_time") + "-" + date.getString("end_time"));
                            }

                            String building = loc.getString("building");
                            String room = loc.getString("room");

                            if (!building.equals("null") && !room.equals("null")) {
                                lecture.setLocation(building + " " + room);
                            } else {
                                lecture.setLocation("");
                            }
                        } else {
                            sectionNumber = "Online";
                            lecture.setTime(mActivity.getResources().
                                    getString(R.string.date_not_available));
                            lecture.setLocation(mActivity.getResources().
                                    getString(R.string.location_not_available));
                        }

                        lecture.setProfessor(prof);
                        lecture.setSection(sectionNumber);
                        lecture.setCapacity(section.getString("enrollment_capacity"));
                        lecture.setTotal(section.getString("enrollment_total"));
                        lectures.add(lecture);
                        break;

                    case "TST":
                        bundle.putBoolean("has_tst", true);

                        TestObject test = new TestObject();

                        test.setSection(section_str.substring(4));
                        test.setTime(date.getString("start_date") + " " +
                                date.getString("start_time") + "-" + date.getString("end_time"));
                        test.setCapacity(section.getString("enrollment_capacity"));
                        test.setTotal(section.getString("enrollment_total"));

                        tests.add(test);
                        break;

                    case "TUT":
                        bundle.putBoolean("has_tut", true);

                        TutorialObject tutorial = new TutorialObject();

                        tutorial.setNumber(section.getString("class_number"));
                        tutorial.setSection(section_str.substring(4));
                        tutorial.setTime(date.getString("weekdays") + " " +
                                date.getString("start_time") + "-" + date.getString("end_time"));
                        tutorial.setLocation(loc.getString("building") + " " + loc.getString("room"));
                        tutorial.setCapacity(section.getString("enrollment_capacity"));
                        tutorial.setTotal(section.getString("enrollment_total"));

                        tutorials.add(tutorial);
                        break;
                    case "LAB":
                        bundle.putBoolean("has_lab", true);
                        break;
                }
            }

            bundle.putString("title", data.getJSONObject(0).getString("title"));
            bundle.putString("courseName", data.getJSONObject(0).getString("subject") + " " +
                    data.getJSONObject(0).getString("catalog_number"));
            bundle.putParcelableArrayList(Constants.lectureSectionObjectListKey, lectures);
            bundle.putParcelableArrayList(Constants.tutorialObjectListKey, tutorials);
            bundle.putParcelableArrayList(Constants.testObjectListKey, tests);


            // get exam JSONBObject
            String exam_url = Connections.getExamsURL(mActivity.getSharedPreferences("TERMS", mActivity.MODE_PRIVATE).getInt("TERM_NUM", 0));
            JSONObject examObject = Connections.getJSON_from_url(exam_url);

            if (examObject != null) {
                JSONArray examData = examObject.getJSONArray("data");

                for (int i = 0; i < examData.length(); i++) {
                    if (examData.getJSONObject(i).getString("course").equals(bundle.getString("courseName"))) {
                        bundle.putBoolean("has_finals", true);
                        JSONArray exam_sections = examData.getJSONObject(i).getJSONArray("sections");
                        for (int j = 0; j < exam_sections.length(); j++) {
                            FinalObject finalObject = new FinalObject();

                            String section = exam_sections.getJSONObject(j).getString("section");

                            finalObject.setSection(section);
                            if (!section.contains("Online")) {
                                finalObject.setTime(exam_sections.getJSONObject(j).getString("start_time") + "-" +
                                        exam_sections.getJSONObject(j).getString("end_time"));
                                finalObject.setLocation(exam_sections.getJSONObject(j).getString("location"));
                                finalObject.setDate(exam_sections.getJSONObject(j).getString("date"));
                                finalObject.setIsOnline(false);
                            } else {
                                finalObject.setIsOnline(true);
                            }
                            finals.add(finalObject);
                        }
                    }
                }
                bundle.putParcelableArrayList(Constants.finalObjectListKey, finals);
            }

            // Fetch course information (description, etc)
            JSONObject courseInfoObject = Connections.getJSON_from_url(Connections.getCourseInfoURL(input));
            JSONObject courseObject = courseInfoObject.getJSONObject("data");

            bundle.putString("description", courseObject.getString("description"));
            String prerequisites = courseObject.getString("prerequisites");
            String antirequisites = courseObject.getString("antirequisites");

            if (prerequisites != null && !prerequisites.equals("null")) {
                bundle.putString("prerequisites", prerequisites);
            }

            if (antirequisites != null && !antirequisites.equals("null")) {
                bundle.putString("antirequisites", antirequisites);
            }

            return bundle;

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    protected void onPostExecute(final Bundle bundle) {
        mAsyncTaskCallbackInterface.onOperationComplete(bundle);
    }


}


<|start_filename|>app/src/main/java/com/YC2010/MyClass/ui/fragments/SearchInfoFragment.java<|end_filename|>
package com.YC2010.MyClass.ui.fragments;

import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.YC2010.MyClass.R;

/**
 * Created by Danny on 2015/12/25.
 */
public class SearchInfoFragment extends Fragment {
    private Activity mActivity;
    private View mView;
    private Bundle mFetchedResult;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.mActivity = getActivity();
        this.mFetchedResult = this.getArguments();
    }

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

        return mView;
    }

    public void updateView() {
        TextView title = (TextView) mView.findViewById(R.id.title);
        TextView description = (TextView) mView.findViewById(R.id.description);

        TextView prerequisites = (TextView) mView.findViewById(R.id.preReq);
        TextView antirequisites = (TextView) mView.findViewById(R.id.antiReq);
        TextView prerequisitesLabel = (TextView) mView.findViewById(R.id.preReqLabel);
        TextView antirequisitesLabel = (TextView) mView.findViewById(R.id.antiReqLabel);

        title.setText(mFetchedResult.getString("title"));
        description.setText(mFetchedResult.getString("description"));

        String prerequisitesText = mFetchedResult.getString("prerequisites");
        String antirequisitesText = mFetchedResult.getString("antirequisites");

        if (prerequisitesText != null && prerequisitesText.length() > 0) {
            prerequisites.setText(prerequisitesText);
            prerequisites.setVisibility(View.VISIBLE);
            prerequisitesLabel.setVisibility(View.VISIBLE);
        }

        if (antirequisitesText != null && antirequisitesText.length() > 0) {
            antirequisites.setText(antirequisitesText);
            antirequisites.setVisibility(View.VISIBLE);
            antirequisitesLabel.setVisibility(View.VISIBLE);
        }
    }
}


<|start_filename|>app/src/main/java/com/YC2010/MyClass/ui/adapters/SectionListAdapter.java<|end_filename|>
package com.YC2010.MyClass.ui.adapters;

import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.YC2010.MyClass.model.LectureSectionObject;
import com.YC2010.MyClass.utils.Constants;
import com.YC2010.MyClass.R;

import java.util.ArrayList;

public class SectionListAdapter extends BaseAdapter {
    ArrayList<LectureSectionObject> mArrayList;
    Context mContext;
    LayoutInflater mLayoutInflater;

    public SectionListAdapter(Context context, int textViewResourceId, Bundle bundle) {
        mLayoutInflater = LayoutInflater.from(context);
        mArrayList = bundle.getParcelableArrayList(Constants.lectureSectionObjectListKey);
        mContext = context;
        Log.d("SectionListAdapter", "Course name is " + bundle.getString("courseName"));
    }

    @Override
    public LectureSectionObject getItem(int i) {
        return mArrayList.get(i);
    }

    @Override
    public int getCount() {
        return mArrayList != null ? mArrayList.size() : 0;
    }

    @Override
    public long getItemId(int arg0) {
        return 0;
    }

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

        View v = mLayoutInflater.inflate(R.layout.section_item, null);

        TextView capacity = (TextView) v.findViewById(R.id.section_item_capacity);
        TextView lec = (TextView) v.findViewById(R.id.section_item_lec);
        TextView loc = (TextView) v.findViewById(R.id.section_item_loc);
        TextView time = (TextView) v.findViewById(R.id.section_item_time);
        TextView prof = (TextView) v.findViewById(R.id.section_item_prof);
        RelativeLayout section_item_prof_layout = (RelativeLayout) v.findViewById((R.id.section_item_prof_layout));

        LectureSectionObject sectionInfo = getItem(position);
        String professor = sectionInfo.getProfessor();

        if (professor != null && professor.length() > 0) {
            prof.setText(professor);
            prof.setVisibility(View.VISIBLE);
            section_item_prof_layout.setVisibility(View.VISIBLE);
        } else {
            prof.setVisibility(View.GONE);
        }

        lec.setText(sectionInfo.getSection());
        time.setText(sectionInfo.getTime());
        loc.setText(sectionInfo.getLocation());

        int enroll_total = Integer.parseInt(sectionInfo.getTotal());
        int enroll_cap = Integer.parseInt(sectionInfo.getCapacity());

        if (enroll_total/enroll_cap >= 1) {
            capacity.setTextColor(mContext.getResources().getColor(R.color.fab_color_1));
        } else {
            capacity.setTextColor(mContext.getResources().getColor(R.color.light_green));
        }

        Log.d("SectionListAdapter", "rate is " + enroll_total/enroll_cap);

        capacity.setText(enroll_total + "/" + enroll_cap);

        return v;
    }

}

<|start_filename|>app/src/main/java/com/YC2010/MyClass/ui/fragments/SettingFragment.java<|end_filename|>
package com.YC2010.MyClass.ui.fragments;

import android.app.Activity;
import android.content.DialogInterface;
import android.net.Uri;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceFragment;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AlertDialog;

import com.YC2010.MyClass.utils.Constants;
import com.YC2010.MyClass.data.CoursesDBHandler;
import com.YC2010.MyClass.R;
import com.YC2010.MyClass.data.ReminderDBHandler;
import com.YC2010.MyClass.model.Reminder_item;

import java.util.List;

/**
 * Created by Jason on 2015-05-26.
 */

public class SettingFragment extends PreferenceFragment {
    private OnFragmentInteractionListener mListener;

    public SettingFragment() {}

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

        addPreferencesFromResource(R.xml.preferences);

        Preference clean_reminder_pref = (Preference) findPreference("pref_key_clean_reminder_db");
        clean_reminder_pref.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
            public boolean onPreferenceClick(Preference preference) {
                //open browser or intent here
                // should show an alert dialog
                ReminderDBHandler reminder_db = new ReminderDBHandler(getActivity());
                reminder_db.removeAll();
                reminder_db.close();

                // show snackBar
                Snackbar.make(getView(), "All reminders removed", Snackbar.LENGTH_SHORT)
                        .show();
                return true;
            }
        });

        Preference import_sample_pref = (Preference) findPreference("pref_key_import_reminders");
        import_sample_pref.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
            public boolean onPreferenceClick(Preference preference) {
                //open browser or intent here
                ReminderDBHandler reminder_db = new ReminderDBHandler(getActivity());
                reminder_db.removeAll("d");
                List<Reminder_item> holiday_2015 = Constants.get_holidays();
                List<Reminder_item> sample_reminder = Constants.get_sample_reminder();
                for(int i = 0; i < holiday_2015.size(); i++){
                    reminder_db.addReminder(holiday_2015.get(i));
                }
                for(int i = 0; i < sample_reminder.size(); i++){
                    reminder_db.addReminder(sample_reminder.get(i));
                }

                // show snackBar
                Snackbar.make(getView(), "Sample reminders added", Snackbar.LENGTH_SHORT)
                        .show();
                return true;
            }
        });

        Preference clean_course_pref = (Preference) findPreference("pref_key_clean_course_db");
        clean_course_pref.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
            public boolean onPreferenceClick(Preference preference) {
                //open browser or intent here
                // should show an alert dialog
                CoursesDBHandler courses_db = new CoursesDBHandler(getActivity());
                courses_db.removeAll();
                courses_db.close();

                // show snackBar
                Snackbar.make(getView(), "All courses removed", Snackbar.LENGTH_SHORT)
                        .show();
                return true;
            }
        });

        Preference credit = findPreference("pref_key_Credit");
        credit.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
            @Override
            public boolean onPreferenceClick(Preference preference) {
                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                builder
                        .setTitle(R.string.credit_title)
                        .setMessage(R.string.credit_content)
                        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {}
                        });
                builder.show();
                return true;
            }
        });

    }

    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

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

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    public interface OnFragmentInteractionListener {

        void onFragmentInteraction(Uri uri);
    }

}


<|start_filename|>app/src/main/java/com/YC2010/MyClass/model/FinalObject.java<|end_filename|>
package com.YC2010.MyClass.model;

import android.os.Parcel;
import android.os.Parcelable;

/**
 * Created by Danny on 2015/10/17.
 */
public class FinalObject implements Parcelable {
    private String section;
    private String time;
    private String location;
    private String date;
    private boolean isOnline;

    public FinalObject() {}

    @Override
    public int describeContents()  {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(section);
        dest.writeString(time);
        dest.writeString(location);
        dest.writeString(date);
        dest.writeByte((byte) (isOnline ? 1 : 0));
    }

    public FinalObject(Parcel src) {
        this.section = src.readString();
        this.time = src.readString();
        this.location = src.readString();
        this.date = src.readString();
        this.isOnline = src.readByte() == 1;
    }

    public static final Creator CREATOR = new Creator() {
        @Override
        public FinalObject createFromParcel(Parcel source) {
            return new FinalObject(source);
        }

        @Override
        public FinalObject[] newArray(int size) {
            return new FinalObject[size];
        }
    };

    public void setSection(String section) {
        this.section = section;
    }

    public void setTime(String time) {
        this.time = time;
    }

    public void setLocation(String location) {
        this.location = location;
    }

    public void setDate(String date) {
        this.date = date;
    }

    public void setIsOnline(boolean isOnline) {
        this.isOnline = isOnline;
    }

    public String getSection() {
        return section;
    }

    public String getTime() {
        return time;
    }

    public String getLocation() {
        return location;
    }

    public String getDate() {
        return date;
    }

    public boolean isOnline() {
        return isOnline;
    }
}


<|start_filename|>app/src/main/java/com/YC2010/MyClass/model/CourseInfo.java<|end_filename|>
package com.YC2010.MyClass.model;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by Lincoln on 2015-06-02.
 */
public class CourseInfo {
    private String courseName;
    private String courseNum;
    private String courseSec;
    private String courseTime;
    private String courseLoc;
    private String courseProf;
    private String tutName;
    private String tutNum;
    private String tutTime;
    private String tutLoc;
    private String tutSec;
    private boolean isOnline;
    private String labName;
    private String labNum;
    private String labTime;
    private String labSec;
    private String labLoc;

    public CourseInfo(String name){
        courseName = name;
    }

    public void setNum(String number){
        courseNum = number;
    }

    public void setLoc(String loc){
        courseLoc = loc;
    }

    public void setTime(String time){
        courseTime = time;
    }

    public void setTimeAPM(String time){
        if (!isOnline && time != null) {
            int i = 0;
            for (; time.charAt(i) < 48 || time.charAt(i) > 57; i++);
            String days = time.substring(0,i);
            String realtime = time.substring(i);
            String starttime = realtime.substring(0,5);
            String endtime = realtime.substring(6);
            try{
                DateFormat f1 = new SimpleDateFormat("HH:mm"); //HH for hour of the day (0 - 23)
                Date d = f1.parse(starttime);
                DateFormat f2 = new SimpleDateFormat("h:mma");
                starttime = f2.format(d); // "12:18am"

                DateFormat f3 = new SimpleDateFormat("HH:mm"); //HH for hour of the day (0 - 23)
                Date d2 = f3.parse(endtime);
                DateFormat f4 = new SimpleDateFormat("h:mma");
                endtime = f4.format(d2); // "12:18am"


            } catch (ParseException e){
                e.printStackTrace();
            }
            courseTime = days + starttime + "-" + endtime;
        } else {
            courseTime = time;
        }
    }
    public void setSec(String sec){
        courseSec = sec;
        isOnline = sec.equals("081");
    }

    public void setProf(String prof){
        courseProf = prof;
    }

    public void setTutname(){
        tutName = courseName;
    }

    public void setTutnum(String num){
        tutNum = num;
    }

    public void setTutTime(String time){
        tutTime = time;
    }

    public void setTutLoc(String loc) {
        tutLoc = loc;
    }

    public void setTutsec(String sec){
        tutSec = sec;
    }

    public void setlabName(){
        tutSec = courseName;
    }

    public void setlabNum(String num){ labNum = num;}

    public void setlabTime(String time){ labTime = time;}

    public void setlabLoc(String loc){ labLoc = loc;}

    public void setlabSec(String sec){ labSec = sec;}

    public void setIsOnline(boolean isOnline) {
        this.isOnline = isOnline;
    }

    public String getCourseName() {
        return courseName;
    }

    public String getCourseNum() {
        return courseNum;
    }

    public String getCourseSec() {
        return courseSec;
    }

    public String getCourseTime() {
        return courseTime;
    }

    public String getCourseLoc() {
        return courseLoc;
    }

    public String getCourseProf() {
        return courseProf;
    }

    public String getTutName() {
        return tutName;
    }

    public String getTutNum() {
        return tutNum;
    }

    public String getTutTime() {
        return tutTime;
    }

    public String getTutLoc() {
        return tutLoc;
    }

    public String getTutSec() {
        return tutSec;
    }

    public boolean isOnline() {
        return isOnline;
    }

    public String getLabName() {
        return labName;
    }

    public String getLabNum() {
        return labNum;
    }

    public String getLabTime() {
        return labTime;
    }

    public String getLabSec() {
        return labSec;
    }

    public String getLabLoc() {
        return labLoc;
    }
}


<|start_filename|>app/src/main/java/com/YC2010/MyClass/ui/fragments/CoursesFragment.java<|end_filename|>
package com.YC2010.MyClass.ui.fragments;

import android.app.AlertDialog;
import android.app.Fragment;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;

import com.YC2010.MyClass.model.CourseInfo;
import com.YC2010.MyClass.ui.adapters.Course_Adapter;
import com.YC2010.MyClass.data.CoursesDBHandler;
import com.YC2010.MyClass.R;

import java.util.List;

/**
 * Created by Jason on 2015-05-25.
 */
public class CoursesFragment extends Fragment {
    private RecyclerView mRecyclerView;
    private RecyclerView.Adapter mAdapter;
    private RecyclerView.LayoutManager mLayoutManager;

    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_COURSE = "COURSE";


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


        // Inflate the layout for this fragment
        View rootView = inflater.inflate(R.layout.fragment_courses, container, false);

        // RecyclerView:
        mRecyclerView = (RecyclerView) rootView.findViewById(R.id.courses_recycler_view);

        // use this setting to improve performance if you know that changes
        // in content do not change the layout size of the RecyclerView
        mRecyclerView.setHasFixedSize(true);

        // use a linear layout manager
        mLayoutManager = new LinearLayoutManager(getActivity());
        mRecyclerView.setLayoutManager(mLayoutManager);

        // get Courses from db
        CoursesDBHandler db = new CoursesDBHandler(getActivity());
        final List<CourseInfo> myDataset = db.getAllCourses(getActivity().getSharedPreferences("TERMS", getActivity().MODE_PRIVATE).getInt("TERM_NUM", 0));


        // specify an adapter (see also next example)
        mAdapter = new Course_Adapter(myDataset, getActivity());

        mAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
            @Override
            public void onChanged() {
                super.onChanged();
                Log.d("CoursesFragment", "Data set changed");
            }
        });

        mRecyclerView.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), mRecyclerView, new ClickListener() {
            @Override
            public void onClick(View view, final int position) {
                SearchFragment mSearchFragment = new SearchFragment();
                Bundle args = new Bundle();
                String course_name = myDataset.get(position).getCourseName();
                args.putString(ARG_COURSE, course_name);
                mSearchFragment.setArguments(args);
                getFragmentManager().beginTransaction()
                        .replace(R.id.container, mSearchFragment)
                        .addToBackStack("7")
                        .commit();
            }

            @Override
            public void onLongClick(final View view, final int position) {
                Log.d("mRecyclerView", "enter onlongclick");
                // vibrate
                Vibrator v = (Vibrator) getActivity().getSystemService(Context.VIBRATOR_SERVICE);
                v.vibrate(10);

                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                builder.setTitle("Delete this Course?");

                builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                        RecyclerView recyclerView = (RecyclerView) getActivity().findViewById(R.id.courses_recycler_view);
                        Course_Adapter adapter = (Course_Adapter) recyclerView.getAdapter();
                        adapter.removeAt(position);

                        // show snackBar
                        Snackbar.make(view, "Course Removed", Snackbar.LENGTH_SHORT)
                                .show();

                    }
                });
                builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        // nothing
                    }
                });
                AlertDialog confirmation = builder.create();

                confirmation.show();
                confirmation.getButton(confirmation.BUTTON_NEGATIVE).setTextColor(getResources().getColor(R.color.myPrimaryColor));
                confirmation.getButton(confirmation.BUTTON_POSITIVE).setTextColor(getResources().getColor(R.color.myPrimaryColor));
            }
        }));

        mRecyclerView.setAdapter(mAdapter);
        return rootView;
    }

    public static interface ClickListener {
        void onClick(View view, int position);

        void onLongClick(View view, int position);
    }

    static class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {

        private GestureDetector gestureDetector;
        private ClickListener clickListener;

        public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final ClickListener clickListener) {
            this.clickListener = clickListener;
            gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
                @Override
                public boolean onSingleTapUp(MotionEvent e) {
                    return true;
                }

                @Override
                public void onLongPress(MotionEvent e) {
                    View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
                    if (child != null && clickListener != null) {
                        clickListener.onLongClick(child, recyclerView.getChildLayoutPosition(child));
                    }
                }
            });
        }

        @Override
        public boolean onInterceptTouchEvent(final RecyclerView rv, MotionEvent e) {

            final View child = rv.findChildViewUnder(e.getX(), e.getY());
            if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
                //Log.d("onInterceptTouchEvent", "before delay");
                // delay 100ms for displaying ripple effect
                Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    public void run() {
                        //write the code here which you want to run after 500 milliseconds
                        //Log.d("onInterceptTouchEvent", "delayed");
                        clickListener.onClick(child, rv.getChildLayoutPosition(child));
                    }
                }, 100);
            }

            return false;
        }

        @Override
        public void onTouchEvent(RecyclerView rv, MotionEvent e) {
        }

        @Override
        public void onRequestDisallowInterceptTouchEvent(boolean bool) {
        }
    }
}


<|start_filename|>app/src/main/java/com/YC2010/MyClass/ui/adapters/Course_Adapter.java<|end_filename|>
package com.YC2010.MyClass.ui.adapters;

import android.content.Context;
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.TextView;

import com.YC2010.MyClass.model.CourseInfo;
import com.YC2010.MyClass.data.CoursesDBHandler;
import com.YC2010.MyClass.R;

import java.util.List;

/**
 * Created by Jason on 2015-06-05.
 */

public class Course_Adapter extends RecyclerView.Adapter<Course_Adapter.ViewHolder> {
    private List<CourseInfo> mDataset;
    private Context mContext;
    private CoursesDBHandler db;
    // Provide a reference to the views for each data item
    // Complex data items may need more than one view per item, and
    // you provide access to all the views for a data item in a view holder
    public static class ViewHolder extends RecyclerView.ViewHolder{
        // each data item is just a string in this case
        public TextView mTitle;
        public TextView mLocation;
        public TextView mSection;
        public TextView mTime;
        public ViewHolder(View v) {
            super(v);
            mTitle = (TextView) v.findViewById(R.id.TitleInCardView);
            mLocation = (TextView) v.findViewById(R.id.LocationInCardView);
            mSection = (TextView) v.findViewById(R.id.SecInCardView);
            mTime = (TextView) v.findViewById(R.id.TimeInCardView);
            //mdaysLeft = (TextView) v.findViewById(R.id.NumberofDaysLeftInCardView);
            //mdaysLeft_Symbol = (TextView) v.findViewById(R.id.DaysLeftInCardView);
        }


    }

    // Provide a suitable constructor (depends on the kind of dataset)
    public Course_Adapter(List<CourseInfo> myDataset, Context context) {
        this.mDataset = myDataset;
        this.mContext = context;
        this.db = new CoursesDBHandler(mContext);
    }


    // Create new views (invoked by the layout manager)
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent,
                                                   int viewType) {
        // create a new view
        View v = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.course_cardview, parent, false);

        // set the view's size, margins, paddings and layout parameters
        final ViewHolder mViewHolder = new ViewHolder(v);
        mViewHolder.itemView.setClickable(true);
        mViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
                                                    @Override
                                                    public void onClick(View v) {
                                                        Log.d("mViewHolder", "enter onclick");
                                                    }
                                                }
        );
        return mViewHolder;
    }



    // Replace the contents of a view (invoked by the layout manager)
    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        // - get element from your dataset at this position
        // - replace the contents of the view with that element
        holder.mTitle.setText(mDataset.get(position).getCourseName());
        holder.mLocation.setText(mDataset.get(position).getCourseLoc());
        holder.mSection.setText(mDataset.get(position).getCourseSec());
        holder.mTime.setText(mDataset.get(position).getCourseTime());
    }

    // Return the size of your dataset (invoked by the layout manager)
    @Override
    public int getItemCount() {
        return mDataset.size();
    }

    @Override
    public void onAttachedToRecyclerView(RecyclerView recyclerView) {
        super.onAttachedToRecyclerView(recyclerView);
    }

    public void updateView() {
        Log.d("Reminder adapter ", "updating view");
        CoursesDBHandler db = new CoursesDBHandler(mContext);
        mDataset = db.getAllCourses(mContext.getSharedPreferences("TERMS", mContext.MODE_PRIVATE).getInt("TERM_NUM", 0));
        notifyDataSetChanged();
    }

    public void removeAt(int position) {
        dbItemRemove(position);
        mDataset.remove(position);
        notifyItemRemoved(position);
    }

    public void dbItemRemove(int position){
        String CourseNum = mDataset.get(position).getCourseNum();
        Log.d("dbItemRemove", "position is " + position);
        db.removeCourse(CourseNum);
    }
}

<|start_filename|>app/src/main/java/com/YC2010/MyClass/data/Connections.java<|end_filename|>
package com.YC2010.MyClass.data;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.util.Log;

import com.YC2010.MyClass.utils.Constants;
import com.YC2010.MyClass.utils.Tools;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;

/**
 * Created by Danny on 2015/10/25.
 */
public class Connections {

    // /courses/{subject}/{catalog_number}

    public static String getCourseInfoURL(String input) {
        String subject = "";
        String cataNum = "";
        boolean isCoursePrefix = true;

        input = input.replaceAll("\\s+","");

        for (int i = 0; i < input.length(); i++) {
            if(isCoursePrefix && Character.isDigit(input.charAt(i)))
                isCoursePrefix = false;
            if(isCoursePrefix){
                subject += input.charAt(i);
            }
            else{
                cataNum += input.charAt(i);
            }
        }

        return Constants.UWAPIROOT + "courses/" + subject + "/" + cataNum + ".json" + URLEnding();
    }

    public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager connectivityManager
                = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();
    }


    // /courses/{subject}/{catalog_number}/schedule
    public static String getScheduleURL(String input) {
        String subject = "";
        String cataNum = "";
        boolean isCoursePrefix = true;
        input = input.replaceAll("\\s+","");

        for (int i = 0; i < input.length(); i++) {
            if(isCoursePrefix && Character.isDigit(input.charAt(i)))
                isCoursePrefix = false;
            if(isCoursePrefix){
                subject += input.charAt(i);
            }
            else{
                cataNum += input.charAt(i);
            }
        }
        return Constants.UWAPIROOT + "courses/" + subject + "/" + cataNum + "/schedule.json" + URLEnding();
    }

    // /terms/{term}/{subject}/{catalog_number}/schedule
    public static String getScheduleURL(String input, Integer term) {
        String subject = "";
        String cataNum = "";
        boolean isCoursePrefix = true;
        input = input.replaceAll("\\s+","");

        for (int i = 0; i < input.length(); i++) {
            if (isCoursePrefix && Character.isDigit(input.charAt(i)))
                isCoursePrefix = false;
            if (isCoursePrefix){
                subject += input.charAt(i);
            }
            else {
                cataNum += input.charAt(i);
            }
        }
        return Constants.UWAPIROOT + "terms/" + term + "/" + subject + "/" + cataNum + "/schedule.json" + URLEnding();
    }

    public static Integer getCurrentTerm() throws Exception {
        String term;
        String termList_url = Constants.UWAPIROOT + "terms/list.json" + URLEnding();
        JSONObject termList = getJSON_from_url(termList_url);
        try {
            term = termList.getJSONObject("data").getString("current_term");
        }
        catch (Exception e){
            e.printStackTrace();
            return null;
        }
        return Integer.parseInt(term);
    }


    /*      return a list of term num and a list of term name     */
    /* index 0: previous term */
    /* index 1: current term  */
    /* index 2: next term     */
    public static Bundle getTerms() {
        Bundle mbundle = new Bundle();
        ArrayList<Integer> termNumList = new ArrayList<>();
        ArrayList<String> termNameList = new ArrayList<>();
        String termList_url = Constants.UWAPIROOT + "terms/list.json" + URLEnding();
        try {
            JSONObject termData = getJSON_from_url(termList_url).getJSONObject("data");
            termNumList.add(0, Integer.parseInt(termData.getString("previous_term")));
            termNumList.add(1, Integer.parseInt(termData.getString("current_term")));
            termNumList.add(2,Integer.parseInt(termData.getString("next_term")));

            JSONObject termYear = termData.getJSONObject("listings");
            Iterator<?> years = termYear.keys();
            JSONArray termTermList;
            HashMap<Integer, String> termMap = new HashMap<>();
            while (years.hasNext()){
                String key = (String) years.next();
                termTermList = termYear.getJSONArray(key);
                for (int j = 0; j < termTermList.length(); j++){
                    termMap.put(termTermList.getJSONObject(j).getInt("id"), termTermList.getJSONObject(j).getString("name"));
                }
            }

            for (int i = 0; i < termNumList.size(); i++){
                termNameList.add(i, termMap.get(termNumList.get(i)));
            }
        }
        catch (Exception e){
            e.printStackTrace();
            return null;
        }

        mbundle.putIntegerArrayList("KEY_TERM_NUM", termNumList);
        mbundle.putStringArrayList("KEY_TERM_NAME", termNameList);
        return mbundle;
    }

    public static String getTermName(String term){
        String termList_url = Constants.UWAPIROOT + "terms/list.json" + URLEnding();
        try {
            JSONObject terms_listing = getJSON_from_url(termList_url).getJSONObject("data").getJSONObject("listings");
            Iterator i = terms_listing.keys();
            while(i.hasNext()){
                String key = (String) i.next();
                JSONArray year = (JSONArray) terms_listing.get(key);
                for(int j = 0; j < year.length(); j++){
                    if (year.getJSONObject(j).getString("id").equals(term)) {
                        Log.d("Constants", year.getJSONObject(j).getString("name"));
                        return year.getJSONObject(j).getString("name");
                    }
                }
            }
            return null;
        }
        catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    public static String getExamsURL(int term) {
        return Constants.UWAPIROOT + "terms/" + term + "/examschedule" + ".json" + URLEnding();
    }

    public static String getSubjectsOfferingURL() {
        return Constants.UWAPIROOT + "codes/subjects" + ".json" + URLEnding();
    }

    public static String getCatalogNumURL(String subject) {
        return Constants.UWAPIROOT + "courses/" + subject + ".json" + URLEnding();
    }

    public static JSONObject getJSON_from_url(String url) throws Exception {
        URL obj = new URL(url);
        HttpURLConnection connection = (HttpURLConnection) obj.openConnection();
        JSONObject jsonObject;

        try {
            Log.d("getJSONObject", "URL is " + url);

            int responseCode = connection.getResponseCode();

            if (responseCode != 200) {
                throw new RuntimeException("Failed: HTTP error code: " + responseCode);
            }

            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));

            String inputLine;
            StringBuilder entityStringBuilder = new StringBuilder();

            while (null != (inputLine = in.readLine())) {
                entityStringBuilder.append(inputLine).append("\n");
            }
            in.close();

            jsonObject = new JSONObject(entityStringBuilder.toString());


        }
        catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return jsonObject;
    }

    public static String URLEnding() {
        return "?key=" + Tools.YOUNEEDTHIS;
    }
}


<|start_filename|>app/src/main/java/com/YC2010/MyClass/ui/fragments/SearchExamFragment.java<|end_filename|>
package com.YC2010.MyClass.ui.fragments;

import android.app.Activity;
import android.app.Fragment;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.YC2010.MyClass.R;
import com.YC2010.MyClass.ui.adapters.FinalsListAdapter;

/**
 * Created by Danny on 2015/12/26.
 */
public class SearchExamFragment extends Fragment {
    private Activity mActivity;
    private View mView;
    private Bundle mFetchedResult;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.mActivity = getActivity();
        this.mFetchedResult = this.getArguments();
    }

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

        if (mFetchedResult.getBoolean("has_finals", false)) {
            TextView finals = (TextView) mView.findViewById(R.id.final_exams);
            if (finals != null) {
                finals.setVisibility(View.VISIBLE);
            }
            updateView();
        }

        return mView;
    }

    public void updateView() {
        // get default divider
        int[] attrs = {android.R.attr.listDivider};
        TypedArray ta = mActivity.obtainStyledAttributes(attrs);
        Drawable divider = ta.getDrawable(0);
        ta.recycle();

        LinearLayout mFinalLinearLayout = (LinearLayout) mView.findViewById(R.id.finals_list);
        FinalsListAdapter FinalsAdapter = new FinalsListAdapter(mActivity, R.layout.section_item, mFetchedResult);
        for (int i = 0; i < FinalsAdapter.getCount(); i++) {
            View view = FinalsAdapter.getView(i, null, mFinalLinearLayout);
            mFinalLinearLayout.addView(view);
            mFinalLinearLayout.setShowDividers(LinearLayout.SHOW_DIVIDER_MIDDLE | LinearLayout.SHOW_DIVIDER_BEGINNING);
            mFinalLinearLayout.setDividerDrawable(divider);
        }
    }
}


<|start_filename|>app/src/main/java/com/YC2010/MyClass/ui/fragments/SearchScheduleFragment.java<|end_filename|>
package com.YC2010.MyClass.ui.fragments;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.content.DialogInterface;
import android.content.res.ColorStateList;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.AppCompatButton;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.YC2010.MyClass.model.CourseInfo;
import com.YC2010.MyClass.model.LectureSectionObject;
import com.YC2010.MyClass.R;
import com.YC2010.MyClass.data.CoursesDBHandler;
import com.YC2010.MyClass.ui.adapters.SectionListAdapter;
import com.YC2010.MyClass.ui.adapters.TstListAdapter;
import com.YC2010.MyClass.ui.adapters.TutListAdapter;
import com.YC2010.MyClass.utils.Constants;

import java.util.ArrayList;

/**
 * Created by Danny on 2015/12/26.
 */
public class SearchScheduleFragment extends Fragment {
    private Activity mActivity;
    private View mView;
    private Bundle mFetchedResult;
    private boolean mCourseTaken;
    private String mTakenCourseNumber;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.mActivity = getActivity();
        this.mFetchedResult = this.getArguments();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.fragment_search_schedule, container, false);
        TextView courseName = (TextView) mView.findViewById(R.id.course_name);
        courseName.setText(mFetchedResult.getString("courseName"));
        setupLists();
        setupAddButton();

        return mView;
    }

    private void setupLists() {

        // get default divider
        int[] attrs = {android.R.attr.listDivider};
        TypedArray ta = mActivity.obtainStyledAttributes(attrs);
        Drawable divider = ta.getDrawable(0);
        ta.recycle();

        LinearLayout mLecLinearLayout = (LinearLayout) mView.findViewById(R.id.lec_list);
        SectionListAdapter LecAdapter = new SectionListAdapter(mActivity, R.layout.section_item, mFetchedResult);
        for (int i = 0; i < LecAdapter.getCount(); i++) {
            View view = LecAdapter.getView(i, null, mLecLinearLayout);
            mLecLinearLayout.addView(view);
            mLecLinearLayout.setShowDividers(LinearLayout.SHOW_DIVIDER_MIDDLE | LinearLayout.SHOW_DIVIDER_BEGINNING);
            mLecLinearLayout.setDividerDrawable(divider);
        }

        TextView lec = (TextView) mView.findViewById(R.id.lec);
        if (lec != null) {
            lec.setVisibility(View.VISIBLE);
        }

        if (mFetchedResult.getBoolean("has_tst", false)) {
            TextView tst = (TextView) mView.findViewById(R.id.tst);
            if (tst != null) {
                tst.setVisibility(View.VISIBLE);
            }

            LinearLayout mTstLinearLayout = (LinearLayout) mView.findViewById(R.id.tst_list);
            TstListAdapter TstAdapter = new TstListAdapter(mActivity, R.layout.section_item, mFetchedResult);
            for (int i = 0; i < TstAdapter.getCount(); i++) {
                View view = TstAdapter.getView(i, null, mTstLinearLayout);
                mTstLinearLayout.addView(view);
                mTstLinearLayout.setShowDividers(LinearLayout.SHOW_DIVIDER_MIDDLE | LinearLayout.SHOW_DIVIDER_BEGINNING);
                mTstLinearLayout.setDividerDrawable(divider);
            }
        }

        if (mFetchedResult.getBoolean("has_tut", false)) {
            TextView tut = (TextView) mView.findViewById(R.id.tut);
            if (tut != null) {
                tut.setVisibility(View.VISIBLE);
            }

            LinearLayout mTutLinearLayout = (LinearLayout) mView.findViewById(R.id.tut_list);
            TutListAdapter TutAdapter = new TutListAdapter(mActivity, R.layout.section_item, mFetchedResult);
            for (int i = 0; i < TutAdapter.getCount(); i++) {
                View view = TutAdapter.getView(i, null, mTutLinearLayout);
                mTutLinearLayout.addView(view);
                mTutLinearLayout.setShowDividers(LinearLayout.SHOW_DIVIDER_MIDDLE | LinearLayout.SHOW_DIVIDER_BEGINNING);
                mTutLinearLayout.setDividerDrawable(divider);
            }
        }
    }

    void setupAddButton() {
        Button addButton = (Button) mView.findViewById(R.id.add_course_button);

        if (addButton != null) {
            boolean courseTaken = false;

            final ArrayList<LectureSectionObject> lectureSections =
                    mFetchedResult.getParcelableArrayList(Constants.lectureSectionObjectListKey);

            if (lectureSections == null) {
                return;
            }

            final CoursesDBHandler db = new CoursesDBHandler(mActivity);

            for (int i = 0; i < lectureSections.size(); i++) {
                if (db.IsInDB(lectureSections.get(i).getNumber())) {
                    courseTaken = true;
                    mTakenCourseNumber = lectureSections.get(i).getNumber();
                    break;
                }
            }

            setCourseTaken(courseTaken);

            addButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(final View view) {
                    if (!mCourseTaken) {
                        // put sec info into a list of string
                        CharSequence[] lecSecList = new CharSequence[lectureSections.size()];
                        for (int i = 0; i < lectureSections.size(); i++) {
                            lecSecList[i] = lectureSections.get(i).getSection();
                        }

                        displayDialog(lecSecList, db, view);
                    } else {
                        setCourseTaken(false);

                        // remove from db
                        if (mTakenCourseNumber != null) {
                            db.removeCourse(mTakenCourseNumber);
                            mTakenCourseNumber = null;
                        }

                        // show snackBar
                        Snackbar.make(view, "Course Dropped", Snackbar.LENGTH_SHORT)
                                .show();
                    }
                    db.close();
                }
            });
            addButton.setVisibility(View.VISIBLE);
        }
    }

    void displayDialog(CharSequence[] sectionList, final CoursesDBHandler db, final View view) {
        // show dialog to choose sections
        AlertDialog ad = new AlertDialog.Builder(mActivity)
                .setTitle("Choose a section")
                .setSingleChoiceItems(sectionList, 0, null)
                .setNegativeButton(R.string.cancel, null)
                .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        int index = ((AlertDialog) dialog).getListView().getCheckedItemPosition();
                        ArrayList<LectureSectionObject> lectures =
                                mFetchedResult.getParcelableArrayList(Constants.lectureSectionObjectListKey);
                        LectureSectionObject selectedSection = lectures.get(index);

                        // add to db
                        CourseInfo course = new CourseInfo(mFetchedResult.getString("courseName"));
                        course.setSec(selectedSection.getSection());
                        course.setNum(selectedSection.getNumber());
                        course.setLoc(selectedSection.getLocation());
                        course.setIsOnline(selectedSection.isOnline());
                        course.setTimeAPM(selectedSection.getTime());
                        course.setProf(selectedSection.getProfessor());

                        db.addCourse(course, mActivity.getSharedPreferences("TERMS", mActivity.MODE_PRIVATE).getInt("TERM_NUM", 0));
                        mTakenCourseNumber = selectedSection.getNumber();

                        // show snackBar
                        Snackbar.make(view, "Course Added", Snackbar.LENGTH_SHORT)
                                .show();

                        setCourseTaken(true);
                        dialog.dismiss();
                    }
                })
                .create();
        ad.show();

        // change color
        ad.getButton(AlertDialog.BUTTON_POSITIVE)
                .setTextColor(mActivity.getResources().getColor(R.color.myPrimaryColor));
        ad.getButton(AlertDialog.BUTTON_NEGATIVE)
                .setTextColor(mActivity.getResources().getColor(R.color.myPrimaryColor));
    }

    private void setCourseTaken(boolean taken) {
        mCourseTaken = taken;
        Button takeButton = (Button) mView.findViewById(R.id.add_course_button);

        if (takeButton != null) {
            if (taken) {
                takeButton.setText("remove");
                ((AppCompatButton)takeButton).setSupportBackgroundTintList(ColorStateList.valueOf(mActivity.getResources().getColor(R.color.fab_color_1)));
            } else {
                takeButton.setText("Take");
                ((AppCompatButton)takeButton).setSupportBackgroundTintList(ColorStateList.valueOf(mActivity.getResources().getColor(R.color.dialog_text_color)));
            }
        }
    }
}


<|start_filename|>app/src/main/java/com/YC2010/MyClass/ui/fragments/SearchFragment.java<|end_filename|>
package com.YC2010.MyClass.ui.fragments;

import android.app.Activity;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.YC2010.MyClass.data.Connections;
import com.YC2010.MyClass.ui.adapters.CourseDetailPagerAdapter;
import com.YC2010.MyClass.data.fetchtasks.SearchFetchTask;
import com.YC2010.MyClass.callbacks.AsyncTaskCallbackInterface;
import com.YC2010.MyClass.R;


/**
 * Created by Danny on 2015/6/27.
 */
public class SearchFragment extends Fragment {
    private String mCourse;
    private Activity mActivity;
    private View mView;
    private float defaultElevation;
    private ProgressDialog mProgDialog;

    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_COURSE = "COURSE";

    public SearchFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (mView == null) {
            mView = inflater.inflate(R.layout.fragment_search, container, false);
            generateView();
        }

        return mView;
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        String course = getArguments().getString(ARG_COURSE);
        mCourse = course;
        mActivity = getActivity();

        if (course == null) {
            Toast.makeText(mActivity, "course string not found", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        // Remove the shadow between the action bar and the tabs
        ActionBar actionBar = ((AppCompatActivity) mActivity).getSupportActionBar();
        if (actionBar != null) {
            defaultElevation = actionBar.getElevation();
            actionBar.setElevation(0);
        }
    }

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

        // Restore the shadow in the action bar
        ActionBar actionBar = ((AppCompatActivity) mActivity).getSupportActionBar();
        if (actionBar != null) {
            actionBar.setElevation(defaultElevation);
        }
    }

    private void setupTabs(Bundle bundle) {
        ViewPager viewPager = (ViewPager) mView.findViewById(R.id.viewpager);
        viewPager.setAdapter(new CourseDetailPagerAdapter(mActivity.getFragmentManager(), mActivity, bundle));

        TabLayout tabLayout = (TabLayout) mView.findViewById(R.id.sliding_tabs);
        tabLayout.setupWithViewPager(viewPager);
        tabLayout.setVisibility(View.VISIBLE);
    }

    private void showErrorMessage(ErrorState errorState) {
        final LinearLayout errorView = (LinearLayout) mView.findViewById(R.id.error_view_layout);
        TextView errorMessage = (TextView) mView.findViewById(R.id.error_view_message);
        ImageView errorIcon = (ImageView) mView.findViewById(R.id.error_view_icon);
        Button errorButton = (Button) mView.findViewById(R.id.error_view_button);

        switch (errorState) {
            case Network:
                errorMessage.setText(mActivity.getString(R.string.error_message_network));
                errorIcon.setImageResource(R.drawable.ic_cloud_off_black_36dp);
                errorButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        errorView.setVisibility(View.GONE);
                        generateView();
                    }
                });
                break;
            case CourseNotFound:
                errorMessage.setText(mActivity.getString(R.string.error_message_course));
                errorIcon.setImageResource(R.drawable.ic_report_black_36dp);
                errorButton.setVisibility(View.GONE);
                break;
        }

        errorView.setVisibility(View.VISIBLE);
    }

    private void generateView() {
        showProgressDialog();

        if (!Connections.isNetworkAvailable(mActivity)) {
            mProgDialog.dismiss();
            showErrorMessage(ErrorState.Network);
        } else {
            SearchFetchTask searchFetchTask = new SearchFetchTask(mActivity, new AsyncTaskCallbackInterface() {
                @Override
                public void onOperationComplete(Bundle bundle) {
                    if (bundle != null && bundle.getBoolean("valid_return")) {
                        setupTabs(bundle);
                        LinearLayout searchLayout = (LinearLayout) mView.findViewById(R.id.search_detail_layout);
                        searchLayout.setVisibility(View.VISIBLE);
                    } else {
                        showErrorMessage(ErrorState.CourseNotFound);
                    }
                    mProgDialog.dismiss();
                }
            });
            searchFetchTask.execute(mCourse);
        }
    }

    private void showProgressDialog() {
        if (mProgDialog == null) {
            mProgDialog = new ProgressDialog(mActivity);
            mProgDialog.setMessage("Loading...");
            mProgDialog.setCanceledOnTouchOutside(false);
            mProgDialog.setIndeterminate(false);
            mProgDialog.setCancelable(false);
            mProgDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        }

        mProgDialog.show();
    }
}

enum ErrorState {
    Network, CourseNotFound
}

<|start_filename|>app/src/main/java/com/YC2010/MyClass/ui/adapters/CourseDetailPagerAdapter.java<|end_filename|>
package com.YC2010.MyClass.ui.adapters;

import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Context;
import android.os.Bundle;
import android.support.v13.app.FragmentStatePagerAdapter;

import com.YC2010.MyClass.R;
import com.YC2010.MyClass.ui.fragments.SearchExamFragment;
import com.YC2010.MyClass.ui.fragments.SearchInfoFragment;
import com.YC2010.MyClass.ui.fragments.SearchScheduleFragment;

/**
 * Created by Danny on 2015/12/25.
 */
public class CourseDetailPagerAdapter extends FragmentStatePagerAdapter {
    final int PAGE_COUNT = 3;
    private String tabTitle[];
    private Context mContext;
    private Bundle mFetchedResult;

    public CourseDetailPagerAdapter(FragmentManager fragmentManager, Context context, Bundle bundle) {
        super(fragmentManager);
        this.mContext = context;
        this.mFetchedResult = bundle;
        this.tabTitle = new String[] {
                context.getResources().getString(R.string.course_tab_title1),
                context.getResources().getString(R.string.course_tab_title2),
                context.getResources().getString(R.string.course_tab_title3)
        };
    }

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

    @Override
    public Fragment getItem(int position) {
        switch (position) {
            case 0:
                SearchScheduleFragment searchScheduleFragment = new SearchScheduleFragment();
                searchScheduleFragment.setArguments(mFetchedResult);
                return searchScheduleFragment;
            case 1:
                SearchExamFragment searchExamFragment = new SearchExamFragment();
                searchExamFragment.setArguments(mFetchedResult);
                return searchExamFragment;
            case 2:
                SearchInfoFragment searchInfoFragment = new SearchInfoFragment();
                searchInfoFragment.setArguments(mFetchedResult);
                return searchInfoFragment;
        }
        return new Fragment();
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return tabTitle[position];
    }
}


<|start_filename|>app/src/main/java/com/YC2010/MyClass/ui/activities/MainActivity.java<|end_filename|>
package com.YC2010.MyClass.ui.activities;

import android.app.FragmentManager;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;

import com.YC2010.MyClass.R;
import com.YC2010.MyClass.data.Connections;
import com.YC2010.MyClass.ui.fragments.CalendarFragment;
import com.YC2010.MyClass.ui.fragments.CoursesFragment;
import com.YC2010.MyClass.ui.fragments.ReminderFragment;
import com.YC2010.MyClass.ui.fragments.SearchFragment;
import com.YC2010.MyClass.ui.fragments.SettingFragment;
import com.YC2010.MyClass.ui.fragments.SubjectsFragment;
import com.YC2010.MyClass.utils.Constants;

import java.util.ArrayList;
//import com.facebook.AccessToken;
//import com.facebook.AccessTokenTracker;
//import com.facebook.CallbackManager;
//import com.facebook.FacebookCallback;
//import com.facebook.FacebookException;
//import com.facebook.FacebookSdk;
//import com.facebook.GraphRequest;
//import com.facebook.GraphResponse;
//import com.facebook.HttpMethod;
//import com.facebook.Profile;
//import com.facebook.ProfileTracker;
//import com.facebook.appevents.AppEventsLogger;
//import com.facebook.login.LoginManager;
//import com.facebook.login.LoginResult;
//import com.facebook.login.widget.LoginButton;


public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener,
        AdapterView.OnItemSelectedListener{

    /**
     * Fragment managing the behaviors, interactions and presentation of the navigation drawer_menu.
     */
    private Toolbar mToolbar;
    private NavigationView mNavigationView;
    private DrawerLayout mDrawerLayout;

    private CharSequence mTitle;
    private CharSequence currentTitle;
//    CallbackManager callbackManager;
//    AccessTokenTracker accessTokenTracker;
//    AccessToken accessToken;
//    ProfileTracker profileTracker;

    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_COURSE = "COURSE";
    private static final String TITLE_KEY = "title key";

    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        Log.d("MainActivity", "enter onCreate");
        super.onCreate(savedInstanceState);

        // update ALL terms in sharedPreference
        new AsyncTask<Void, Void, Void>() {
            @Override
            protected Void doInBackground(Void... params) {
                try {
                    ArrayList<Integer> termNumList = Connections.getTerms().getIntegerArrayList("KEY_TERM_NUM");
                    ArrayList<String> termNameList = Connections.getTerms().getStringArrayList("KEY_TERM_NAME");

                    if (termNumList != null) {
                        getSharedPreferences("TERMS", MODE_PRIVATE)
                                .edit()
                                .putInt("CURRENT_TERM", termNumList.get(1))
                                .putInt("NEXT_TERM", termNumList.get(2))
                                .apply();
                    }
                    if (termNameList != null) {
                        getSharedPreferences("TERMS", MODE_PRIVATE)
                                .edit()
                                .putString("CURRENT_TERM_NAME", termNameList.get(1) + " (Current)")
                                .putString("NEXT_TERM_NAME", termNameList.get(2) + " (Next)")
                                .apply();
                    }
                }
                catch (Exception e) {
                    e.printStackTrace();
                }
                return null;
            }

        }.execute();

        if (savedInstanceState != null){
            // get title out
            mTitle = savedInstanceState.getCharSequence(TITLE_KEY);
        }
        setContentView(R.layout.activity_main);

        mToolbar = (Toolbar) findViewById(R.id.toolbar_actionbar);
        setSupportActionBar(mToolbar);

        if (savedInstanceState == null) Log.d("MainActivity", "savedInstanceState is null");
        else Log.d("MainActivity", "savedInstanceState is NOT null");

        //Initializing NavigationView
        mNavigationView = (NavigationView) findViewById(R.id.navigation_view);

        //Setting Navigation View Item Selected Listener to handle the item click of the navigation menu
        mNavigationView.setNavigationItemSelectedListener(this);

        // make the profile image as a circle
        ImageView profileImageContainer = (ImageView) mNavigationView.getHeaderView(0).findViewById(R.id.profile_image);
        profileImageContainer.setImageDrawable((new RoundImage(BitmapFactory.decodeResource(getResources(), R.drawable.avatar))));

        // show calendar initially, before any drawer_menu item select
        if (savedInstanceState == null) {
            mNavigationView.getMenu().getItem(0).setChecked(true);
            mTitle = getString(R.string.title_MyClass);
            getFragmentManager().beginTransaction()
                    .replace(R.id.container, new CalendarFragment())
                    .addToBackStack("0")
                    .commit();
            if (mToolbar != null) {
                mToolbar.setTitle(mTitle);
            }
        }

        // Initializing Drawer Layout and ActionBarToggle
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer);
        ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this,mDrawerLayout,mToolbar,R.string.drawer_openDrawer, R.string.drawer_closeDrawer){
            @Override
            public void onDrawerClosed(View drawerView) {
                // Code here will be triggered once the drawer_menu closes as we don't want anything to happen so we leave this blank
                super.onDrawerClosed(drawerView);
            }

            @Override
            public void onDrawerOpened(View drawerView) {
                // Code here will be triggered once the drawer_menu open as we don't want anything to happen so we leave this blank
                super.onDrawerOpened(drawerView);
            }
        };

        // set up the term spinner
        Spinner termSpinner = (Spinner) mNavigationView.getHeaderView(0).findViewById(R.id.term_spinner);
        // Create an ArrayAdapter using the string array and a default spinner layout
        ArrayList<String> termStrings = new ArrayList<>();
        termStrings.add(0, getSharedPreferences("TERMS", MODE_PRIVATE).getString("CURRENT_TERM_NAME", Constants.defaultCurTermName));
        termStrings.add(1, getSharedPreferences("TERMS", MODE_PRIVATE).getString("NEXT_TERM_NAME", Constants.defaultNextTermName));
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, termStrings);
        // Specify the layout to use when the list of choices appears
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        // Apply the adapter to the spinner
        termSpinner.setAdapter(adapter);
        ArrayList<Integer> termInts = new ArrayList<>();
        termInts.add(0, getSharedPreferences("TERMS", MODE_PRIVATE).getInt("CURRENT_TERM", Constants.defaultCurTermNum));
        termInts.add(1, getSharedPreferences("TERMS", MODE_PRIVATE).getInt("NEXT_TERM", Constants.defaultNextTermNum));
        termSpinner.setSelection(termInts.indexOf(getSharedPreferences("TERMS", MODE_PRIVATE).getInt("TERM_NUM", termInts.get(0))));
        termSpinner.setOnItemSelectedListener(this);

        //Setting the actionbarToggle to drawer_menu layout
        mDrawerLayout.setDrawerListener(actionBarDrawerToggle);

        //calling sync state is necessay or else your hamburger icon wont show up
        actionBarDrawerToggle.syncState();

        checkFirstRun();


//        /* Facebook stuff starts */
//        FacebookSdk.sdkInitialize(getApplicationContext());
//        callbackManager = CallbackManager.Factory.create();
//
//        accessTokenTracker = new AccessTokenTracker() {
//            @Override
//            protected void onCurrentAccessTokenChanged(
//                    AccessToken oldAccessToken,
//                    AccessToken currentAccessToken) {
//                // Set the access token using
//                // currentAccessToken when it's loaded or set.
//            }
//        };
//        // If the access token is available already assign it.
//        accessToken = AccessToken.getCurrentAccessToken();
//        profileTracker = new ProfileTracker() {
//            @Override
//            protected void onCurrentProfileChanged(
//                    Profile oldProfile,
//                    Profile currentProfile) {
//                // App code
//            }
//        };
//        /* Facebook stuff ends */

    }

    @Override
    protected void onStop() {
        Log.d("MainActivity", "enter onStop");
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        Log.d("MainActivity", "enter onDestroy");
        //Toast.makeText(getApplicationContext(), "onDestroy", Toast.LENGTH_LONG).show();
        super.onDestroy();

        // Facebook Related Code
//        accessTokenTracker.stopTracking();
//        profileTracker.stopTracking();

    }

    @Override
    protected void onResume() {
        super.onResume();

        // Logs 'install' and 'app activate' App Events.
//        AppEventsLogger.activateApp(this);
    }

    @Override
    protected void onPause() {
        super.onPause();

        // Logs 'app deactivate' App Event.
//        AppEventsLogger.deactivateApp(this);
    }

    @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {
        // convert stack into arraylist
        savedInstanceState.putCharSequence(TITLE_KEY, mTitle);
        super.onSaveInstanceState(savedInstanceState);
    }

    @Override
    public void onBackPressed() {
        // pop title and fragment stack
        Log.d("MainActivity", "stack count is " + getFragmentManager().getBackStackEntryCount());
        if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
            mDrawerLayout.closeDrawer(GravityCompat.START);
        }
        else if (getFragmentManager().getBackStackEntryCount() <= 1) {
            moveTaskToBack(true);
        }
        else{
            FragmentManager.BackStackEntry backEntry=getFragmentManager().getBackStackEntryAt(getFragmentManager().getBackStackEntryCount()-1);
            String str = backEntry.getName();
            if(str.equals("0") || str.equals("1") || str.equals("2") || str.equals("3") || str.equals("4"))
                moveTaskToBack(true);
            else if(!str.equals("0") && !str.equals("1") && !str.equals("2") && !str.equals("3") && !str.equals("4"))
                getFragmentManager().popBackStackImmediate();
        }
    }

    public void checkFirstRun() {
        SharedPreferences sp = getSharedPreferences("PREFERENCE", MODE_PRIVATE);
        boolean isFirstRun = sp.getBoolean("isFirstRun", true);
        if (isFirstRun){
            sp.edit()
                    .putBoolean("isFirstRun", false)
                    .apply();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // search button
        getMenuInflater().inflate(R.menu.main_activity_actions, menu);
        final MenuItem searchItem = menu.findItem(R.id.action_search);
        SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                Log.d("MainActivity", "Text Submitted");
                MenuItemCompat.collapseActionView(searchItem);

                // pass query into the fragment through a bundle
                SearchFragment mSearchFragment = new SearchFragment();
                Bundle args = new Bundle();
                args.putString(ARG_COURSE, query);
                mSearchFragment.setArguments(args);
                getFragmentManager().beginTransaction()
                        .replace(R.id.container, mSearchFragment)
                        .addToBackStack("7")
                        .commit();
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                return false;
            }
        });

        searchView.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean queryTextFocused) {
                if (!queryTextFocused) {
                    MenuItemCompat.collapseActionView(searchItem);
                }
            }
        });

        // if calendar is shown, show calendar action overflow
        if(mNavigationView.getMenu().getItem(0).isChecked()) {
            getMenuInflater().inflate(R.menu.calender_action_overflow, menu);
        }
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
//        int id = item.getItemId();
//
//        if (id == R.id.Login_FB_setting){
//            AlertDialog.Builder builder = new AlertDialog.Builder(this);
//
//            builder.setTitle("Log in to Facebook");
//            builder.setView(R.layout.facebook_login_dialog);
//
//            AlertDialog login_dialog = builder.create();
//            login_dialog.show();
//
//            LoginButton loginButton = (LoginButton) login_dialog.findViewById(R.id.login_button);
//            List<String> permissions = new ArrayList<String>();
//            permissions.add("user_friends");
//
//            LoginManager.getInstance().logInWithReadPermissions(
//                    this,
//                    Arrays.asList("user_events"));
//
//            loginButton.setReadPermissions(permissions);
//            // If using in a fragment
//            //loginButton.setFragment(new NativeFragmentWrapper(this));
//            // Other app specific specialization
//
//            // Callback registration
//            loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
//                @Override
//                public void onSuccess(LoginResult loginResult) {
//                    Log.d("MainActivity", "success");
//                    // App code
//                    Profile profile = Profile.getCurrentProfile();
//                    // change username
//                    Log.d("MainActivity", "got id is " + profile.getId() + " " + profile.getFirstName() +
//                            " " + profile.getLastName());
//
//                    String userID = profile.getId();
//
//                    new GraphRequest(
//                            AccessToken.getCurrentAccessToken(),
//                            "/" + userID + "/events",
//                            null,
//                            HttpMethod.GET,
//                            new GraphRequest.Callback() {
//                                public void onCompleted(GraphResponse response) {
//                            /* handle the result */
//                                    try {
//                                        Log.d("MainActivity", response.toString());
//                                        JSONArray eventsArray = response.getJSONObject().getJSONArray("data");
//                                        final ReminderDBHandler reminder_db = new ReminderDBHandler(getApplicationContext());
//                                        reminder_db.removeAll("fb");
//                                        Bundle parameters = new Bundle();
//                                        parameters.putString("fields", "id,name,start_time,place");
//                                        for (int i = 0; i < eventsArray.length(); i++) {
//                                            JSONObject mEvent = eventsArray.getJSONObject(i);
//                                            String eid = mEvent.getString("id");
//                                    /* make the API call */
//                                            GraphRequest request = new GraphRequest(
//                                                    AccessToken.getCurrentAccessToken(),
//                                                    "/" + eid,
//                                                    null,
//                                                    HttpMethod.GET,
//                                                    new GraphRequest.Callback() {
//                                                        public void onCompleted(GraphResponse response) {
//                                                    /* handle the result */
//                                                            try {
//                                                                //Log.d("MainActivity", response.toString());
//                                                                JSONObject event = response.getJSONObject();
//                                                                String loc = event.getJSONObject("place").getString("name");
//                                                                //String loc = "";
//                                                                String title = event.getString("name");
//                                                                String start_time = event.getString("start_time");
//                                                                DateFormat f1 = new SimpleDateFormat("yyyy-MM-dd'T'h:mm:ssZ", Locale.CANADA);
//                                                                Date d = f1.parse(start_time);
//                                                                final Reminder_item new_fb_events = new Reminder_item(UUID.randomUUID().toString(), title, loc, d.getTime(), "fb");
//
//                                                                SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
//                                                                Boolean exam_warning = sharedPref.getBoolean("pref_key_exam_warning", true);
//
//                                                                if (exam_warning && reminder_db.closoToExam(d)){
//                                                                    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
//                                                                    builder.setMessage(title + " has exams followed by within a week, do you still want to create this event?")
//                                                                            .setTitle("Event Warning");
//                                                                    builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {
//                                                                        @Override
//                                                                        public void onClick(DialogInterface dialogInterface, int i) {
//                                                                            reminder_db.addReminder(new_fb_events);
//
//                                                                        }
//                                                                    });
//                                                                    builder.setNegativeButton("NO", null);
//                                                                    AlertDialog dialog = builder.create();
//                                                                    dialog.show();
//
//
//                                                                }
//                                                                else
//                                                                    reminder_db.addReminder(new_fb_events);
//
//                                                            } catch (org.json.JSONException e) {
//                                                                e.printStackTrace();
//                                                            } catch (java.text.ParseException p) {
//                                                                p.printStackTrace();
//                                                            }
//                                                        }
//                                                    }
//                                            );
//                                            request.setParameters(parameters);
//                                            request.executeAsync();
//                                        }
//                                        reminder_db.close();
//                                    } catch (org.json.JSONException e) {
//                                        e.printStackTrace();
//                                    }
//                                }
//                            }
//                    ).executeAsync();
//                }
//
//                @Override
//                public void onCancel() {
//                    Log.d("MainActivity", "cancel");
//                    // App code
//                }
//
//                @Override
//                public void onError(FacebookException exception) {
//                    Log.d("MainActivity", "error");
//                    // App code
//                }
//            });
//
//            login_dialog.dismiss();
//        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.d("MainActivity", "got result");
        super.onActivityResult(requestCode, resultCode, data);
//        callbackManager.onActivityResult(requestCode, resultCode, data);
    }

    public static class RoundImage extends Drawable {
        private final Bitmap mBitmap;
        private final Paint mPaint;
        private final RectF mRectF;
        private final int mBitmapWidth;
        private final int mBitmapHeight;

        public RoundImage(Bitmap bitmap) {
            mBitmap = bitmap;
            mRectF = new RectF();
            mPaint = new Paint();
            mPaint.setAntiAlias(true);
            mPaint.setDither(true);
            final BitmapShader shader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
            mPaint.setShader(shader);

            mBitmapWidth = mBitmap.getWidth();
            mBitmapHeight = mBitmap.getHeight();
        }

        @Override
        public void draw(Canvas canvas) {
            canvas.drawOval(mRectF, mPaint);
        }

        @Override
        protected void onBoundsChange(Rect bounds) {
            super.onBoundsChange(bounds);
            mRectF.set(bounds);
        }

        @Override
        public void setAlpha(int alpha) {
            if (mPaint.getAlpha() != alpha) {
                mPaint.setAlpha(alpha);
                invalidateSelf();
            }
        }

        @Override
        public void setColorFilter(ColorFilter cf) {
            mPaint.setColorFilter(cf);
        }

        @Override
        public int getOpacity() {
            return PixelFormat.TRANSLUCENT;
        }

        @Override
        public int getIntrinsicWidth() {
            return mBitmapWidth;
        }

        @Override
        public int getIntrinsicHeight() {
            return mBitmapHeight;
        }

        public void setAntiAlias(boolean aa) {
            mPaint.setAntiAlias(aa);
            invalidateSelf();
        }

        @Override
        public void setFilterBitmap(boolean filter) {
            mPaint.setFilterBitmap(filter);
            invalidateSelf();
        }

        @Override
        public void setDither(boolean dither) {
            mPaint.setDither(dither);
            invalidateSelf();
        }

        public Bitmap getBitmap() {
            return mBitmap;
        }
    }



    /*** Here begins all listeners ***/

    /**************** implements NavigationView.OnNavigationItemSelectedListener ****************/
    @Override
    public boolean onNavigationItemSelected(MenuItem menuItem) {
        Log.d("MainActivity", "onNavigationItemSelected");
        mDrawerLayout.closeDrawers();

        //Checking if the item is in checked state or not, if not make it in checked state
        if (menuItem.isChecked()){
            //Closing drawer_menu on item click
            return true;
        }

        menuItem.setChecked(true);

        //Check to see which item was being clicked and perform appropriate action
        switch (menuItem.getItemId()) {
            case R.id.drawer_Calender:
                mTitle = getString(R.string.title_MyClass);
                getFragmentManager().beginTransaction()
                        .replace(R.id.container, new CalendarFragment())
                        .addToBackStack("0")
                        .commit();
                break;
            case R.id.drawer_Courses:
                mTitle = getString(R.string.title_Courses);
                getFragmentManager().beginTransaction()
                        .replace(R.id.container, new CoursesFragment())
                        .addToBackStack("1")
                        .commit();
                break;
            case R.id.drawer_Course_Select:
                mTitle = getString(R.string.title_Course_Select);
                getFragmentManager().beginTransaction()
                        .replace(R.id.container, new SubjectsFragment())
                        .addToBackStack("2")
                        .commit();
                break;
            case R.id.drawer_Reminder:
                mTitle = getString(R.string.title_Reminder);
                getFragmentManager().beginTransaction()
                        .replace(R.id.container, new ReminderFragment())
                        .addToBackStack("3")
                        .commit();
                break;
            case R.id.drawer_Settings:
                mTitle = getString(R.string.title_Settings);
                getFragmentManager().beginTransaction()
                        .replace(R.id.container, new SettingFragment())
                        .addToBackStack("4")
                        .commit();
                break;
            default:
                Toast.makeText(getApplicationContext(), "undefine drawer item selected, please report to the developer", Toast.LENGTH_LONG).show();
                break;
        }

        if (mToolbar != null) {
            mToolbar.setTitle(mTitle);
        }
        return true;
    }


    /**************** AdapterView.OnItemSelectedListener(Term Selection) ****************/
    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        SharedPreferences termSharedPreferences = getSharedPreferences("TERMS", MODE_PRIVATE);
        // search for term id and add it into shared preference
        int selectedTermID = 200;
        Log.d("MainActivity", "selected item is " + parent.getItemAtPosition(position) + ", " + termSharedPreferences.getString("CURRENT_TERM_NAME", Constants.defaultCurTermName));
        if (parent.getItemAtPosition(position).equals(termSharedPreferences.getString("CURRENT_TERM_NAME", Constants.defaultCurTermName))){
            selectedTermID = termSharedPreferences.getInt("CURRENT_TERM", Constants.defaultCurTermNum);
        }
        if (parent.getItemAtPosition(position).equals(termSharedPreferences.getString("NEXT_TERM_NAME", Constants.defaultNextTermName))){
            selectedTermID = termSharedPreferences.getInt("NEXT_TERM", Constants.defaultNextTermNum);
        }
        Log.d("MainActivity", "selectedTermID is " + selectedTermID);

        if (termSharedPreferences.getInt("TERM_NUM", -1) ==  -1){
            termSharedPreferences.edit().putInt("TERM_NUM", selectedTermID).apply();
        }
        else if (termSharedPreferences.getInt("TERM_NUM", -1) != selectedTermID) {
            termSharedPreferences.edit().putInt("TERM_NUM", selectedTermID).apply();

            // get back to the calender view
            mDrawerLayout.closeDrawers();
            mNavigationView.getMenu().getItem(0).setChecked(true);
            mTitle = getString(R.string.title_MyClass);
            getFragmentManager().beginTransaction()
                    .replace(R.id.container, new CalendarFragment())
                    .addToBackStack("0")
                    .commit();
            if (mToolbar != null) {
                mToolbar.setTitle(mTitle);
            }

            Toast.makeText(getApplicationContext(), "Change term to " + parent.getItemAtPosition(position),
                    Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }
}


<|start_filename|>app/src/main/java/com/YC2010/MyClass/model/TutorialObject.java<|end_filename|>
package com.YC2010.MyClass.model;

import android.os.Parcel;
import android.os.Parcelable;

/**
 * Created by Danny on 2015/10/17.
 */
public class TutorialObject implements Parcelable {
    private String number;
    private String section;
    private String time;
    private String location;
    private String capacity;
    private String total;

    public TutorialObject() {}

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(number);
        dest.writeString(section);
        dest.writeString(time);
        dest.writeString(location);
        dest.writeString(capacity);
        dest.writeString(total);
    }

    public TutorialObject(Parcel src) {
        this.number = src.readString();
        this.section = src.readString();
        this.time = src.readString();
        this.location = src.readString();
        this.capacity = src.readString();
        this.total = src.readString();
    }

    public static final Creator CREATOR = new Creator() {
        @Override
        public TutorialObject createFromParcel(Parcel source) {
            return new TutorialObject(source);
        }

        @Override
        public TutorialObject[] newArray(int size) {
            return new TutorialObject[size];
        }
    };

    public void setTotal(String total) {
        this.total = total;
    }

    public void setSection(String section) {
        this.section = section;
    }

    public void setTime(String time) {
        this.time = time;
    }

    public void setCapacity(String capacity) {
        this.capacity = capacity;
    }

    public void setNumber(String number) {
        this.number = number;
    }

    public void setLocation(String location) {
        this.location = location;
    }

    public String getNumber() {
        return number;
    }

    public String getSection() {
        return section;
    }

    public String getTime() {
        return time;
    }

    public String getLocation() {
        return location;
    }

    public String getCapacity() {
        return capacity;
    }

    public String getTotal() {
        return total;
    }
}
