Thursday, 11 June 2015

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;
    }
}

No comments:

Post a Comment