com.michael.feng.textlater.NewActivity.java Source code

Java tutorial

Introduction

Here is the source code for com.michael.feng.textlater.NewActivity.java

Source

/*
 * Copyright (C) 2013 The Android Open Source Project
 *
 * 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.michael.feng.textlater;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import android.app.AlarmManager;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TimePicker;

import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;

public class NewActivity extends SherlockFragmentActivity implements OnClickListener {

    private EditText textContact;
    private Button addContactButton;
    private static EditText textDate;
    private static EditText textTime;
    private Button setDateButton;
    private Button setTimeButton;
    private EditText textContent;
    private Button sendButton;
    private ImageView backButton;
    private MessageDAO messageDAO;
    public static Map<String, Integer> whenMap = new HashMap<String, Integer>();;
    private String contactNames = "";
    private String contactNumbers = "";

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

        // Remove title bar
        // requestWindowFeature(Window.FEATURE_NO_TITLE);

        setContentView(R.layout.activity_new);
        getSupportActionBar().setDisplayUseLogoEnabled(false);
        getSupportActionBar().setDisplayHomeAsUpEnabled(false);
        getSupportActionBar().setDisplayShowHomeEnabled(false);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        getSupportActionBar().setDisplayShowCustomEnabled(true);
        getSupportActionBar().setCustomView(R.layout.abs_layout_new);

        backButton = (ImageView) findViewById(R.id.back);
        backButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                finish();
            }
        });
        backButton.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View arg0, MotionEvent event) {
                switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    // touch down code
                    backButton.setBackgroundColor(Color.rgb(104, 156, 210));
                    break;

                case MotionEvent.ACTION_MOVE:
                    // touch move code
                    break;

                case MotionEvent.ACTION_UP:
                    // touch up code
                    backButton.setBackgroundColor(Color.TRANSPARENT);
                    break;
                }
                return false;
            }
        });

        // Init Add Contact Button and EditText
        textContact = (EditText) findViewById(R.id.textContact);
        textContact.addTextChangedListener(new TextWatcher() {
            @Override
            public void afterTextChanged(Editable arg0) {
                // TODO Auto-generated method stub
            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
                // TODO Auto-generated method stub
            }

            @Override
            public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
                validateMessage();
            }
        });
        textContact.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                textContact.setSelection(textContact.getText().length());
            }
        });

        addContactButton = (Button) findViewById(R.id.addContactButton);
        addContactButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                Log.d("add button click", "hep");
                Intent in = new Intent(getApplicationContext(), ContactsActivity.class);
                contactNames = textContact.getText().toString();
                if (null != contactNames && !"".equals(contactNames)) {
                    in.putExtra("contactNames", contactNames);
                    in.putExtra("contactNumbers", contactNumbers);
                    Log.d("addbutton contactNames", contactNames);
                    Log.d("addbutton contactNumbers", contactNumbers);
                }
                int requestCode = 0;
                startActivityForResult(in, requestCode);
            }
        });

        // Init TextDate EditText
        textDate = (EditText) findViewById(R.id.textDate);
        textDate.setInputType(InputType.TYPE_NULL);
        textDate.setOnFocusChangeListener(new OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean hasFocus) {
                if (hasFocus) {
                    showDatePickerDialog(view);
                }
            }
        });
        textDate.setOnClickListener(this);

        // Init TextDate Button
        setDateButton = (Button) findViewById(R.id.setDateButton);
        setDateButton.setOnClickListener(this);

        // Init TextTime EditText
        textTime = (EditText) findViewById(R.id.textTime);
        textTime.setInputType(InputType.TYPE_NULL);
        textTime.setOnFocusChangeListener(new OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean hasFocus) {
                if (hasFocus) {
                    showTimePickerDialog(view);
                }
            }
        });
        textTime.setOnClickListener(this);

        // Init TextTime Button
        setTimeButton = (Button) findViewById(R.id.setTimeButton);
        setTimeButton.setOnClickListener(this);

        // Init Active Button and Content EditText
        textContent = (EditText) findViewById(R.id.textContent);
        textContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void afterTextChanged(Editable arg0) {
                validateMessage();
            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
                // TODO Auto-generated method stub
            }

            @Override
            public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
                // TODO
            }
        });
        sendButton = (Button) findViewById(R.id.sendButton);
        sendButton.setOnClickListener(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (null != data) {
            contactNames = data.getStringExtra("contactNames");
            contactNumbers = data.getStringExtra("contactNumbers");
            Log.d("contactNames on result", contactNames);
            Log.d("contactNumbers on result", contactNumbers);
        }
        // ??????
        switch (requestCode) {
        case 0:
            textContact.setText(contactNames);
            break;
        default:
            break;
        }
    }

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

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

    @Override
    protected void onResume() {
        textContact.setSelection(textContact.getText().length());
        super.onResume();
    }

    protected void validateMessage() {
        String textStr = "";
        String contactStr = "";
        textStr = textContent.getText().toString();
        contactStr = textContact.getText().toString();
        if (null != textStr && textStr.length() > 0 && null != contactStr && contactStr.length() > 0) {
            sendButton.setEnabled(true);
        } else {
            sendButton.setEnabled(false);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getSupportMenuInflater();
        inflater.inflate(R.menu.detailactivity_itemlist, menu);
        return true;
    }

    public void setWhenMap(Map<String, Integer> whenMap) {
        this.whenMap = whenMap;
    }

    @Override
    public void onClick(View arg0) {
        switch (arg0.getId()) {
        case R.id.textDate:
            showDatePickerDialog(arg0);
            break;
        case R.id.textTime:
            showTimePickerDialog(arg0);
            break;
        case R.id.setDateButton:
            showDatePickerDialog(arg0);
            break;
        case R.id.setTimeButton:
            showTimePickerDialog(arg0);
            break;
        case R.id.sendButton:
            Message message = contructMessage();
            scheduleTask(message);
            saveTask(message);
            finish();
            break;
        }
    }

    // Construct message object
    private Message contructMessage() {
        Message message = new Message();
        if (!"".equals(contactNames))
            contactNames = contactNames.trim();
        else
            contactNames = textContact.getText().toString().trim();

        if (!"".equals(contactNumbers))
            contactNumbers = contactNumbers.trim();
        else
            contactNumbers = textContact.getText().toString().trim();

        // To remove character ";" from single contact
        int charIndex = contactNames.indexOf(";") + 1;
        if (contactNames.length() == charIndex)
            contactNames = contactNames.substring(0, charIndex - 1);

        // To remove character ";" from single number
        charIndex = contactNumbers.indexOf(";") + 1;
        if (contactNumbers.length() == charIndex)
            contactNumbers = contactNumbers.substring(0, charIndex - 1);

        message.setTextContact(contactNames);
        message.setTextNumber(contactNumbers);
        if (!"".equals(textDate.getText().toString().trim()) && !"".equals(textTime.getText().toString().trim())) {
            message.setTextWhen(textDate.getText().toString().trim() + " " + textTime.getText().toString().trim());
        } else {
            Date tasktime = Calendar.getInstance().getTime();
            SimpleDateFormat df = new SimpleDateFormat("yyyy.M.dd HH:mm");
            message.setTextWhen(df.format(tasktime));
        }
        message.setTextContent(textContent.getText().toString());
        return message;
    }

    // Save message to DB
    private void saveTask(Message msg) {
        messageDAO = new MessageDAO(this);
        messageDAO.open();
        messageDAO.insertMessage(msg);
        messageDAO.close();
    }

    // Schedule timer task within Alarm
    private void scheduleTask(Message message) {

        Calendar calendar = Calendar.getInstance();
        if (null != whenMap && whenMap.containsKey("year")) {
            calendar.set(Calendar.YEAR, whenMap.get("year"));
            calendar.set(Calendar.MONTH, whenMap.get("month"));
            calendar.set(Calendar.DAY_OF_MONTH, whenMap.get("day"));
            calendar.set(Calendar.HOUR_OF_DAY, whenMap.get("hour"));
            calendar.set(Calendar.MINUTE, whenMap.get("min"));
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MILLISECOND, 0);
            cleanWhenMap();
        }

        Intent intent = new Intent(this, AlarmReceiver.class);
        intent.putExtra("textContact", message.getTextContact().trim());
        intent.putExtra("textNumber", message.getTextNumber().trim());
        intent.putExtra("textWhen", message.getTextWhen());
        intent.putExtra("textContent", message.getTextContent());
        // Different requestCode can lead to different PendingIntent
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, (int) calendar.getTimeInMillis(), intent,
                PendingIntent.FLAG_UPDATE_CURRENT);
        AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);

        Log.d("requstcode in new-->", calendar.getTimeInMillis() + "");

        // AlarmManager.RTC_WAKEUP can be executed when CPU sleep
        // AlarmManager.RTC can't be executed when CPU sleep
        am.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
    }

    private void cleanWhenMap() {
        whenMap.put("year", null);
        whenMap.put("month", null);
        whenMap.put("day", null);
        whenMap.put("hour", null);
        whenMap.put("min", null);
    }

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

    public void showTimePickerDialog(View v) {
        DialogFragment newFragment = new TimePickerFragment();
        newFragment.show(getSupportFragmentManager(), "timePicker");
    }

    public void showDatePickerDialog(View v) {
        DialogFragment newFragment = new DatePickerFragment();
        newFragment.show(getSupportFragmentManager(), "datePicker");
    }

    public static class TimePickerFragment extends DialogFragment implements TimePickerDialog.OnTimeSetListener {

        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            // Use the current time as the default values for the picker
            final Calendar c = Calendar.getInstance();
            int hour = c.get(Calendar.HOUR_OF_DAY);
            int minute = c.get(Calendar.MINUTE);

            // Create a new instance of TimePickerDialog and return it
            return new TimePickerDialog(getActivity(), this, hour, minute,
                    DateFormat.is24HourFormat(getActivity()));
        }

        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
            // Do something with the time chosen by the user
            textTime.setText(hourOfDay + ":" + minute);
            whenMap.put("hour", hourOfDay);
            whenMap.put("min", minute);
        }
    }

    public static class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {

        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            // Use the current date as the default date in the picker
            final Calendar c = Calendar.getInstance();
            int year = c.get(Calendar.YEAR);
            int month = c.get(Calendar.MONTH);
            int day = c.get(Calendar.DAY_OF_MONTH);

            // Create a new instance of DatePickerDialog and return it
            return new DatePickerDialog(getActivity(), this, year, month, day);
        }

        public void onDateSet(DatePicker view, int year, int month, int day) {
            // Do something with the date chosen by the user
            textDate.setText(year + "." + (month + 1) + "." + day);
            whenMap.put("year", year);
            whenMap.put("month", month);
            whenMap.put("day", day);
        }
    }

}