Thursday, 11 June 2015

Active alarms class

package com.siliconicpro.admin.ialarm;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.ListFragment;
import android.view.ActionMode;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;

public class Active extends ListFragment {
    private ListView list;
    private static ArrayList<Long> alarm_ids = new ArrayList<>(); // List of Selected Alarms
    private int flag = 1; // To activate Multi-Select Action Mode
    private long action_mode_id; // Alarm Id which activates Action Mode
    private Boolean select_all_toggle = false;
    private int counter = 0; // Used with select_all_toggle

    // Sends Selected Alarm Ids
    public static ArrayList<Long> getAlarm_ids() {
        return alarm_ids;
    }

    // Refresh active alarms list
    public void refreshAdapter(int layout){
        // Saving position of Scroll Bar
        int first_pos = list.getFirstVisiblePosition();
        View first_view = list.getChildAt(0);
        int top = 0;
        if (first_view != null) {
            top = first_view.getTop() - list.getPaddingTop();
        }
        // Getting Data of Active Alarms
        Cursor c = AlarmsTable.getActArcData(Home.getDop(), 1); // 1 for Active, 0 for Archive
        // Refreshing the List with New Layout
        setListAdapter(new myAdapter(getActivity(), c, 0, layout, 1));
        // Restoring position of Scroll Bar
        list.setSelectionFromTop(first_pos, top);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.active, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable final Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        list = getListView();
        // Getting Data of Active Alarms
        Cursor c = AlarmsTable.getActArcData(Home.getDop(), 1); // 1 for Active, 0 for Archive
        final myAdapter adapter = new myAdapter(getActivity(), c, 0, R.layout.row_layout, 1);
        setListAdapter(adapter);

    //--------------------------------Start of Multi Selection Mode----------------------------

        list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
        list.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
            @Override
            public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
                // Showing list of Checkable Alarms to Delete
                // Executes only 1st Time When Action Mode is Activated
                if(flag == 1){
                    // showing new list
                    refreshAdapter(R.layout.row_layout_sel);
                    // Alarm ID which Activated Action Mode
                    action_mode_id = id;
                    checked = false;
                    flag = 0;
                }

                // Select All Issue Solution
                // Opposite Behaviour to Parameter (Not for action_mode_id)
                if(select_all_toggle && id != action_mode_id){
                    checked = !checked;
                }
                // Opposite Behaviour to Parameter (Only for action_mode_id)
                if(counter != 0 && counter % 2 == 0 && id == action_mode_id){
                    checked = !checked;
                }

                // Not Executes 1st Time as checked == false (else part executes)
                // If Alarm is Selected (Checked)
                if(checked) {
                    // action_mode_id is Removed when Selected
                    // If Selected ID is action_mode_id then Remove because it was
                    // selected by default on Long Press.
                    if(id == action_mode_id){
                        alarm_ids.remove(id);
                    }
                    else {
                        // Checking if Current ID is Unique
                        int temp = 1;
                        for (Long i : alarm_ids) {
                            if (i == id) {
                                temp = 0;
                            }
                        }
                        // Adding only Unique IDs
                        if (temp == 1) {
                            alarm_ids.add(id);
                        }
                    }
                }
                // If Alarm is Unselected
                else{
                    // action_mode_id is Added when Unselected
                    if(id == action_mode_id) {
                        alarm_ids.add(id);
                    }
                    else{
                        alarm_ids.remove(id);
                    }
                }

                // Not Executes 1st Time Because getChildCount == 0 first Time
                if(list.getChildCount() > 0) {
                    View view = list.getChildAt(position - list.getFirstVisiblePosition());
                    CheckBox box = (CheckBox) view.findViewById(R.id.sel_unsel);
                    if(!box.isChecked()) {
                        box.setChecked(true); // Toggle State
                    } else {
                        box.setChecked(false); // Toggle State
                    }
                    if(!alarm_ids.isEmpty()){
                        // Setting Title of the Screen
                        mode.setTitle(alarm_ids.size() + " Selected");
                    }
                    // Ending Action Mode
                    if(alarm_ids.isEmpty()) {
                        mode.finish();
                    }
                }
                // Executes only 1st Time
                else{
                    // Setting Title of the Screen
                    mode.setTitle(alarm_ids.size() + " Selected");
                }
            }

            @Override
            public boolean onCreateActionMode(ActionMode mode, Menu menu) {
                MenuInflater inflater = mode.getMenuInflater();
                inflater.inflate(R.menu.multi_sel_active, menu);
                return true;
            }

            @Override
            public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
                return false;
            }

            @Override
            public boolean onActionItemClicked(final ActionMode mode, MenuItem item) {
                switch (item.getItemId()){
                    case R.id.delete_alarm:
                        // Deleting Selected Alarms by the User
                        if(alarm_ids.isEmpty()){
                            Toast.makeText(getActivity(), "Nothing Selected", Toast.LENGTH_SHORT).show();
                        }
                        else {
                            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                            builder.setTitle("Delete")
                                    .setIcon(getResources().getDrawable(R.drawable.ic_action_delete))
                                    .setMessage("Selected alarms will be deleted!")
                                    .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            for (long id : alarm_ids) {
                                                // Deleting from Database
                                                AlarmsTable.deleteAlarm(id, Home.getDop());
                                                // Deleting from System
                                                Home.cancelAlarm(getActivity(), id);
                                            }
                                            mode.finish();
                                            Toast.makeText(getActivity(), "Alarm deleted successfully", Toast.LENGTH_LONG).show();
                                            dialog.cancel();
                                        }
                                    })
                                    .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            mode.finish();
                                            dialog.cancel();
                                        }
                                    });
                            builder.show();
                        }
                        break;
                    case R.id.select_all:
                        select_all_toggle = !select_all_toggle;
                        counter++;
                        // Getting Data of Active Alarms
                        Cursor c = AlarmsTable.getActArcData(Home.getDop(), 1); // 1 for Active, 0 for Archive
                        if(select_all_toggle) {
                            alarm_ids.clear();
                            // Adding all Row IDs of Alarms (Selecting All)
                            // do-while as cursor is already at 1st Row
                            do
                            {
                                long j = c.getInt(c.getColumnIndex(AlarmsTable._id));
                                alarm_ids.add(j);
                            }while(c.moveToNext());
                            c.close();
                            // Setting Title
                            mode.setTitle(alarm_ids.size() + " Selected");
                            // Refreshing List Adapter
                            refreshAdapter(R.layout.row_layout_sel);
                        }
                        else{
                            // Removing all Row IDs of Alarms (Un-Selecting All)
                            alarm_ids.clear();
                            // Setting Title
                            mode.setTitle("No Selection");
                            // Refreshing List Adapter
                            refreshAdapter(R.layout.row_layout_sel);
                        }
                        break;
                    case R.id.move:
                        // Moving Alarms to Archive
                        for (long id : alarm_ids) {
                            AlarmsTable.updateActArcStatus((int) id, 0, Home.getDop()); // Move to Archive
                            AlarmsTable.updateSysTime((int)id, Home.getDop()); // Show on Top
                            int status = AlarmsTable.getAlarmStatus((int)id, Home.getDop());
                            if(status == 1){
                                // Turning Off
                                AlarmsTable.updateAlarmStatus((int) id, 0, Home.getDop());
                                // Deleting from System
                                Home.cancelAlarm(getActivity(), id);
                            }
                        }
                        mode.finish();
                        // Refresh all Pages of View Pager
                        refreshViewPager();
                        Toast.makeText(getActivity(), "Alarm moved to Archive Section", Toast.LENGTH_SHORT).show();
                        break;
                }
                return true;
            }

            @Override
            public void onDestroyActionMode(ActionMode mode) {
                alarm_ids.clear();
                // Showing normal list
                refreshAdapter(R.layout.row_layout);
                // Re-Setting Multi-Selection Mode Flag
                flag = 1;
                // Re-Setting Select All Toggle
                select_all_toggle = false;
                // Re-Setting counter
                counter = 0;
            }
        });
    }

    //--------------------------------End of Multi Selection Mode-------------------------------

    @Override
    public void onListItemClick(ListView l, View v, int position, final long id) {
        super.onListItemClick(l, v, position, id);
        Intent intent = new Intent(getActivity(), AlarmDetails.class);
        Cursor cursor = AlarmsTable.getAlarm(Home.getDop(), Long.toString(id));
        intent.putExtra("id", Long.toString(id));
        intent.putExtra("time", cursor.getString(cursor.getColumnIndex(AlarmsTable.TIME)));
        intent.putExtra("date", cursor.getString(cursor.getColumnIndex(AlarmsTable.DATE)));
        intent.putExtra("interval", Integer.toString(cursor.getInt(cursor.getColumnIndex(AlarmsTable.INTERVAL))));
        intent.putExtra("repeat", Integer.toString(cursor.getInt(cursor.getColumnIndex(AlarmsTable.REPEAT))));
        intent.putExtra("title", cursor.getString(cursor.getColumnIndex(AlarmsTable.TITLE)));
        intent.putExtra("alert1", cursor.getString(cursor.getColumnIndex(AlarmsTable.ALERT_1)));
        intent.putExtra("alert2", cursor.getString(cursor.getColumnIndex(AlarmsTable.ALERT_2)));
        intent.putExtra("snooze", cursor.getString(cursor.getColumnIndex(AlarmsTable.SNOOZE)));
        intent.putExtra("location", cursor.getString(cursor.getColumnIndex(AlarmsTable.LOCATION)));
        intent.putExtra("url", cursor.getString(cursor.getColumnIndex(AlarmsTable.URL)));
        intent.putExtra("description", cursor.getString(cursor.getColumnIndex(AlarmsTable.DESCRIPTION)));
        intent.putExtra("status", Integer.toString(cursor.getInt(cursor.getColumnIndex(AlarmsTable.STATUS))));
        intent.putExtra("active_archive", Integer.toString(cursor.getInt(cursor.getColumnIndex(AlarmsTable.ACT_ARC))));
        cursor.close();
        startActivity(intent);
    }

    // Refresh All Pages of View Pager
    private void refreshViewPager() {
        List<Fragment> fragments = new ArrayList<>();
        fragments.add(new Active());
        fragments.add(new Archive());
        myPagerAdapter adapter = new myPagerAdapter(getActivity().getSupportFragmentManager(), getActivity(), fragments);
        Home.viewPager.setAdapter(adapter);
        Home.viewPager.setCurrentItem(0); // Active List of Alarms
    }
}

No comments:

Post a Comment