Thursday, 11 June 2015

Settings table class

package com.siliconicpro.admin.ialarm;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;

import com.siliconicpro.admin.ialarm.R;

public class SettingsTable{

    /*...............................Table and Columns Names..............................*/

    public static final String SETTINGS_TABLE = "settingsTable"; // Table name
    public static final String RINGTONE = "ringTone";
    private static String[] columns = {RINGTONE};

    /*..................................Queries of Table................................*/

    // create table
    public static final String CREATE_SETTINGS_TABLE =
                     "CREATE TABLE " + SETTINGS_TABLE + " ("+ RINGTONE + " VARCHAR(255));";
    // delete table
    public static final String DROP_SETTINGS_TABLE = "DROP TABLE IF EXISTS "+SETTINGS_TABLE+";";

    /*...................................TABLE Methods..................................*/

    public static void insertDefaultRow(SQLiteDatabase db){
        // Creating default row for SETTINGS TABLE
        ContentValues contentValues = new ContentValues();
        contentValues.put(RINGTONE, getDefaultUri());
        db.insert(SETTINGS_TABLE, null, contentValues);
    }

    // Runs only when app is opened 1st time
    private static String getDefaultUri() {
        Uri uri = RingtoneManager.getActualDefaultRingtoneUri(Home.getContext(), RingtoneManager.TYPE_RINGTONE);
        return String.valueOf(uri);
    }

    public static Uri getUri(DatabaseOperations dop){
        SQLiteDatabase db = dop.getReadableDatabase();
        Cursor cursor = db.query(SETTINGS_TABLE, columns, null, null, null, null, null);
        cursor.moveToFirst();
        String uri = cursor.getString(cursor.getColumnIndex(RINGTONE));
        db.close();
        return Uri.parse(uri);
    }

    public static Cursor getSettingsData(DatabaseOperations dop){
        SQLiteDatabase db = dop.getReadableDatabase();
        Cursor cursor = db.query(SETTINGS_TABLE, columns, null, null, null, null, null);
        cursor.moveToFirst();
        db.close();
        return cursor;
    }

    public static void updateRingTone(String ringtone, DatabaseOperations dop) {
        SQLiteDatabase db = dop.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(RINGTONE, ringtone);
        db.update(SETTINGS_TABLE, contentValues, null, null);
        db.close();
    }

}

Settings screen class

package com.siliconicpro.admin.ialarm;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class Settings extends ActionBarActivity implements View.OnClickListener{

    private static TextView ringToneSelect;
    private String saved_uri = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.settings);

        ActionBar ab = getSupportActionBar();
        ColorDrawable colorDrawable = new ColorDrawable(Color.parseColor("#ff156514"));
        ab.setBackgroundDrawable(colorDrawable);

        // initializing all variables
        RelativeLayout ringTone = (RelativeLayout)findViewById(R.id.ringtone);
        ringToneSelect = (TextView)findViewById(R.id.ring_tone_select);

        // showing all data of SETTINGS_TABLE from DATABASE
        showSettingsData();

        // setting On Click Listener
        ringTone.setOnClickListener(this);
    }

    public void showSettingsData(){
        Cursor c = SettingsTable.getSettingsData(Home.getDop());
        String uri = c.getString(c.getColumnIndex(SettingsTable.RINGTONE));
        Ringtone ringtone = RingtoneManager.getRingtone(this, Uri.parse(uri));
        String title = ringtone.getTitle(this);
        ringToneSelect.setText(title);
        c.close();
    }

    @Override
    public void onClick(View v) {
        switch(v.getId()){
            case R.id.ringtone:
                // Showing Popup of System Built-in RingTones
                Intent tone_intent = new Intent(RingtoneManager.ACTION_RINGTONE_PICKER);
                tone_intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE, RingtoneManager.TYPE_ALL);
                tone_intent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_SILENT, false);
                tone_intent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_DEFAULT, false);
                tone_intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TITLE, "Select Alarm Tone");
                // Showing Current Selection in Popup
                if (saved_uri != null) {
                    // if Popup Opens 2nd+ Time
                    tone_intent.putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI, Uri.parse(saved_uri));
                } else {
                    // if Popup Opens 1st Time
                    tone_intent.putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI, SettingsTable.getUri(Home.getDop()));
                }
                startActivityForResult(tone_intent, 0);
                break;

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(resultCode == RESULT_OK){
            //sends the ringtone that is picked in the Ringtone Picker Dialog
            Uri uri = data.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);
            saved_uri = uri.toString();
            Ringtone ringtone = RingtoneManager.getRingtone(this, uri);
            String title = ringtone.getTitle(this);
            ringToneSelect.setText(title);
            try
            {
                // Storing in Database
                SettingsTable.updateRingTone(String.valueOf(uri), Home.getDop());
            }
            catch (Exception localException)
            {
                Toast.makeText(this, "error", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle savedInstanceState){
        // Save the state before orientation change
        savedInstanceState.putString("ringTone", ringToneSelect.getText().toString());
        savedInstanceState.putString("savedUri", saved_uri);
        super.onSaveInstanceState(savedInstanceState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState){
        super.onRestoreInstanceState(savedInstanceState);
        // Restore the state after orientation change
        ringToneSelect.setText(savedInstanceState.getString("ringTone"));
        saved_uri = savedInstanceState.getString("savedUri");
    }
}



Notification receiver class

package com.siliconicpro.admin.ialarm;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class NReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Intent intent1 = new Intent(context, Transparent.class);
        intent1.putExtra("id", intent.getExtras().getString("id"));
        intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent1);
    }
}

New alarm class

package com.siliconicpro.admin.ialarm;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.NumberPicker;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import com.cocosw.bottomsheet.BottomSheet;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class NewAlarm extends ActionBarActivity implements View.OnClickListener{

    private RelativeLayout repeat, snooze_;
    private CheckBox repeatCheck;
    private TextView time, date;
    private static TextView alert1, alert2, snooze, interval;
    private static Boolean snoozeForAll = false;
    private EditText title, description, url, location;
    private DateFormat timeFormat = new SimpleDateFormat("hh:mm aa");
    private DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
    private Calendar time_cal, date_cal;
    private int days=0, hours=0, min=0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.new_alarm);

        ActionBar ab = getSupportActionBar();
        ColorDrawable colorDrawable = new ColorDrawable(Color.parseColor("#ff156514"));
        ab.setBackgroundDrawable(colorDrawable);

        repeat = (RelativeLayout)findViewById(R.id.alarm_repeat);
        snooze_ = (RelativeLayout)findViewById(R.id.snooze);
        repeatCheck = (CheckBox)findViewById(R.id.alarm_repeat_check);
        time = (TextView)findViewById(R.id.time_value);
        date = (TextView)findViewById(R.id.date_value);
        alert1 = (TextView)findViewById(R.id.alert1);
        alert2 = (TextView)findViewById(R.id.alert2);
        snooze = (TextView)findViewById(R.id.snooze_value);
        interval = (TextView)findViewById(R.id.interval_value);
        title = (EditText)findViewById(R.id.title_value);
        url = (EditText)findViewById(R.id.url_value);
        location = (EditText)findViewById(R.id.loaction_value);
        description = (EditText)findViewById(R.id.decription_value);
        time_cal = Calendar.getInstance();
        date_cal = Calendar.getInstance();

        // Default snooze time
        String snoozeTime = AlarmsTable.getDefaultSnooze(Home.getDop());
        if(snoozeTime.equals("")){
            snooze.setText(getResources().getString(R.string.default_snooze));
        }
        else {
            snooze.setText(snoozeTime);
        }

        // On Click Listener
        time.setOnClickListener(this);
        date.setOnClickListener(this);
        interval.setOnClickListener(this);
        alert1.setOnClickListener(this);
        alert2.setOnClickListener(this);
        snooze_.setOnClickListener(this);
        repeat.setOnClickListener(this);

        // To Check if Soft Keyboard is Opened/Closed
        final View activityRootView = findViewById(R.id.scrollView);
        activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                Rect r = new Rect();
                //r will be populated with the coordinates of your view that area still visible.
                activityRootView.getWindowVisibleDisplayFrame(r);

                int heightDiff = activityRootView.getRootView().getHeight() - (r.bottom - r.top);
                // Opened
                if (heightDiff > 100) { // if more than 100 pixels, its probably a keyboard...
                    // Disabling Click Events on Screen
                    //set_Clickable(false);
                }
                // Closed
                else{
                    // Enabling Click Events on Screen
                    //set_Clickable(true);
                }
            }
        });

        // Getting and Setting system time and date
        time.setText(timeFormat.format(new Date()));
        date.setText(dateFormat.format(new Date()));
    }

    // Setting Clickable States if Keyboard is Opened/Closed
    public void set_Clickable(Boolean clickable){
        time.setClickable(clickable);
        date.setClickable(clickable);
        interval.setClickable(clickable);
        repeat.setClickable(clickable);
        alert1.setClickable(clickable);
        alert2.setClickable(clickable);
        snooze_.setClickable(clickable);
        title.setClickable(clickable);
        description.setClickable(clickable);
        url.setClickable(clickable);
        location.setClickable(clickable);
    }

    @Override
    public void onClick(View v) {
        switch(v.getId()){
            case R.id.time_value:
                // Launch Time Picker dialog
                TimePickerDialog tpd = new TimePickerDialog(this,
                        new TimePickerDialog.OnTimeSetListener() {
                            @Override
                            public void onTimeSet(TimePicker view, int hourOfDay,
                                                  int minute) {
                                // Display Selected time in textView
                                time_cal.set(Calendar.HOUR_OF_DAY, hourOfDay);
                                time_cal.set(Calendar.MINUTE, minute);
                                time.setText(timeFormat.format(time_cal.getTime()));
                            }
                        }, time_cal.get(Calendar.HOUR_OF_DAY), time_cal.get(Calendar.MINUTE), false);
                tpd.show();
                break;
            case R.id.date_value:
                // Launch Date Picker Dialog
                DatePickerDialog dpd = new DatePickerDialog(this,
                        new DatePickerDialog.OnDateSetListener() {
                            @Override
                            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                                // Display Selected date in textView
                                date_cal.set(Calendar.YEAR, year);
                                date_cal.set(Calendar.MONTH, monthOfYear);
                                date_cal.set(Calendar.DAY_OF_MONTH, dayOfMonth);
                                date.setText(dateFormat.format(date_cal.getTime()));
                            }
                        }, date_cal.get(Calendar.YEAR), date_cal.get(Calendar.MONTH), date_cal.get(Calendar.DAY_OF_MONTH));
                dpd.show();
                break;
            case R.id.interval_value:
                // Showing Dialog for Minutes, Hours, Days
                showIntervalPicker();
                break;
            case R.id.alarm_repeat:
                repeatCheck.toggle();
                break;
            case R.id.alert1:
                AlertDialog_ alert1 = new AlertDialog_();
                Bundle args1 = new Bundle();
                args1.putInt("flag", 1);
                alert1.setArguments(args1);
                alert1.show(getSupportFragmentManager(), "alert1");
                break;
            case R.id.alert2:
                AlertDialog_ alert2 = new AlertDialog_();
                Bundle args2 = new Bundle();
                args2.putInt("flag", 2);
                alert2.setArguments(args2);
                alert2.show(getSupportFragmentManager(), "alert2");
                break;
            case R.id.snooze:
                AutoSilence autoSilenceDialog = new AutoSilence();
                autoSilenceDialog.show(getSupportFragmentManager(), "autoSilenceDialog");
                break;
        }
    }

    // To Hide Keyboard on Outside Touch
    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (v != null) {
                Rect outRect = new Rect();
                v.getGlobalVisibleRect(outRect);
                if (!outRect.contains((int)event.getRawX(), (int)event.getRawY())) {
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
        }
        return super.dispatchTouchEvent(event);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.new_alarm, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch(item.getItemId()) {
            // when user clicks on Add button
            case R.id.add:
                if (interval.getText().toString().equals(getResources().getString(R.string.minHourDay))) {
                    Toast.makeText(this, "Please Enter Interval Time!", Toast.LENGTH_LONG).show();
                } else if (title.getText().toString().equals("")) {
                    Toast.makeText(this, "Please Enter Title!", Toast.LENGTH_LONG).show();
                } else {
                    // Adding New Alarm into Database
                    String time_ = time.getText().toString();
                    String date_ = date.getText().toString();
                    int interval_ = getIntervalMinutes();
                    int repeatCheck_ = (repeatCheck.isChecked() ? 1 : 0);
                    String title_ = title.getText().toString();
                    String alert1_ = alert1.getText().toString();
                    String alert2_ = alert2.getText().toString();
                    String snooze_ = snooze.getText().toString();
                    String location_ = location.getText().toString();
                    String url_ = url.getText().toString();
                    String description_ = description.getText().toString();
                    // Getting Alarm Ring Time
                    long ringTime = Home.getRingTime(time_, date_, interval_);
                    // When Ring Time is greater than system time
                    if (ringTime > System.currentTimeMillis()) {
                        // Inserting alarm in database
                        long id = AlarmsTable.insertAlarm(time_, date_, interval_, repeatCheck_, title_, alert1_, alert2_,
                                snooze_, location_, url_, description_, Home.getDop());
                        if (snoozeForAll) {
                            AlarmsTable.setSnoozeTimeForAll(snooze_, Home.getDop());
                        }
                        // Creating alarm in System
                        Home.setNewAlarm(this, time_, date_, interval_, repeatCheck_, id, alert1_, alert2_);
                        // Showing Toast Notification
                        String ring_time = Home.ringTime(time_, date_, interval_);
                        Toast.makeText(this, "Alarm set on " + ring_time, Toast.LENGTH_LONG).show();
                        finish();
                    }
                    // When date is parsed but Ring Time is less than system time
                    else if (ringTime < System.currentTimeMillis() && ringTime != 0) {
                        Toast.makeText(this, "Not created as alarm time is in the past", Toast.LENGTH_LONG).show();
                    }
                    // When date is not parsed
                    else {
                        Toast.makeText(this, "Alarm not created!", Toast.LENGTH_LONG).show();
                    }
                }
                break;
            }
            return super.onOptionsItemSelected(item);
    }

    private int getIntervalMinutes() {
        int daysInMinutes = days * 24 * 60;
        int hoursInMinutes = hours * 60;
        return daysInMinutes + hoursInMinutes + min;
    }

    @Override
    protected void onSaveInstanceState(Bundle savedInstanceState){
        // Save the state before orientation change
        savedInstanceState.putString("time", time.getText().toString());
        savedInstanceState.putString("date", date.getText().toString());
        savedInstanceState.putString("interval", interval.getText().toString());
        savedInstanceState.putString("alert1", alert1.getText().toString());
        savedInstanceState.putString("alert2", alert2.getText().toString());
        savedInstanceState.putString("snooze", snooze.getText().toString());
        super.onSaveInstanceState(savedInstanceState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState){
        super.onRestoreInstanceState(savedInstanceState);
        // Restore the state after orientation change
        time.setText(savedInstanceState.getString("time"));
        date.setText(savedInstanceState.getString("date"));
        interval.setText(savedInstanceState.getString("interval"));
        alert1.setText(savedInstanceState.getString("alert1"));
        alert2.setText(savedInstanceState.getString("alert2"));
        snooze.setText(savedInstanceState.getString("snooze"));
    }

    // Dialog for Alert Times
    public static class AlertDialog_ extends DialogFragment {
        // Array of list values shown in dialog
        private String[] alerts;
        private String selected;
        private int index = -1;
        private int flag;

        @NonNull
        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            final String alerts[] = Home.getStringArray(getResources().getStringArray(R.array.alerts));
            flag = getArguments().getInt("flag");
            // determine selected index
            for(int i=0; i<alerts.length; i++){
                if(flag == 1) {
                    if (alerts[i].equals(alert1.getText().toString())) {
                        index = i;
                    }
                }
                else{
                    if (alerts[i].equals(alert2.getText().toString())) {
                        index = i;
                    }
                }
            }
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            builder.setTitle("Alert me before")
                    .setSingleChoiceItems(alerts, index, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            selected = alerts[which];
                            if(flag == 1){
                                alert1.setText(selected);
                            }
                            else{
                                alert2.setText(selected);
                            }
                            dialog.cancel();
                        }
                    })
                    .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                        }
                    });
            return builder.create();
        }
    }

    // Select Auto-Silence-Duration Alert Dialog
    public static class AutoSilence extends DialogFragment {
        // Array of list values shown in dialog
        private String[] durations;
        private String selected;
        private int index;

        @NonNull
        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            durations = getResources().getStringArray(R.array.snooze);
            // determine selected index
            for(int i=0; i<durations.length; i++){
                if(durations[i].equals(snooze.getText().toString())){
                    index = i;
                }
            }
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            builder.setTitle("Select Snooze Time")
                    .setSingleChoiceItems(durations, index, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            final DialogInterface snoozeDialog = dialog;
                            selected = durations[which];
                            new BottomSheet.Builder(getActivity(), R.style.BottomSheet_StyleDialog)
                                    .sheet(R.menu.bottomsheet)
                                    .listener(new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            switch (which) {
                                                case R.id.for_this:
                                                    snoozeForAll = false;
                                                    snooze.setText(selected);
                                                    snoozeDialog.cancel();
                                                    break;
                                                case R.id.for_all:
                                                    snoozeForAll = true;
                                                    snooze.setText(selected);
                                                    snoozeDialog.cancel();
                                                    break;
                                                case R.id.cancel:
                                                    snoozeDialog.cancel();
                                                    break;
                                            }
                                        }
                                    }).show();
                        }
                    })
                    .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                        }
                    });
            return builder.create();
        }
    }

    // Days/hours/min Picker Dialog
    public void showIntervalPicker(){
        LayoutInflater inflater = (LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = inflater.inflate(R.layout.number_picker, null);
        final NumberPicker daysPicker = (NumberPicker) view.findViewById(R.id.picker1);
        final NumberPicker hoursPicker = (NumberPicker) view.findViewById(R.id.picker2);
        final NumberPicker minPicker = (NumberPicker) view.findViewById(R.id.picker3);
        final Context ctx = this;

        daysPicker.setMaxValue(31);
        daysPicker.setMinValue(0);
        daysPicker.setValue(days);
        daysPicker.setWrapSelectorWheel(true);

        hoursPicker.setMaxValue(23);
        hoursPicker.setMinValue(0);
        hoursPicker.setValue(hours);
        hoursPicker.setWrapSelectorWheel(true);

        minPicker.setMaxValue(59);
        minPicker.setMinValue(0);
        minPicker.setValue(min);
        minPicker.setWrapSelectorWheel(true);

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setView(view);
        builder.setTitle("Remind After");
        builder.setPositiveButton("Set Value", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                    days = daysPicker.getValue();
                    hours = hoursPicker.getValue();
                    min = minPicker.getValue();
                    interval.setText(Home.getIntervalLabel(ctx, days, hours, min));
            }
        });
        builder.setNegativeButton("Go Back", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.create();
        builder.show();
    }

}

Fragment pager adapter class

package com.siliconicpro.admin.ialarm;

import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.view.ViewGroup;

import java.util.List;

class myPagerAdapter extends FragmentPagerAdapter{

    // list of 2 fragments
    private List<Fragment> list;
    // array of tab titles defined in strings.xml file
    private String[] tabs;

    public myPagerAdapter(FragmentManager fm, Context ctx, List<Fragment> list){
        super(fm);
        tabs = ctx.getResources().getStringArray(R.array.tabs);
        this.list = list;
    }
    @Override
    public int getCount() {
        // no of tabs
        return list.size();
    }

    @Override
    public CharSequence getPageTitle(int position) {
        // setting tab titles
        return tabs[position];
    }

    @Override
    public Fragment getItem(int position) {
        return list.get(position);
    }

}

Custom cursor adapter class

package com.siliconicpro.admin.ialarm;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.Configuration;
import android.database.Cursor;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v7.widget.SwitchCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.support.v4.widget.CursorAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.Toast;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

public class myAdapter extends CursorAdapter {

    private LayoutInflater mInflater;
    private int row_layout;
    private static Context ctx;
    private int active_archive; // Active 1, Archive 0 (To determine class which invoked adapter)
    private DateFormat timeFormat = new SimpleDateFormat("hh:mm aa");
    private DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");

    public myAdapter(Context context, Cursor c, int flags, int layout, int flag) {
        super(context, c, flags);
        ctx = context;
        mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        // Getting Layout for Alarms List
        row_layout = layout;
        this.active_archive = flag;
    }

    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        View row = mInflater.inflate(row_layout, parent, false);
        ViewHolder holder = new ViewHolder();
        holder.title = (TextView)row.findViewById(R.id.title);
        holder.location = (TextView)row.findViewById(R.id.location);
        holder.ring_time = (TextView)row.findViewById(R.id.time);
        holder.repeat = (TextView)row.findViewById(R.id.repeat);

        // Choosing a Layout Containing either Switch or Checkbox
        switch(row_layout){
            case R.layout.row_layout:
                holder.on_off = (SwitchCompat)row.findViewById(R.id.on_off);
                break;
            case R.layout.row_layout_sel:
                holder.sel_unsel = (CheckBox)row.findViewById(R.id.sel_unsel);
                break;
        }
        row.setTag(holder);
        return row;
    }

    @Override
    public void bindView(final View view, final Context context, final Cursor c) {
        final ViewHolder holder = (ViewHolder)view.getTag();

        // getting values from Database
        final int id = c.getInt(c.getColumnIndex(AlarmsTable._id));
        final String time_ = c.getString(c.getColumnIndex(AlarmsTable.TIME));
        final String date_ = c.getString(c.getColumnIndex(AlarmsTable.DATE));
        final int interval_ = c.getInt(c.getColumnIndex(AlarmsTable.INTERVAL));
        final String title_ = c.getString(c.getColumnIndex(AlarmsTable.TITLE));
        final String alert1_ = c.getString(c.getColumnIndex(AlarmsTable.ALERT_1));
        final String alert2_ = c.getString(c.getColumnIndex(AlarmsTable.ALERT_2));
        final String location_ = c.getString(c.getColumnIndex(AlarmsTable.LOCATION));
        final int repeat_ = c.getInt(c.getColumnIndex(AlarmsTable.REPEAT));
        final int act_arc = c.getInt(c.getColumnIndex(AlarmsTable.ACT_ARC));

        // setting values
        // Get Screen Orientation Info
        int ot = context.getResources().getConfiguration().orientation;
        switch(ot){
            case Configuration.ORIENTATION_LANDSCAPE:
                // Title
                if(title_.length() > 25) {
                    holder.title.setText(title_.substring(0, 25) + "...");
                }
                else{
                    holder.title.setText(title_);
                }

                // Location
                if(location_.equals("")){
                    holder.location.setText("No Location");
                }
                else{
                    if(location_.length() > 35) {
                        holder.location.setText(location_.substring(0, 35) + "...");
                    }
                    else{
                        holder.location.setText(location_);
                    }
                }
                // Repeat
                String intervalLabel = Home.minutesToIntervalLabel(ctx, interval_);
                if(repeat_ == 0){
                    holder.repeat.setText("No Repeat");
                }
                else{
                    if(intervalLabel.length() > 25) {
                        holder.repeat.setText("Repeats after " + intervalLabel.substring(0, 25) + "...");
                    }
                    else{
                        holder.repeat.setText("Repeats after " + intervalLabel);
                    }
                }
                break;
            case Configuration.ORIENTATION_PORTRAIT:
                // Title
                if(title_.length() > 15) {
                    holder.title.setText(title_.substring(0, 15) + "...");
                }
                else{
                    holder.title.setText(title_);
                }
                // Location
                if(location_.equals("")){
                    holder.location.setText("No Location");
                }
                else{
                    if(location_.length() > 20) {
                        holder.location.setText(location_.substring(0, 20) + "...");
                    }
                    else{
                        holder.location.setText(location_);
                    }
                }
                // Repeat
                String intervalLabel_ = Home.minutesToIntervalLabel(ctx, interval_);
                if(repeat_ == 0){
                    holder.repeat.setText("No Repeat");
                }
                else{
                    if(intervalLabel_.length() > 12) {
                        holder.repeat.setText("Repeats after " + intervalLabel_.substring(0, 12) + "...");
                    }
                    else{
                        holder.repeat.setText("Repeats after " + intervalLabel_);
                    }
                }
                break;
        }

        String ringTime = Home.ringTime(time_, date_, interval_); // getting target Ring time
        holder.ring_time.setText(ringTime);

        // Choosing a Layout Containing either Switch or Checkbox
        switch(row_layout){
            case R.layout.row_layout:
                // Applying Listener on Switch
                holder.on_off.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                        // Code does not execute automatically
                        if(buttonView.isShown()) {
                            // When Switch is Turned ON
                            if (isChecked) {
                                long alarmTime = Home.getRingTime(time_, date_, interval_);
                                long currentTime = System.currentTimeMillis();
                                // In case of Active List of Alarms
                                if (act_arc == 1) {
                                    // For Repeat and No Repeat
                                    if (alarmTime > currentTime) {
                                        if (AlarmsTable.onAlarms(Home.getDop()) < 30) {
                                            // Turn On
                                            AlarmsTable.updateAlarmStatus(id, 1, Home.getDop());
                                            Home.setNewAlarm(ctx, time_, date_, interval_, repeat_, (long) id, alert1_, alert2_);
                                            String ring_time = Home.ringTime(time_, date_, interval_);
                                            Toast.makeText(ctx, "Alarm set on " + ring_time, Toast.LENGTH_SHORT).show();
                                            // Setting Text Colors
                                            holder.title.setTextColor(ctx.getResources().getColor(R.color.textColorOn));
                                            holder.location.setTextColor(ctx.getResources().getColor(R.color.textColorOn2));
                                            holder.ring_time.setTextColor(ctx.getResources().getColor(R.color.textColorOn2));
                                            holder.repeat.setTextColor(ctx.getResources().getColor(R.color.textColorOn2));
                                            refreshViewPager(Home.viewPager.getCurrentItem());
                                        } else {
                                            Toast.makeText(ctx, "Number of active alarms have reached the limit!", Toast.LENGTH_SHORT).show();
                                        }
                                    }
                                    // Only For Repeat
                                    else if (alarmTime <= currentTime && repeat_ == 1) {
                                        if (AlarmsTable.onAlarms(Home.getDop()) < 30) {
                                            // Turn On
                                            AlarmsTable.updateAlarmStatus(id, 1, Home.getDop());
                                            String newTime_ = timeFormat.format(currentTime);
                                            String newDate_ = dateFormat.format(currentTime);
                                            AlarmsTable.updateRepeatTime(String.valueOf(id), newTime_, newDate_, Home.getDop());
                                            Home.setNewAlarm(ctx, newTime_, newDate_, interval_, repeat_, (long) id, alert1_, alert2_);
                                            String ring_time = Home.ringTime(newTime_, newDate_, interval_);
                                            Toast.makeText(ctx, "Alarm set on " + ring_time, Toast.LENGTH_SHORT).show();
                                            // Setting Text Colors
                                            holder.title.setTextColor(ctx.getResources().getColor(R.color.textColorOn));
                                            holder.location.setTextColor(ctx.getResources().getColor(R.color.textColorOn2));
                                            holder.ring_time.setTextColor(ctx.getResources().getColor(R.color.textColorOn2));
                                            holder.repeat.setTextColor(ctx.getResources().getColor(R.color.textColorOn2));
                                            refreshViewPager(Home.viewPager.getCurrentItem());
                                        } else {
                                            Toast.makeText(ctx, "Number of active alarms have reached the limit!", Toast.LENGTH_SHORT).show();
                                        }
                                    }
                                    // Only For No Repeat
                                    else {
                                        Toast.makeText(ctx, "Not created! as alarm time is in the past", Toast.LENGTH_SHORT).show();
                                        refreshViewPager(Home.viewPager.getCurrentItem());
                                    }
                                }
                                // In case of Archive List of Alarms
                                else {
                                    // For Repeat and No Repeat
                                    if (alarmTime > currentTime) {
                                        showDialog(id, act_arc, c); // act_arc = 0
                                    }
                                    // Only for Repeat
                                    else if (alarmTime <= currentTime && repeat_ == 1) {
                                        showDialog(id, act_arc, c); // act_arc = 0
                                    }
                                    // Only for No Repeat
                                    else {
                                        Toast.makeText(ctx, "Not created! as alarm time is in the past", Toast.LENGTH_SHORT).show();
                                        refreshViewPager(Home.viewPager.getCurrentItem());
                                    }
                                }
                            }

                            // When Switch is Turned OFF
                            else {
                                // In case of Active List of Alarms
                                if (act_arc == 1) {
                                    // Turn Off
                                    AlarmsTable.updateAlarmStatus(id, 0, Home.getDop());
                                    // Deleting Alarm from System
                                    Home.cancelAlarm(ctx, (long) id);
                                    Toast.makeText(ctx, "Alarm Cancelled!", Toast.LENGTH_SHORT).show();
                                    showDialog(id, act_arc, c); // act_arc = 1
                                }
                            }
                        }
                    }
                });

                // Setting state of Switch
                // Getting Updated Cursor Each Time (containing only Status)
                int status = AlarmsTable.getAlarmStatus(id, Home.getDop());
                if(status == 1) {
                    holder.on_off.setChecked(true);
                    // Setting Text Colors
                    holder.title.setTextColor(ctx.getResources().getColor(R.color.textColorOn));
                    holder.location.setTextColor(ctx.getResources().getColor(R.color.textColorOn2));
                    holder.ring_time.setTextColor(ctx.getResources().getColor(R.color.textColorOn2));
                    holder.repeat.setTextColor(ctx.getResources().getColor(R.color.textColorOn2));
                }
                else{
                    holder.on_off.setChecked(false);
                    // Setting Text Colors
                    holder.title.setTextColor(ctx.getResources().getColor(R.color.textColor));
                    holder.location.setTextColor(ctx.getResources().getColor(R.color.textColor2));
                    holder.ring_time.setTextColor(ctx.getResources().getColor(R.color.textColor2));
                    holder.repeat.setTextColor(ctx.getResources().getColor(R.color.textColor2));
                }
                break;

            case R.layout.row_layout_sel:
                // Setting Text Colors
                int status_ = AlarmsTable.getAlarmStatus(id, Home.getDop());
                if(status_ == 1) {
                    // Setting Text Colors (ON)
                    holder.title.setTextColor(ctx.getResources().getColor(R.color.textColorOn));
                    holder.location.setTextColor(ctx.getResources().getColor(R.color.textColorOn2));
                    holder.ring_time.setTextColor(ctx.getResources().getColor(R.color.textColorOn2));
                    holder.repeat.setTextColor(ctx.getResources().getColor(R.color.textColorOn2));
                }
                else{
                    // Setting Text Colors (OFF)
                    holder.title.setTextColor(ctx.getResources().getColor(R.color.textColor));
                    holder.location.setTextColor(ctx.getResources().getColor(R.color.textColor2));
                    holder.ring_time.setTextColor(ctx.getResources().getColor(R.color.textColor2));
                    holder.repeat.setTextColor(ctx.getResources().getColor(R.color.textColor2));
                }
                // Saving State of Checkbox While Scrolling
                // Getting IDs of Selected Alarms from Active/Archive Class
                // Checking those included in Selected IDs list
                ArrayList<Long> alarm_ids;
                if(active_archive == 1){
                    // from Active class
                   alarm_ids = Active.getAlarm_ids();
                }
                else{
                    // from Archive class
                   alarm_ids = Archive.getAlarm_ids();
                }
                int flag = 0;
                for(Long i: alarm_ids){
                    if(c.getInt(c.getColumnIndex(AlarmsTable._id)) == i){
                        holder.sel_unsel.setChecked(true);
                        flag = 1;
                        break;
                    }
                }
                // Un-checking those not included in Selected IDs list
                if(flag == 0){
                    holder.sel_unsel.setChecked(false);
                }
                break;
        }
    }

    private void showDialog(final int id, final int act_arc, final Cursor c) {
        // getting values from Database
        final String time_ = c.getString(c.getColumnIndex(AlarmsTable.TIME));
        final String date_ = c.getString(c.getColumnIndex(AlarmsTable.DATE));
        final String alert1_ = c.getString(c.getColumnIndex(AlarmsTable.ALERT_1));
        final String alert2_ = c.getString(c.getColumnIndex(AlarmsTable.ALERT_2));
        final int interval_ = c.getInt(c.getColumnIndex(AlarmsTable.INTERVAL));
        final int repeat_ = c.getInt(c.getColumnIndex(AlarmsTable.REPEAT));

        // Showing Alert Dialog
        AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
        String title, msg;
        final int position;
        if(act_arc == 1){
            title = "Move to Archive!";
            msg = "This alarm will be sent to Archive Alarms Section.";
            position = 0; // for Active list
        }
        else{
            title = "Activate Alarm!";
            msg = "This alarm will be sent to Active Alarms Section.";
            position = 1; // for Archive list
        }
        builder.setTitle(title)
                .setMessage(msg)
                .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (act_arc == 1) {
                            AlarmsTable.updateActArcStatus(id, 0, Home.getDop()); // Move to Archive
                            AlarmsTable.updateSysTime(id, Home.getDop()); // Show on Top
                            dialog.cancel();
                            refreshViewPager(position);
                            Toast.makeText(ctx, "Alarm moved to Archive Section!", Toast.LENGTH_SHORT).show();
                        }
                        else {
                            long alarmTime = Home.getRingTime(time_, date_, interval_);
                            long currentTime = System.currentTimeMillis();

                            // For Repeat and No Repeat
                            if(alarmTime > currentTime) {
                                if(AlarmsTable.onAlarms(Home.getDop()) < 30) {
                                    // Turn On
                                    AlarmsTable.updateAlarmStatus(id, 1, Home.getDop());
                                    AlarmsTable.updateActArcStatus(id, 1, Home.getDop()); // Move to Active
                                    AlarmsTable.updateSysTime(id, Home.getDop()); // Show on Top
                                    Home.setNewAlarm(ctx, time_, date_, interval_, repeat_, (long) id, alert1_, alert2_);
                                    String ring_time = Home.ringTime(time_, date_, interval_);
                                    Toast.makeText(ctx, "Alarm set on " + ring_time, Toast.LENGTH_SHORT).show();
                                }
                                else{
                                    Toast.makeText(ctx, "Number of active alarms have reached the limit!", Toast.LENGTH_SHORT).show();
                                }
                            }
                            // Only For Repeat
                            else if(alarmTime <= currentTime && repeat_ == 1){
                                if(AlarmsTable.onAlarms(Home.getDop()) < 30) {
                                    // Turn On
                                    AlarmsTable.updateAlarmStatus(id, 1, Home.getDop());
                                    AlarmsTable.updateActArcStatus(id, 1, Home.getDop()); // Move to Active
                                    AlarmsTable.updateSysTime(id, Home.getDop()); // Show on Top
                                    String newTime_ = timeFormat.format(currentTime);
                                    String newDate_ = dateFormat.format(currentTime);
                                    AlarmsTable.updateRepeatTime(String.valueOf(id), newTime_, newDate_, Home.getDop());
                                    Home.setNewAlarm(ctx, newTime_, newDate_, interval_, repeat_, (long) id, alert1_, alert2_);
                                    String ring_time = Home.ringTime(newTime_, newDate_ , interval_);
                                    Toast.makeText(ctx, "Alarm set on " + ring_time, Toast.LENGTH_SHORT).show();
                                }
                                else{
                                    Toast.makeText(ctx, "Number of active alarms have reached the limit!", Toast.LENGTH_SHORT).show();
                                }
                            }
                            dialog.cancel();
                            refreshViewPager(position);
                        }
                    }
                })
                .setNegativeButton("No", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                        refreshViewPager(position);
                    }
                });
        builder.show();
    }

    private void refreshViewPager(int position) {
        List<Fragment> fragments = new ArrayList<>();
        fragments.add(new Active());
        fragments.add(new Archive());
        myPagerAdapter adapter = new myPagerAdapter(((FragmentActivity)ctx).getSupportFragmentManager(), ctx, fragments);
        Home.viewPager.setAdapter(adapter);
        Home.viewPager.setCurrentItem(position);
    }

    static class ViewHolder{
        TextView title, location, ring_time, repeat;
        SwitchCompat on_off;
        CheckBox sel_unsel;
    }
}

Database helper class

package com.siliconicpro.admin.ialarm;

import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.Toast;

class DatabaseOperations extends SQLiteOpenHelper {

    private static final String DATABASE_NAME = "alarmDatabase";
    private static final int DATABASE_VERSION = 9;
    private Context context;

    public DatabaseOperations(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        this.context = context;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        try {
            // Creating SETTINGS_TABLE
            db.execSQL(SettingsTable.CREATE_SETTINGS_TABLE);
            SettingsTable.insertDefaultRow(db);

            // Creating ALARMS_TABLE
            db.execSQL(AlarmsTable.CREATE_ALARMS_TABLE);
        } catch (SQLException e) {
            Toast.makeText(context, "Database Problem", Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        Toast.makeText(context, "onUpgrade called", Toast.LENGTH_SHORT).show();
        db.execSQL(SettingsTable.DROP_SETTINGS_TABLE);
        db.execSQL(AlarmsTable.DROP_ALARMS_TABLE);
        onCreate(db);
    }
}