study.tdcc.act.MainCalendar.java Source code

Java tutorial

Introduction

Here is the source code for study.tdcc.act.MainCalendar.java

Source

/**
 ToDoCycleCalendar
 Copyright (C) 2012  Tohru Mashiko
    
 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.
    
 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.
    
 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
    
    
 ??MainCalendar
 ?Activity
 ???
 (?//???)
     0.1/2012.05.21/T.Mashiko
     0.2/2012.05.22/T.Mashiko
     0.3/2012.05.29/T.Mashiko
     0.4/2012.06.04/T.Mashiko
     0.5/2012.06.06/T.Mashiko Long
     0.6/2012.06.15/T.Mashiko YYYY-MM?
     0.7/2012.06.17/T.Mashiko
     0.8/2012.06.18/T.Mashiko
     0.9/2012.06.19/T.Mashiko ??,
     1.0/2012.06.25/T.Mashiko OAuthCode??
     1.1/2012.06.26/T.Mashiko OAuthCode??,GDATA??
     1.2/2012.06.27/T.Mashiko GDATA??
     1.3/2012.06.28/T.Mashiko GDATA??
     1.4/2012.07.02/T.Mashiko GDATA??
     1.5/2012.07.03/T.Mashiko GDATA??
     1.7/2012.07.04/T.Mashiko 
     1.8/2012.07.05/T.Mashiko OAuth????
     1.9/2012.07.06/T.Mashiko OAuth??SQLiteTokenExpires????
     2.0/2012.07.08/T.Mashiko ??
     2.1/2012.07.09/T.Mashiko ,
     2.2/2012.07.10/T.Mashiko 
     2.3/2012.07.11/T.Mashiko ???
     2.4/2012.07.18/T.Mashiko 
     2.5/2012.08.22/T.Mashiko ?,?
     2.6/2012.08.23/T.Mashiko ?
     2.7/2012.09.04/T.Mashiko ????
     2.8/2012.09.05/T.Mashiko ???????UI?()?????
     2.9/2012.09.06/T.Mashiko ???,?????
     3.0/2012.09.07/T.Mashiko ???,?Insert???URL??
     3.1/2012.09.08/T.Mashiko ?Delete???,?????
     3.2/2012.09.10/T.Mashiko Insert????URL???????
     3.3/2012.09.13/T.Mashiko ???25??????????2?????????,parse??null??????
     3.4/2012.09.14/T.Mashiko ????,OutOfMemory
     3.5/2012.09.19/T.Mashiko ??OutOfMemory(?300?)
     3.6/2012.09.26/T.Mashiko About
     3.7/2012.09.27/T.Mashiko 
*/
package study.tdcc.act;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import study.tdcc.*;
import study.tdcc.adapter.*;
import study.tdcc.bean.*;
import study.tdcc.lib.*;
import study.tdcc.lib.ScheduleDatabaseHelper.ScheduleCursor;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.database.SQLException;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.DatePicker;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;

public class MainCalendar extends Activity implements OnItemClickListener {
    //
    private TextView tvCustomTitle;
    //(?)
    private TextView tvCustomTitleVersion;
    //
    private ViewFlipper vfCalendar;
    //?
    private GestureDetector gdObj;
    //
    private TextView tvYearMonth;
    //
    private GridView gvCalendar;
    //
    private GridView gvObj;
    //CalendarCellAdapter
    private CalendarCellAdapter ccaDay = null;
    //???
    private GregorianCalendar gcTargetYearMonthDay;
    //????
    private GregorianCalendar gcNow;
    //
    private ScheduleDatabaseHelper sdhDB;
    //??
    private ScreenTransitionData stdObj = new ScreenTransitionData();
    //?
    private ProgressDialog pdObj = null;
    //
    private ArrayList<String> alDateCell;
    //???handler
    private Handler hObj;
    //
    private boolean blFlick = true;
    //
    private boolean blDialogButton = true;
    //?handler
    private Handler hGetTokenObj;
    //
    private Map<String, String> mpTokens;
    //?handler
    private Handler hSyncCalendarObj;

    //AuthCode???
    private String strAuthCode;
    //
    private String strUpdateStartTime = null;
    //?
    private String strLastUpdate = null;
    //???
    public static final String LAST_UPDATE = "LastUpdate";
    //????
    private String strAccessToken;
    private String strRefreshToken;
    private long lgAccessTokenExpire;
    //?????
    private static final String ACCESS_TOKEN = "access_token";
    private static final String REFRESH_TOKEN = "refresh_token";
    private static final String EXPIRES_IN = "expires_in";

    // Google APIS?????
    public static final String CLIENT_SECRET = "My_Client_secret";
    //IDGoogle APIS?????
    public static final String CLIENT_ID = "My_Client_ID";

    //URIGoogle APIS??
    public static final String REDIRECT_URI = "urn:ietf:wg:oauth:2.0:oob";
    //OAUTHURL
    public static final String OAUTH_URL = "https://accounts.google.com/o/oauth2/auth";
    //??
    public static final String GRANT_TYPE_A = "authorization_code";
    public static final String GRANT_TYPE_R = "refresh_token";
    //?URL
    public static final String TOKEN_URL = "https://accounts.google.com/o/oauth2/token";
    //
    public static final String CONTENT_TYPE_AX = "application/x-www-form-urlencoded";
    public static final String CONTENT_TYPE_AA = "application/atom+xml";
    //?
    public static final String SCOPE = "https://www.google.com/calendar/feeds/";
    //????????
    public static final String RESPONSE_CODE = "code";
    //OAUTH??URI
    public static final Uri OAUTH_URI = Uri.parse(OAUTH_URL + "?client_id=" + CLIENT_ID + "&redirect_uri="
            + REDIRECT_URI + "&scope=" + SCOPE + "&response_type=" + RESPONSE_CODE);
    //onActivityResult??Activity?request
    public static final int BROWSER = 11;
    //onActivityResult??Activity?requestAuthCode
    public static final int AUTH_CODE_REGISTRATION = 12;
    //AuthCode????
    public static final String AUTH_CODE = "AuthCode";

    //GDATA
    public static final String GDATA_VERSION_TAG = "GData-Version";
    //GDATA?
    public static final String GDATA_VERSION = "2";
    //GoogleCalendar?FEED??URL
    //showdeleted=true???????????
    public static final String CALENDAR_FEED_URL = "https://www.google.com/calendar/feeds/default/private/full?max-results=300&showdeleted=true";
    //API??Feed?????????URL
    public static final String DEFAULT_URL = "https://www.google.com/calendar/feeds/default/private/full";
    //HTTP??????
    private boolean blHttpSucceeded = false;
    //HTTP???????
    private int intResponseCode = 0;
    //GData(Insert)
    ArrayList<GDataEvent> alInsertGCEvents;
    //GData(Update)
    ArrayList<GDataEvent> alUpdateGCEvents;
    //GData(Delete)
    ArrayList<GDataEvent> alDeleteGCEvents;
    //Google?????
    private boolean blSyncGC = true;
    //Google????????????????
    private int intUnreflected = 0;

    //??
    OnTouchListener otlObj = new OnTouchListener() {
        public boolean onTouch(View view, MotionEvent event) {
            if (gdObj.onTouchEvent(event))
                return true;
            return false;
        }
    };

    //?
    OnGestureListener oglObj = new OnGestureListener() {
        public boolean onDown(MotionEvent event) {
            Log.d("DEBUG", "MainCalendar onDown Start");
            Log.d("DEBUG", "MainCalendar onDown End");
            return false;
        }

        //?
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            Log.d("DEBUG", "MainCalendar onFling Start");
            float flCoordX = Math.abs(velocityX);
            float flCoordY = Math.abs(velocityY);
            if (flCoordX > flCoordY && flCoordX > 150) {
                if (blFlick == true) {
                    //
                    blFlick = false;
                    //??????1??
                    gcTargetYearMonthDay.set(Calendar.DAY_OF_MONTH, 1);
                    if (e1.getX() < e2.getX()) {
                        //1?
                        gcTargetYearMonthDay.add(Calendar.MONTH, -1);
                        //?
                        long lgLowerLimitTime = DateUtil.convMSec(getString(R.string.lower_limit_time));
                        if (gcTargetYearMonthDay.getTimeInMillis() < lgLowerLimitTime) {
                            Log.d("DEBUG", "MainCalendar onFling ?");
                            gcTargetYearMonthDay.add(Calendar.MONTH, 1);
                        }
                    } else {
                        //1?
                        gcTargetYearMonthDay.add(Calendar.MONTH, 1);
                        //?
                        long lgUpperLimitTime = DateUtil.convMSec(getString(R.string.upper_limit_time));
                        if (gcTargetYearMonthDay.getTimeInMillis() > lgUpperLimitTime) {
                            gcTargetYearMonthDay.add(Calendar.MONTH, -1);
                            Log.d("DEBUG", "MainCalendar onFling ?");
                        }
                    }
                    tvYearMonth.setText(DateUtil.YEARMONTH_FORMAT.format(gcTargetYearMonthDay.getTime()));
                    //??
                    changeYMColor(gcTargetYearMonthDay.get(Calendar.MONTH) + 1);
                    //???handler
                    hObj = new Handler();
                    //?(??)
                    makeCalDateCell();
                    Log.d("DEBUG", "MainCalendar onFling End");
                    return true;
                }
            }
            Log.d("DEBUG", "MainCalendar onFling End");
            return false;
        }

        public void onLongPress(MotionEvent arg0) {
            Log.d("DEBUG", "MainCalendar onLongPress Start");
            Log.d("DEBUG", "MainCalendar onLongPress End");
        }

        public boolean onScroll(MotionEvent arg0, MotionEvent arg1, float arg2, float arg3) {
            Log.d("DEBUG", "MainCalendar onScroll Start");
            Log.d("DEBUG", "MainCalendar onScroll End");
            return false;
        }

        public void onShowPress(MotionEvent arg0) {
            Log.d("DEBUG", "MainCalendar onShowPress Start");
            Log.d("DEBUG", "MainCalendar onShowPress End");
        }

        public boolean onSingleTapUp(MotionEvent arg0) {
            Log.d("DEBUG", "MainCalendar onSingleTapUp Start");
            Log.d("DEBUG", "MainCalendar onSingleTapUp End");
            return false;
        }
    };

    /**
     * onCreate
     * @param savedInstanceState ?
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        Log.d("DEBUG", "MainCalendar onCreate Start");
        super.onCreate(savedInstanceState);
        //
        requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
        //???
        setContentView(R.layout.calendar);
        //???
        Window window = getWindow();
        window.setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.customtitle);
        //????
        getScreenTransitionData();
        //???
        getScreenRestoreData(savedInstanceState);
        //?????
        getViewElement();
        //?
        setCustomTitle();
        //???
        setViewListener();
        //????
        setViewElement();
        //
        blFlick = true;
        Log.d("DEBUG", "MainCalendar onCreate End");
    }

    /**
     * ????
     */
    private void getScreenTransitionData() {
        Log.d("DEBUG", "MainCalendar getScreenTransitionData Start");
        //?????
        Bundle bExtras = getIntent().getExtras();
        if (bExtras != null) {
            stdObj.setStrCalendarYearMonth(bExtras.getString("calym"));
            stdObj.setStrCalendarYearMonthDay(bExtras.getString("calymd"));
            stdObj.setStrUserInterfaceId(bExtras.getString("uiid"));
            stdObj.setLgKeyId(bExtras.getLong("keyid"));
        }
        Log.d("DEBUG", "MainCalendar getScreenTransitionData End");
    }

    /**
     * ???
     * @param savedInstanceState ?
     */
    private void getScreenRestoreData(Bundle savedInstanceState) {
        Log.d("DEBUG", "MainCalendar getScreenRestoreData Start");
        if (savedInstanceState != null) {
            //??
            stdObj.setStrCalendarYearMonth(savedInstanceState.getString("calym"));
        }
        Log.d("DEBUG", "MainCalendar getScreenRestoreData End");
    }

    /**
     * ????
     *
     */
    private void getViewElement() {
        Log.d("DEBUG", "MainCalendar getViewElement Start");
        //
        tvCustomTitle = (TextView) this.findViewById(R.id.titletext);
        //?
        tvCustomTitleVersion = (TextView) this.findViewById(R.id.titleversion);
        //
        vfCalendar = (ViewFlipper) this.findViewById(R.id.vfCalendar);
        //
        tvYearMonth = (TextView) findViewById(R.id.yearMonth);
        //
        gvCalendar = (GridView) findViewById(R.id.gvCalendar);
        //??
        gdObj = new GestureDetector(this, oglObj);
        Log.d("DEBUG", "MainCalendar getViewElement End");
    }

    /**
     * ?
     *
     */
    private void setCustomTitle() {
        Log.d("DEBUG", "MainCalendar setCustomTitle Start");
        tvCustomTitle.setText(getString(R.string.act_name1));
        StringBuilder sbObj = new StringBuilder();
        sbObj.append(getString(R.string.title_version));
        PackageManager pmObj = this.getPackageManager();
        try {
            PackageInfo piObj = pmObj.getPackageInfo(this.getPackageName(), PackageManager.GET_ACTIVITIES);
            sbObj.append(piObj.versionName);
        } catch (NameNotFoundException e) {
            Log.e("ERROR", "MainCalendar setCustomTitle NameNotFoundException", e);
        }
        tvCustomTitleVersion.setText(sbObj.toString());
        Log.d("DEBUG", "MainCalendar setCustomTitle End");
    }

    /**
     * ????
     *
     */
    private void setViewListener() {
        Log.d("DEBUG", "MainCalendar setViewListener Start");
        //?
        tvYearMonth.setOnClickListener(new DateOnClickListener(this));
        //?
        gvCalendar.setOnItemClickListener(this);
        gvCalendar.setOnTouchListener(otlObj);
        Log.d("DEBUG", "MainCalendar setViewListener End");
    }

    /**
     * ????
     *
     */
    private void setViewElement() {
        Log.d("DEBUG", "MainCalendar setViewElement Start");
        //GregorianCalendar???
        //
        gcNow = new GregorianCalendar();
        //??????
        if (stdObj.getStrCalendarYearMonth() == null || stdObj.getStrCalendarYearMonth().equals("")) {
            //?
            gcTargetYearMonthDay = new GregorianCalendar();
            String strInitialDate = DateUtil.YEARMONTH_FORMAT.format(gcTargetYearMonthDay.getTime());
            gcTargetYearMonthDay = DateUtil.toCalendar(strInitialDate + DateUtil.FIRST_DAY);
            Log.d("DEBUG", "MainCalendar setViewElement stdObj:");
        } else {
            gcTargetYearMonthDay = DateUtil.toCalendar(stdObj.getStrCalendarYearMonth() + DateUtil.FIRST_DAY);
            Log.d("DEBUG", "MainCalendar setViewElement stdObj:");
        }
        //???
        tvYearMonth.setText(DateUtil.YEARMONTH_FORMAT.format(gcTargetYearMonthDay.getTime()));
        //??
        //??
        int intMonth = gcTargetYearMonthDay.get(Calendar.MONTH) + 1;
        changeYMColor(intMonth);
        //??
        gvObj = (GridView) vfCalendar.getCurrentView();
        //??
        gvObj.setNumColumns(DateUtil.DAYS_OF_WEEK);
        //ScheduleDatabaseHelper?
        sdhDB = new ScheduleDatabaseHelper(this);
        //???handler
        hObj = new Handler();
        //?(??)
        makeCalDateCell();
        Log.d("DEBUG", "MainCalendar setViewElement End");
    }

    /**
     * ?(??)
     */
    public void makeCalDateCell() {
        Log.d("DEBUG", "MainCalendar makeCalDateCell Start");
        //??
        pdObj = new ProgressDialog(MainCalendar.this);
        pdObj.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        pdObj.setMessage(getString(R.string.scload_msg));
        //?????
        pdObj.setCancelable(false);
        //?
        pdObj.show();
        //????
        Thread thread = new Thread(runLoadAllDay);
        //?
        thread.start();
        Log.d("DEBUG", "MainCalendar makeCalDateCell End");
    }

    /**
     * runLoadAllDay??
     */
    private Runnable runLoadAllDay = new Runnable() {
        public void run() {
            Log.d("DEBUG", "MainCalendar runLoadAllDay run Start");
            alDateCell = new ArrayList<String>();
            ArrayList<AllDayWhere> alSqlWhere = new ArrayList<AllDayWhere>();
            for (int intCt = 0; intCt < (DateUtil.DAYS_OF_WEEK * 6); intCt++) {
                //42?????
                AllDayWhere objADW = new AllDayWhere();
                Calendar calCell = (Calendar) gcTargetYearMonthDay.clone();
                calCell.set(Calendar.DAY_OF_MONTH, 1);
                calCell.add(Calendar.DAY_OF_MONTH, intCt - calCell.get(Calendar.DAY_OF_WEEK) + 1);
                //?
                objADW.setLgStartTime(calCell.getTimeInMillis());
                //?
                calCell.add(Calendar.DAY_OF_MONTH, 1);
                objADW.setLgEndTime(calCell.getTimeInMillis());
                alSqlWhere.add(intCt, objADW);
            }
            //?
            alDateCell = selectAllDaySchedule(alSqlWhere);
            if (alDateCell == null) {
                hObj.post(new Runnable() {
                    public void run() {
                        //
                        //
                        pdObj.dismiss();
                        Toast.makeText(MainCalendar.this, getString(R.string.sqlite_read_err), Toast.LENGTH_LONG)
                                .show();
                        endActivity();
                    }
                });
            } else {
                hObj.post(new Runnable() {
                    public void run() {
                        //GridView?DateCellAdapter?
                        //DateCellAdapter???(??)
                        ccaDay = new CalendarCellAdapter(MainCalendar.this, alDateCell, gcTargetYearMonthDay,
                                gcNow);
                        gvObj.setAdapter(ccaDay);
                        //
                        blFlick = true;
                        //
                        pdObj.dismiss();
                    }
                });
            }
            Log.d("DEBUG", "MainCalendar runLoadAllDay run End");
        }
    };

    /**
     * ????
     *
     * @alSqlWhere 42????
     * @return 42?
     */
    private ArrayList<String> selectAllDaySchedule(ArrayList<AllDayWhere> alSqlWhere) {
        Log.d("DEBUG", "MainCalendar selectAllDaySchedule Start");
        ArrayList<String> alResult = new ArrayList<String>();
        try {
            //??
            alResult = sdhDB.getScheduleAllDayList(alSqlWhere);
        } catch (SQLException e) {
            alResult = null;
            Log.e("ERROR", "MainCalendar selectAllDaySchedule DB Error", e);
        }
        Log.d("DEBUG", "MainCalendar selectAllDaySchedule End");
        return alResult;
    }

    /**
     * ??
     *
     * @param intMonth 
     */
    public void changeYMColor(int intMonth) {
        Log.d("DEBUG", "MainCalendar changeYMColor Start");
        if (intMonth % 2 == 0) {
            //???()
            tvYearMonth.setTextColor(Color.rgb(22, 74, 132));
        } else {
            //??(?)
            tvYearMonth.setTextColor(Color.rgb(162, 32, 65));
        }
        Log.d("DEBUG", "MainCalendar changeYMColor End");
    }

    /**
     * ???
     *
     * @param parent 
     * @param view 
     * @param position ?
     * @param id ID
     */
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Log.d("DEBUG", "MainCalendar onItemClick Start");
        if (blFlick == true) {
            //
            blFlick = false;
            //
            Calendar calDay = (Calendar) gcTargetYearMonthDay.clone();
            //yyyy-MM ?
            String strYM = DateUtil.YEARMONTH_FORMAT.format(calDay.getTime());
            //position?
            calDay.set(Calendar.DAY_OF_MONTH, 1);
            calDay.add(Calendar.DAY_OF_MONTH, position - calDay.get(Calendar.DAY_OF_WEEK) + 1);
            //???
            long lgLowerLimitTime = DateUtil.convMSec(getString(R.string.lower_limit_time));
            long lgUpperLimitTime = DateUtil.convMSec(getString(R.string.upper_limit_time));
            if (calDay.getTimeInMillis() < lgLowerLimitTime) {
                //????
                Toast.makeText(MainCalendar.this, getString(R.string.select_errmsg1), Toast.LENGTH_SHORT).show();
                blFlick = true;
                return;
            } else if (calDay.getTimeInMillis() > lgUpperLimitTime) {
                //????
                Toast.makeText(MainCalendar.this, getString(R.string.select_errmsg2), Toast.LENGTH_SHORT).show();
                blFlick = true;
                return;
            }
            //yyyy-MM-dd ?
            String strYMD = DateUtil.DATE_FORMAT.format(calDay.getTime());
            nextActivity(MainTab.class, strYMD, strYM);
        }
        Log.d("DEBUG", "MainCalendar onItemClick End");
    }

    /**
     * DateOnClickListener
     *  ???
     */
    private class DateOnClickListener implements OnClickListener, DialogInterface.OnCancelListener {
        private Context contextObj = null;

        public DateOnClickListener(Context context) {
            Log.d("DEBUG", "MainCalendar DateOnClickListener DateOnClickListener Start");
            //Context??????????????
            contextObj = context;
            Log.d("DEBUG", "MainCalendar DateOnClickListener DateOnClickListener End");
        }

        /**
         * ????
         * @param View ??
         */
        public void onClick(View view) {
            Log.d("DEBUG", "MainCalendar DateOnClickListener onClick Start");
            GregorianCalendar gcObj = null;
            if (view == tvYearMonth && blFlick == true) {
                //????
                //
                blFlick = false;
                String strTempYear = DateUtil.toDivideYearMonth(tvYearMonth.getText().toString())[0];
                String strTempMonth = DateUtil.toDivideYearMonth(tvYearMonth.getText().toString())[1];
                gcObj = DateUtil.toCalendar(DateUtil.toAddZeroYear(strTempYear) + "-"
                        + DateUtil.toAddZeroMonth(strTempMonth) + DateUtil.FIRST_DAY);
            } else {
                return;
            }
            //AlertDialog???
            AlertDialog.Builder adbObj = new AlertDialog.Builder(contextObj);
            //
            blDialogButton = true;
            final DatePicker dpObj = new DatePicker(contextObj);
            dpObj.updateDate(gcObj.get(Calendar.YEAR), gcObj.get(Calendar.MONTH), gcObj.get(Calendar.DAY_OF_MONTH));
            int intDayID = Resources.getSystem().getIdentifier("day", "id", "android");
            dpObj.findViewById(intDayID).setVisibility(View.GONE);
            adbObj.setView(dpObj).setTitle(contextObj.getString(R.string.select_calendar))
                    .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface diObj, int intWhich) {
                            if (blDialogButton == true) {
                                //
                                blDialogButton = false;
                                //??
                                long lgLowerLimitTime = DateUtil.convMSec(getString(R.string.lower_limit_time));
                                long lgUpperLimitTime = DateUtil.convMSec(getString(R.string.upper_limit_time));
                                GregorianCalendar gcalObj = new GregorianCalendar();
                                gcalObj.set(dpObj.getYear(), dpObj.getMonth(), dpObj.getDayOfMonth());
                                if (gcalObj.getTimeInMillis() < lgLowerLimitTime) {
                                    gcalObj = DateUtil.toCalendar(getString(R.string.lower_limit_time));
                                } else if (gcalObj.getTimeInMillis() > lgUpperLimitTime) {
                                    gcalObj = DateUtil.toCalendar(getString(R.string.upper_limit_time));
                                }
                                String strSkipDate = DateUtil.YEARMONTH_FORMAT.format(gcalObj.getTime());
                                //????View??
                                gcTargetYearMonthDay = DateUtil.toCalendar(strSkipDate + DateUtil.FIRST_DAY);
                                //
                                gcNow = new GregorianCalendar();
                                //??
                                gvObj = (GridView) vfCalendar.getCurrentView();
                                //??
                                gvObj.setNumColumns(DateUtil.DAYS_OF_WEEK);
                                tvYearMonth
                                        .setText(DateUtil.YEARMONTH_FORMAT.format(gcTargetYearMonthDay.getTime()));
                                //??
                                changeYMColor(gcTargetYearMonthDay.get(Calendar.MONTH) + 1);
                                //ScheduleDatabaseHelper?
                                sdhDB = new ScheduleDatabaseHelper(MainCalendar.this);
                                //???handler
                                hObj = new Handler();
                                //?(??)
                                makeCalDateCell();
                            }
                        }
                    }).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface diObj, int intWhich) {
                            if (blDialogButton == true) {
                                //
                                blDialogButton = false;
                                //
                                blFlick = true;
                            }
                        }
                    }).setOnCancelListener(this).create().show();
            Log.d("DEBUG", "MainCalendar DateOnClickListener onClick End");
        }

        /**
         * onCancel
         * ?
         *
         * @param dialog dialog 
         */
        @Override
        public void onCancel(DialogInterface dialog) {
            Log.d("DEBUG", "MainCalendar DateOnClickListener onCancel Start");
            //?????
            //
            blFlick = true;
            Log.d("DEBUG", "MainCalendar DateOnClickListener onCancel End");
        }

    }

    /**
     * ??
     *
     * @param Menu ??
     * @return ??????true
     */
    public boolean onCreateOptionsMenu(Menu menu) {
        Log.d("DEBUG", "MainCalendar onCreateOptionsMenu Start");
        //MenuInflater?
        MenuInflater miObj = getMenuInflater();
        //MenuInflater?????
        miObj.inflate(R.menu.calendar_menu, menu);
        Log.d("DEBUG", "MainCalendar onCreateOptionsMenu End");
        return super.onCreateOptionsMenu(menu);
    }

    /**
     * ???
     *
     * @param MenuItem ???
     * @return ?????true 
     */
    public boolean onOptionsItemSelected(MenuItem item) {
        Log.d("DEBUG", "MainCalendar onOptionsItemSelected Start");
        if (item.getItemId() == R.id.searchMenu) {
            //?
            //
            Calendar calDay = (Calendar) gcTargetYearMonthDay.clone();
            //yyyy-MM ?
            String strYM = DateUtil.YEARMONTH_FORMAT.format(calDay.getTime());
            //???
            nextActivity(Search.class, "", strYM);
            //?
            endActivity();
            Log.d("DEBUG", "MainCalendar onOptionsItemSelected(1) End");
            return true;
        } else if (item.getItemId() == R.id.syncMenu) {
            //??
            syncCalendar();
            Log.d("DEBUG", "MainCalendar onOptionsItemSelected(2) End");
            return true;
        } else if (item.getItemId() == R.id.aggregateCalculationMenu) {
            //?
            //
            Calendar calDay = (Calendar) gcTargetYearMonthDay.clone();
            //yyyy-MM ?
            String strYM = DateUtil.YEARMONTH_FORMAT.format(calDay.getTime());
            //???
            nextActivity(AggregateCalculation.class, "", strYM);
            //?
            endActivity();
            Log.d("DEBUG", "MainCalendar onOptionsItemSelected(3) End");
            return true;
        } else if (item.getItemId() == R.id.subcategoryEdit) {
            //?
            //
            Calendar calDay = (Calendar) gcTargetYearMonthDay.clone();
            //yyyy-MM ?
            String strYM = DateUtil.YEARMONTH_FORMAT.format(calDay.getTime());
            //???
            nextActivity(SubcategoryEdit.class, "", strYM);
            //?
            endActivity();
            Log.d("DEBUG", "MainCalendar onOptionsItemSelected(4) End");
            return true;
        } else if (item.getItemId() == R.id.backUpRestore) {
            //???
            //
            Calendar calDay = (Calendar) gcTargetYearMonthDay.clone();
            //yyyy-MM ?
            String strYM = DateUtil.YEARMONTH_FORMAT.format(calDay.getTime());
            //?????
            nextActivity(BackupRestore.class, "", strYM);
            //?
            endActivity();
            Log.d("DEBUG", "MainCalendar onOptionsItemSelected(5) End");
            return true;
        } else if (item.getItemId() == R.id.about) {
            //About?
            showDialog(this, getString(R.string.about_msg1), getString(R.string.about_msg2));
            Log.d("DEBUG", "MainCalendar onOptionsItemSelected(6) End");
            return true;
        } else if (item.getItemId() == R.id.endMenu) {
            //?
            //?yes/no?
            showYesNoDialog(this, R.string.mes1_dialog, R.string.mes2_dialog,
                    new DialogInterface.OnClickListener() {
                        //??
                        public void onClick(DialogInterface dialog, int whith) {
                            if (whith == DialogInterface.BUTTON_POSITIVE) {
                                //
                                endActivity();
                            }
                        }
                    });
            Log.d("DEBUG", "MainCalendar onOptionsItemSelected(7) End");
            return true;
        }
        Log.d("DEBUG", "MainCalendar onOptionsItemSelected(8) End");
        return false;
    }

    /**
     * Google???
     */
    public void syncCalendar() {
        Log.d("DEBUG", "MainCalendar syncCalendar Start");
        //???
        if (NetWorkUtil.isOffline(this.getApplicationContext())) {
            //??
            Log.d("DEBUG", "MainCalendar onCreate Offline");
            Toast.makeText(MainCalendar.this, getString(R.string.network_if_err), Toast.LENGTH_LONG).show();
        } else {
            //??
            Log.d("DEBUG", "MainCalendar onCreate Online");
            //?
            strUpdateStartTime = DateUtil.toUTCString(new GregorianCalendar());
            //?DB??
            sdhDB = new ScheduleDatabaseHelper(this);
            AuthInfo aiObj = selectAuthInfo();
            if (aiObj == null) {
                Toast.makeText(MainCalendar.this, getString(R.string.sqlite_read_err), Toast.LENGTH_LONG).show();
                endActivity();
            } else {
                strAccessToken = aiObj.getStrAccessToken();
                strRefreshToken = aiObj.getStrRefreshToken();
                lgAccessTokenExpire = aiObj.getLgAccessTokenExpire();
                //??
                strLastUpdate = aiObj.getStrLastUpdate();
                if (strRefreshToken == null) {
                    //RefreshToken???????
                    if (strAuthCode == null || strAuthCode.equals("")) {
                        //AuthCode????getOAuthCode
                        getOAuthCode();
                    } else {
                        //AuthCode???????Web??Auth????????AccessToken?
                        //?????handler
                        hGetTokenObj = new Handler();
                        //???handler
                        hSyncCalendarObj = new Handler();
                        //???handler
                        hObj = new Handler();
                        getAccessToken();
                    }
                } else if (lgAccessTokenExpire < Calendar.getInstance().getTimeInMillis()) {
                    Log.d("DEBUG", "MainCalendar syncCalendar lgAccessTokenExpire" + lgAccessTokenExpire);
                    Log.d("DEBUG", "MainCalendar syncCalendar < " + Calendar.getInstance().getTimeInMillis());
                    //?????handler
                    hGetTokenObj = new Handler();
                    //???handler
                    hSyncCalendarObj = new Handler();
                    //???handler
                    hObj = new Handler();
                    //AccessToken?????AccessToken??????getGoogleCalendar
                    refreshToken();
                } else {
                    //???handler
                    hObj = new Handler();
                    //???handler
                    hSyncCalendarObj = new Handler();
                    //AccessToken??????????getGoogleCalendar()
                    syncGoogleCalendar();
                }
            }
        }
        Log.d("DEBUG", "MainCalendar syncCalendar End");
    }

    /**
     * startOAuth
     * OAuth 2.0?????????
     * Google????
     */
    private void getOAuthCode() {
        Log.d("DEBUG", "MainCalendar getOAuthCode Start");
        //URI????Intent?
        Intent intent = new Intent(Intent.ACTION_VIEW, OAUTH_URI);
        //?????????URI??
        startActivityForResult(intent, BROWSER);
        Log.d("DEBUG", "MainCalendar getOAuthCode End");
    }

    /**
     * AccessToken????
     *
     */
    private void getAccessToken() {
        Log.d("DEBUG", "MainCalendar getAccessToken Start");
        //??
        pdObj = new ProgressDialog(MainCalendar.this);
        pdObj.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        pdObj.setMessage(getString(R.string.getToken));
        //?????
        pdObj.setCancelable(false);
        //?
        pdObj.show();
        //????
        Thread thread = new Thread(runGetAccessToken);
        //?
        thread.start();
        Log.d("DEBUG", "MainCalendar getAccessToken End");
    }

    /**
     * runGetAccessToken??
     */
    private Runnable runGetAccessToken = new Runnable() {
        public void run() {
            Log.d("DEBUG", "MainCalendar runGetAccessToken run Start");
            strAccessToken = null;
            strRefreshToken = null;
            ArrayList<NameValuePair> alNVP = new ArrayList<NameValuePair>();
            //???nameValuePair?
            //code?getOAuthCode?????(AuthCode)
            alNVP.add(new BasicNameValuePair("client_id", CLIENT_ID));
            alNVP.add(new BasicNameValuePair("client_secret", CLIENT_SECRET));
            alNVP.add(new BasicNameValuePair("redirect_uri", REDIRECT_URI));
            alNVP.add(new BasicNameValuePair("grant_type", GRANT_TYPE_A));
            alNVP.add(new BasicNameValuePair("code", strAuthCode));
            //token???
            mpTokens = getToken(alNVP);
            if (mpTokens != null) {
                hGetTokenObj.post(new Runnable() {
                    public void run() {
                        //tokens??????
                        strAccessToken = mpTokens.get(ACCESS_TOKEN);
                        strRefreshToken = mpTokens.get(REFRESH_TOKEN);
                        lgAccessTokenExpire = Long.valueOf(mpTokens.get(EXPIRES_IN));
                        AuthInfo aiObj = new AuthInfo();
                        aiObj.setStrAccessToken(strAccessToken);
                        aiObj.setStrRefreshToken(strRefreshToken);
                        aiObj.setLgAccessTokenExpire(lgAccessTokenExpire);
                        boolean blResult = sdhDB.updateAuthInfoRefreshToken(aiObj);
                        if (blResult == false) {
                            //
                            //
                            strAuthCode = null;
                            pdObj.dismiss();
                            Toast.makeText(MainCalendar.this, getString(R.string.getToken_err), Toast.LENGTH_LONG)
                                    .show();
                        } else {
                            //
                            pdObj.dismiss();
                            //Google???
                            syncGoogleCalendar();
                        }
                    }
                });
            } else {
                hGetTokenObj.post(new Runnable() {
                    public void run() {
                        //
                        //
                        strAuthCode = null;
                        pdObj.dismiss();
                        Toast.makeText(MainCalendar.this, getString(R.string.getToken_err), Toast.LENGTH_LONG)
                                .show();
                    }
                });
            }
            Log.d("DEBUG", "MainCalendar runGetAccessToken run End");
        }
    };

    /**
     * ??Token??
     *
     * @param ArrayList<NameValuePair> ??????
     * @return Map<String,String> ?????Map (?HashMap)
     */
    private Map<String, String> getToken(ArrayList<NameValuePair> nameValuePair) {
        Log.d("DEBUG", "MainCalendar getToken Start");
        long lgNowTime = Calendar.getInstance().getTimeInMillis();
        HashMap<String, String> hmResult = new HashMap<String, String>();
        //HttpPost?URL???
        HttpPost hpObj = new HttpPost(TOKEN_URL);
        //DefaultHttpClient?HttpClient???Entity??execute
        HttpClient hcObj = new DefaultHttpClient();
        hpObj.setHeader("Content-Type", CONTENT_TYPE_AX);
        try {
            hpObj.setEntity(new UrlEncodedFormEntity(nameValuePair));
            HttpResponse response = hcObj.execute(hpObj);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                //execute???HttpResponse?????
                BufferedReader brObj = new BufferedReader(
                        new InputStreamReader(new BufferedInputStream(response.getEntity().getContent())));
                String strJson = null;
                try {
                    StringBuilder sbObj = new StringBuilder();
                    String strLine;
                    while ((strLine = brObj.readLine()) != null) {
                        sbObj.append(strLine);
                    }
                    strJson = sbObj.toString();
                    //???JSON????
                    JSONObject joRoot = new JSONObject(strJson);
                    if (joRoot.has(ACCESS_TOKEN)) {
                        //Log.d("DEBUG","MainCalendar getToken ACCESS_TOKEN" + joRoot.getString(ACCESS_TOKEN));
                        hmResult.put(ACCESS_TOKEN, joRoot.getString(ACCESS_TOKEN));
                    }
                    if (joRoot.has(REFRESH_TOKEN)) {
                        //Log.d("DEBUG","MainCalendar getToken REFRESH_TOKEN" + joRoot.getString(REFRESH_TOKEN));
                        hmResult.put(REFRESH_TOKEN, joRoot.getString(REFRESH_TOKEN));
                    }
                    if (joRoot.has(EXPIRES_IN)) {
                        //Log.d("DEBUG","MainCalendar getToken EXPIRES_IN" + joRoot.getString(EXPIRES_IN));
                        long lgExpires = Long.valueOf(joRoot.getString(EXPIRES_IN)) * 1000;
                        lgNowTime = lgNowTime + lgExpires;
                        hmResult.put(EXPIRES_IN, String.valueOf(lgNowTime));
                    }
                } catch (JSONException e) {
                    Log.e("ERROR", "MainCalendar getToken JSONException : ", e);
                    return null;
                }
            } else {
                //???????HTTPStatus400
                Log.e("ERROR",
                        "MainCalendar getToken HttpStatus Error:" + response.getStatusLine().getStatusCode());
                return null;
            }
        } catch (UnsupportedEncodingException e) {
            Log.e("ERROR", "MainCalendar getToken UnsupportedEncodingException : ", e);
            return null;
        } catch (ClientProtocolException e) {
            Log.e("ERROR", "MainCalendar getToken ClientProtocolException : ", e);
            return null;
        } catch (IOException e) {
            Log.e("ERROR", "MainCalendar getToken IOException : ", e);
            return null;
        }
        Log.d("DEBUG", "MainCalendar getToken End");
        return hmResult;
    }

    /**
     * AccessToken??
     *
     */
    private void refreshToken() {
        Log.d("DEBUG", "MainCalendar refreshToken Start");
        //??
        pdObj = new ProgressDialog(MainCalendar.this);
        pdObj.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        pdObj.setMessage(getString(R.string.getToken));
        //?????
        pdObj.setCancelable(false);
        //?
        pdObj.show();
        //????
        Thread thread = new Thread(runRefreshToken);
        //?
        thread.start();
        Log.d("DEBUG", "MainCalendar refreshToken End");
    }

    /**
     * runRefreshToken??
     */
    private Runnable runRefreshToken = new Runnable() {
        public void run() {
            Log.d("DEBUG", "MainCalendar runRefreshToken run Start");
            strAccessToken = null;
            //???nameValuePair?
            ArrayList<NameValuePair> alNVP = new ArrayList<NameValuePair>();
            alNVP.add(new BasicNameValuePair("client_id", CLIENT_ID));
            alNVP.add(new BasicNameValuePair("client_secret", CLIENT_SECRET));
            alNVP.add(new BasicNameValuePair("refresh_token", strRefreshToken));
            alNVP.add(new BasicNameValuePair("grant_type", GRANT_TYPE_R));
            //getToken??token?
            mpTokens = getToken(alNVP);
            if (mpTokens != null) {
                hGetTokenObj.post(new Runnable() {
                    public void run() {
                        strAccessToken = mpTokens.get(ACCESS_TOKEN);
                        lgAccessTokenExpire = Long.valueOf(mpTokens.get(EXPIRES_IN));
                        AuthInfo aiObj = new AuthInfo();
                        aiObj.setStrAccessToken(strAccessToken);
                        aiObj.setLgAccessTokenExpire(lgAccessTokenExpire);
                        boolean blResult = sdhDB.updateAuthInfoAccessToken(aiObj);
                        if (blResult == false) {
                            //
                            //
                            pdObj.dismiss();
                            Toast.makeText(MainCalendar.this, getString(R.string.getToken_err), Toast.LENGTH_LONG)
                                    .show();
                        } else {
                            //
                            pdObj.dismiss();
                            //Google???
                            syncGoogleCalendar();
                        }
                    }
                });
            } else {
                hGetTokenObj.post(new Runnable() {
                    public void run() {
                        //
                        //
                        pdObj.dismiss();
                        Toast.makeText(MainCalendar.this, getString(R.string.getToken_err), Toast.LENGTH_LONG)
                                .show();
                    }
                });
            }
            Log.d("DEBUG", "MainCalendar runRefreshToken run End");
        }
    };

    /**
     * getGoogleCalendar ? updateGoogleCalendar??
     * ????
     */
    public void syncGoogleCalendar() {
        Log.d("DEBUG", "MainCalendar syncGoogleCalendar Start");
        //??
        pdObj = new ProgressDialog(MainCalendar.this);
        pdObj.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        pdObj.setMessage(getString(R.string.nowOnSync));
        //?????
        pdObj.setCancelable(false);
        //?
        pdObj.show();
        //????
        Thread thread = new Thread(runSyncGoogleCalendar);
        //?
        thread.start();
        Log.d("DEBUG", "MainCalendar syncGoogleCalendar End");
    }

    /**
     * getGoogleCalendar??
     */
    private Runnable runSyncGoogleCalendar = new Runnable() {
        public void run() {
            Log.d("DEBUG", "MainCalendar runSyncGoogleCalendar run Start");
            blSyncGC = true;
            boolean blGetGC = true;
            boolean blUpdateGC = true;
            intUnreflected = 0;
            //??
            blGetGC = getGoogleCalendar();
            if (blGetGC == false) {
                blSyncGC = false;
            } else {
                //?
                blUpdateGC = updateGoogleCalendar();
                if (blUpdateGC == false) {
                    blSyncGC = false;
                } else {
                    //?
                    boolean blChangeScheduleCountResult = selectChangeScheduleCount();
                    if (blChangeScheduleCountResult == false) {
                        Log.e("ERROR",
                                "MainCalendar runSyncGoogleCalendar ?");
                        blSyncGC = false;
                    }
                }
            }
            //
            System.gc();
            //????
            pdObj.dismiss();
            hSyncCalendarObj.post(new Runnable() {
                public void run() {
                    //???
                    if (blSyncGC == false) {
                        Toast.makeText(MainCalendar.this, getString(R.string.gCSync_err), Toast.LENGTH_LONG).show();
                    }
                    //???????????
                    if (intUnreflected != 0) {
                        Toast.makeText(MainCalendar.this, getString(R.string.gCSync_Unreflected) + intUnreflected,
                                Toast.LENGTH_LONG).show();
                    }
                    //hSyncCalendarObj??????
                    //?(??)
                    makeCalDateCell();
                }
            });
            Log.d("DEBUG", "MainCalendar runSyncGoogleCalendar run End");
        }
    };

    /**
     * Google???
     * 
     * @return boolean true:??, false:??
     */
    public boolean getGoogleCalendar() {
        Log.d("DEBUG", "MainCalendar getGoogleCalendar Start");
        boolean blResult = true;
        boolean blInitFlg = true;
        String strUpdatedQuery = null;
        if (strLastUpdate != null) {
            //?????????updated-min??????????
            strUpdatedQuery = "&updated-min=" + strLastUpdate;
        } else {
            //???????updateQuery????
            strUpdatedQuery = "";
        }
        //?(1300)?strNextUrl
        String strNextUrl = CALENDAR_FEED_URL;
        //ScheduleDatabaseHelper?
        sdhDB = new ScheduleDatabaseHelper(MainCalendar.this);
        //nextUrl?????
        while (strNextUrl != null) {
            //?(????????????)
            GDataCalendarParser gcpObj = new GDataCalendarParser(this, sdhDB);
            StringBuffer sbObj = new StringBuffer();
            sbObj.append(strNextUrl);
            //?????AccessTokenoauth_token???URL?
            sbObj.append("&oauth_token=");
            //Google???????
            if (strRefreshToken != null && (lgAccessTokenExpire < Calendar.getInstance().getTimeInMillis())) {
                boolean blReToken = true;
                //????
                blReToken = reacquisitionToken();
                if (blReToken == false) {
                    //?????????
                    Log.e("ERROR", "MainCalendar getGoogleCalendar ????");
                    blResult = false;
                    break;
                }
            }
            sbObj.append(strAccessToken);
            //300????????strNextUrl???????
            if (blInitFlg == true) {
                sbObj.append(strUpdatedQuery);
            }
            ArrayList<String> alResult = new ArrayList<String>();
            alResult = gcpObj.parse(httpGet(sbObj.toString()), 0l);
            if (alResult == null || alResult.get(1) != null) {
                //???????
                blResult = false;
                //Google?(OutOfMemoryError)
                alResult = null;
                break;
            } else {
                strNextUrl = alResult.get(0);
                Log.d("DEBUG", "MainCalendar getGoogleCalendar strNextUrl" + strNextUrl);
                blInitFlg = false;
                //?(OutOfMemoryError)
                alResult = null;
            }
            //StringBuilder?(OutOfMemoryError)
            sbObj = null;
            //?(OutOfMemoryError)
            gcpObj = null;
            //
            System.gc();
        }
        if (blResult == true) {
            strLastUpdate = strUpdateStartTime;
            //????
            blResult = saveLastUpdate();
        }
        Log.d("DEBUG", "MainCalendar getGoogleCalendar End");
        return blResult;
    }

    /**
     * ????
     * 
     * @return boolean true:??, false:??
     */
    public boolean reacquisitionToken() {
        Log.d("DEBUG", "MainCalendar reacquisitionToken Start");
        boolean blResult = true;
        //???nameValuePair?
        ArrayList<NameValuePair> alNVP = new ArrayList<NameValuePair>();
        alNVP.add(new BasicNameValuePair("client_id", CLIENT_ID));
        alNVP.add(new BasicNameValuePair("client_secret", CLIENT_SECRET));
        alNVP.add(new BasicNameValuePair("refresh_token", strRefreshToken));
        alNVP.add(new BasicNameValuePair("grant_type", GRANT_TYPE_R));
        //getToken??token?
        mpTokens = getToken(alNVP);
        if (mpTokens != null) {
            strAccessToken = mpTokens.get(ACCESS_TOKEN);
            lgAccessTokenExpire = Long.valueOf(mpTokens.get(EXPIRES_IN));
            AuthInfo aiObj = new AuthInfo();
            aiObj.setStrAccessToken(strAccessToken);
            aiObj.setLgAccessTokenExpire(lgAccessTokenExpire);
            blResult = sdhDB.updateAuthInfoAccessToken(aiObj);
        } else {
            blResult = false;
        }
        Log.d("DEBUG", "MainCalendar reacquisitionToken End");
        return blResult;
    }

    /**
     * URL??InputStream??
     * @param String ?URL
     * *return InputStream ??????????InputStream
     */
    public InputStream httpGet(String strURL) {
        Log.d("DEBUG", "MainCalendar httpGet Start");
        HttpGet hgObj = new HttpGet(strURL);
        HttpClient hcObj = new DefaultHttpClient();
        //GData Version 2?Header
        hgObj.setHeader(GDATA_VERSION_TAG, GDATA_VERSION);
        HttpResponse response;
        try {
            //HTTP?
            response = hcObj.execute(hgObj);
            int statusCode = response.getStatusLine().getStatusCode();
            Log.d("DEBUG", "MainCalendar httpGet HttpResponseCode : " + statusCode);
            //HttpGet,HttpClient?(OutOfMemory)
            hgObj = null;
            hcObj = null;
            if (statusCode == HttpStatus.SC_OK) {
                //????response?InputStream??
                return response.getEntity().getContent();
            } else if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
                return null;
            }
        } catch (Exception e) {
            Log.e("ERROR", "MainCalendar httpGet ERROR", e);
            //HttpGet,HttpClient?(OutOfMemory)
            hgObj = null;
            hcObj = null;
        }
        Log.d("DEBUG", "MainCalendar httpGet End");
        return null;
    }

    /**
     * ????
     * 
     * @return boolean true:??, false:??
     */
    public boolean saveLastUpdate() {
        Log.d("DEBUG", "MainCalendar saveLastUpdate Start");
        boolean blResult = true;
        AuthInfo aiObj = new AuthInfo();
        aiObj.setStrLastUpdate(strLastUpdate);
        blResult = sdhDB.updateAuthInfoLastUpdate(aiObj);
        Log.d("DEBUG", "MainCalendar saveLastUpdate End");
        return blResult;
    }

    /**
     * Google??
     * 
     * @return boolean true:??, false:??
     */
    public boolean updateGoogleCalendar() {
        Log.d("DEBUG", "MainCalendar updateGoogleCalendar Start");
        boolean blResult = true;
        //ScheduleDatabaseHelper?
        sdhDB = new ScheduleDatabaseHelper(this);
        //?
        boolean blChangeScheduleResult = selectChangeSchedule();
        if (blChangeScheduleResult == false) {
            Log.e("ERROR", "MainCalendar updateGoogleCalendar ?");
            blResult = false;
        } else {
            //?
            GDataCalendarParser gcpObj = new GDataCalendarParser(this, sdhDB);
            //Delete???
            String strDeleteResult = null;
            String strInsertTime = null;
            //Insert?
            for (GDataEvent gdeObj : alInsertGCEvents) {
                //Insert???POST????
                //?parse???????
                StringBuffer sbPostURL = new StringBuffer();
                sbPostURL.append(DEFAULT_URL);
                sbPostURL.append("?oauth_token=");
                //Google??????
                if (strRefreshToken != null && (lgAccessTokenExpire < Calendar.getInstance().getTimeInMillis())) {
                    boolean blReToken = true;
                    //????
                    blReToken = reacquisitionToken();
                    if (blReToken == false) {
                        //?????????
                        Log.e("ERROR",
                                "MainCalendar updateGoogleCalendar ????");
                        blResult = false;
                        break;
                    }
                }
                sbPostURL.append(strAccessToken);
                //??
                strInsertTime = DateUtil.toUTCString(new GregorianCalendar());
                //?updated-min????????
                sbPostURL.append("&updated-min=");
                sbPostURL.append(strInsertTime);
                ArrayList<String> alResult = new ArrayList<String>();
                alResult = gcpObj.parse(httpPost(sbPostURL.toString(), gcpObj.insertSerializer(gdeObj)),
                        gdeObj.getLgAlarmFlag());
                if (blHttpSucceeded && alResult != null && alResult.get(1) == null
                        && intResponseCode == HttpURLConnection.HTTP_CREATED) {
                    //??
                    //SQL?(ID)
                    Schedule objSchedule = new Schedule();
                    objSchedule.setLgId(gdeObj.getLgId());
                    //SCHEDULE(?)
                    blResult = sdhDB.deleteScheduleId(objSchedule);
                    if (blResult == false) {
                        //SCHEDULE??
                        Log.e("ERROR", "MainCalendar updateGoogleCalendar Insert???  "
                                + gdeObj.getLgId());
                        //?(OutOfMemoryError)
                        alResult = null;
                        break;
                    }
                    //?(OutOfMemoryError)
                    alResult = null;
                } else if (blHttpSucceeded && alResult != null && alResult.get(1) == null
                        && intResponseCode == HttpURLConnection.HTTP_OK) {
                    //?????Google?????????
                    Log.e("ERROR",
                            "MainCalendar updateGoogleCalendar Insert???200?  "
                                    + gdeObj.getLgId());
                    //?(OutOfMemoryError)
                    alResult = null;
                } else {
                    //HttpPost??
                    Log.e("ERROR", "MainCalendar updateGoogleCalendar Insert?  " + gdeObj.getLgId());
                    blResult = false;
                    //?(OutOfMemoryError)
                    alResult = null;
                    break;
                }
            }

            //Insert?????????Update?
            if (blResult == true) {
                //Update?
                for (GDataEvent gdeObj : alUpdateGCEvents) {
                    //URL?
                    StringBuffer sbPostURL = new StringBuffer();
                    sbPostURL.append(gdeObj.getStrEditUrl());
                    sbPostURL.append("?oauth_token=");
                    //Google??????
                    if (strRefreshToken != null
                            && (lgAccessTokenExpire < Calendar.getInstance().getTimeInMillis())) {
                        boolean blReToken = true;
                        //????
                        blReToken = reacquisitionToken();
                        if (blReToken == false) {
                            //?????????
                            Log.e("ERROR",
                                    "MainCalendar updateGoogleCalendar ????");
                            blResult = false;
                            break;
                        }
                    }
                    sbPostURL.append(strAccessToken);
                    //?????
                    ArrayList<String> alResult = new ArrayList<String>();
                    alResult = gcpObj.parse(
                            httpPut(sbPostURL.toString(),
                                    gcpObj.updateSerializer(httpGet(sbPostURL.toString()), gdeObj)),
                            gdeObj.getLgAlarmFlag());
                    //??Google??????
                    //Modified????????????????
                    //???????????MODIFIED?????????
                    //???????????)
                    if (alResult == null || !(blHttpSucceeded && alResult.get(1) == null)) {
                        //HttpPut????DB?
                        Log.e("ERROR", "MainCalendar updateGoogleCalendar Update?  " + gdeObj.getLgId());
                        blResult = false;
                        //?(OutOfMemoryError)
                        alResult = null;
                        break;
                    }
                    //?(OutOfMemoryError)
                    alResult = null;
                }
            }

            //Insert?orUpdate?????????Delete?
            if (blResult == true) {
                //Delete?
                for (GDataEvent gdeObj : alDeleteGCEvents) {
                    //URL???httpDelete??
                    StringBuffer sbPostURL = new StringBuffer();
                    sbPostURL.append(gdeObj.getStrEditUrl());
                    sbPostURL.append("?oauth_token=");
                    //Google??????
                    if (strRefreshToken != null
                            && (lgAccessTokenExpire < Calendar.getInstance().getTimeInMillis())) {
                        boolean blReToken = true;
                        //????
                        blReToken = reacquisitionToken();
                        if (blReToken == false) {
                            //?????????
                            Log.e("ERROR",
                                    "MainCalendar updateGoogleCalendar ????");
                            blResult = false;
                            break;
                        }
                    }
                    sbPostURL.append(strAccessToken);
                    InputStream isResult = httpDelete(sbPostURL.toString());
                    if (isResult != null) {
                        strDeleteResult = InputCheckUtil.convertStreamToString(isResult);
                    } else {
                        strDeleteResult = null;
                    }
                    if (blHttpSucceeded && (strDeleteResult != null && strDeleteResult.equals(""))) {
                        //?
                        //SQL?(ID)
                        Schedule objSchedule = new Schedule();
                        objSchedule.setLgId(gdeObj.getLgId());
                        //SCHEDULE(?)
                        blResult = sdhDB.deleteScheduleId(objSchedule);
                        if (blResult == false) {
                            //SCHEDULE??
                            Log.e("ERROR",
                                    "MainCalendar updateGoogleCalendar Delete???  "
                                            + gdeObj.getLgId());
                            break;
                        }
                    } else if (blHttpSucceeded
                            && (strDeleteResult != null && strDeleteResult.equals("") == false)) {
                        //?????Google????????
                        Log.e("ERROR",
                                "MainCalendar updateGoogleCalendar Delete???200???????  "
                                        + gdeObj.getLgId());
                    } else {
                        //HttpPost??
                        Log.e("ERROR", "MainCalendar updateGoogleCalendar Delete?  " + gdeObj.getLgId());
                        blResult = false;
                        break;
                    }
                }
            }
            //?(OutOfMemoryError)
            gcpObj = null;
            alInsertGCEvents = null;
            alUpdateGCEvents = null;
            alDeleteGCEvents = null;
        }
        Log.d("DEBUG", "MainCalendar updateGoogleCalendar End");
        return blResult;
    }

    /**
     * ????
     *
     * @return ?????true
     */
    private boolean selectChangeSchedule() {
        Log.d("DEBUG", "MainCalendar selectChangeSchedule Start");
        boolean blResult = true;
        ScheduleCursor scObj = null;
        //insert/update/delete?????
        alInsertGCEvents = new ArrayList<GDataEvent>();
        alUpdateGCEvents = new ArrayList<GDataEvent>();
        alDeleteGCEvents = new ArrayList<GDataEvent>();
        try {
            String[] where_args = {};
            //??
            scObj = sdhDB.getChangeScheduleList(where_args);
            //??
            startManagingCursor(scObj);
            Log.d("DEBUG", "MainCalendar selectChangeSchedule ScheduleCursor Count : " + scObj.getCount());
            for (int intCt = 0; intCt < scObj.getCount(); intCt++) {
                //?
                GDataEvent gdeObj = new GDataEvent();
                //ID
                gdeObj.setLgId(scObj.getColId());
                //
                gdeObj.setLgDeleted(scObj.getColDeleted());
                //
                gdeObj.setLgModified(scObj.getColModified());
                //??
                gdeObj.setStrTitle(scObj.getColTitle());
                //
                gdeObj.setStrWhere(scObj.getColGdWhere());
                //
                gdeObj.setGcStart(scObj.getColGdWhenStarttime());
                //
                gdeObj.setGcEnd(scObj.getColGdWhenEndtime());
                //
                gdeObj.setStrContent(scObj.getColContent());
                //?
                gdeObj.setGcPublished(scObj.getColPublished());
                //
                gdeObj.setGcUpdated(scObj.getColUpdated());
                //
                gdeObj.setStrCategory(scObj.getColCategory());
                //URL
                gdeObj.setStrEditUrl(scObj.getColEditUrl());
                //
                gdeObj.setStrEventStatus(scObj.getColGdEventstatus());
                //ID
                gdeObj.setStrEventId(scObj.getColCalendarId());
                //ETAG
                gdeObj.setStrEtag(scObj.getColEtag());
                //?(??)
                //(??)
                gdeObj.setAlarmMap(scObj.getColAlarmList());
                //(TDCC)
                gdeObj.setLgAlarmFlag(scObj.getColAlarmFlag());

                if (gdeObj.getStrEventId() == null) {
                    //Id???????Google????????insert?
                    alInsertGCEvents.add(gdeObj);
                } else if (gdeObj.getLgDeleted() == 1) {
                    //??????delete?
                    alDeleteGCEvents.add(gdeObj);
                } else {
                    //???update?
                    alUpdateGCEvents.add(gdeObj);
                }
                scObj.moveToNext();
            }
            scObj.close();
        } catch (SQLException e) {
            blResult = false;
            Log.e("ERROR", "MainCalendar selectChangeSchedule DB Error", e);
        } finally {
            if (scObj != null) {
                scObj.close();
            }
        }
        Log.d("DEBUG", "MainCalendar selectChangeSchedule End");
        return blResult;
    }

    /**
     * Http Delete?
     * 
     * @param strUrl
     * @return InputStream ???XML?InputStream
     */
    public InputStream httpDelete(String strUrl) {
        Log.d("DEBUG", "MainCalendar httpDelete Start");
        Log.d("DEBUG", "MainCalendar httpDelete End");
        return httpPostXml(strUrl, "", "DELETE");
    }

    /**
     * Http Post?
     *
     * @param strUrl
     * @param strXml
     * @return InputStream ???XML?InputStream
     */
    public InputStream httpPost(String strUrl, String strXml) {
        Log.d("DEBUG", "MainCalendar httpPost Start");
        Log.d("DEBUG", "MainCalendar httpPost End");
        return httpPostXml(strUrl, strXml, null);
    }

    /**
     * Http Put?
     *
     * @param strUrl
     * @param strXml
     * @return InputStream ???XML?InputStream
     */
    public InputStream httpPut(String strUrl, String strXml) {
        Log.d("DEBUG", "MainCalendar httpPut Start");
        Log.d("DEBUG", "MainCalendar httpPut End");
        return httpPostXml(strUrl, strXml, "PUT");
    }

    /**
     * XML?????
     * 
     * @param strUrl
     * @param strXml
     * @param strMethod (PUT,DELETE)
     * @return InputStream ???InputStream
     */
    public InputStream httpPostXml(String strUrl, String strXml, String strMethod) {
        Log.d("DEBUG", "MainCalendar httpPostXml Start");
        blHttpSucceeded = false;
        try {
            while (strUrl != null) {
                URL urlObj = new URL(strUrl);
                //URL?????
                HttpURLConnection httpURLCObj = (HttpURLConnection) urlObj.openConnection();
                //?POST?
                httpURLCObj.setRequestMethod("POST");
                //GData-Version?
                httpURLCObj.setRequestProperty(GDATA_VERSION_TAG, GDATA_VERSION);
                if (strMethod != null) {
                    //POST??????If-Match:*?X-HTTP-Method-Override
                    httpURLCObj.setRequestProperty("If-Match", "*");
                    httpURLCObj.setRequestProperty("X-HTTP-Method-Override", strMethod);
                }
                //
                httpURLCObj.setDoOutput(true);
                //Content-Type??XML
                httpURLCObj.setRequestProperty("Content-Type", CONTENT_TYPE_AA);
                //
                httpURLCObj.setUseCaches(false);
                //OutputStreamWriter??XML??
                OutputStreamWriter outputStreamWriter = new OutputStreamWriter(httpURLCObj.getOutputStream(),
                        "UTF-8");
                outputStreamWriter.write(strXml);
                outputStreamWriter.close();
                //HTTP??
                intResponseCode = 0;
                intResponseCode = httpURLCObj.getResponseCode();
                strUrl = null;
                Log.d("DEBUG", "MainCalendar httpPostXml HttpResponseCode : " + intResponseCode);
                if (intResponseCode == HttpURLConnection.HTTP_OK
                        || intResponseCode == HttpURLConnection.HTTP_CREATED) {
                    //??OK???CREATED?????
                    blHttpSucceeded = true;
                    Log.d("DEBUG", "MainCalendar httpPostXml End(1)");
                    //?InputStream??
                    return httpURLCObj.getInputStream();
                } else if (intResponseCode == HttpURLConnection.HTTP_MOVED_TEMP) {
                    //??MOVED_TEMP?????????
                    //?Location????URL????(?while?
                    Map<String, List<String>> mResponseHeaders = httpURLCObj.getHeaderFields();
                    if (mResponseHeaders.containsKey("Location")) {
                        strUrl = mResponseHeaders.get("Location").get(0);
                    } else if (mResponseHeaders.containsKey("location")) {
                        strUrl = mResponseHeaders.get("location").get(0);
                    }
                } else {
                    //??OK???CREATED???MOVED_TEMP??
                    blHttpSucceeded = false;
                    Log.d("DEBUG",
                            "MainCalendar httpPostXml End(2)  ??OK,CREATED,MOVED_TEMP??");
                }
            }
        } catch (Exception e) {
            Log.e("ERROR", "MainCalendar httpPostXml ERROR", e);
        }
        Log.d("DEBUG", "MainCalendar httpPostXml End(3)");
        return null;
    }

    /**
     * AuthInfo????
     * @param strAryArgs SQL?
     * @return ?????true
     */
    private AuthInfo selectAuthInfo() {
        Log.d("DEBUG", "MainCalendar selectAuthInfo Start");
        AuthInfo authInfoObj = new AuthInfo();
        ScheduleDatabaseHelper.AuthInfoCursor sdObj = null;
        try {
            //?
            String[] where_args = {};
            //??
            sdObj = sdhDB.getAuthInfo(where_args);
            //??
            startManagingCursor(sdObj);
            Log.d("DEBUG", "MainCalendar selectAuthInfo AuthInfoCursor Count : " + sdObj.getCount());
            for (int intCt = 0; intCt < sdObj.getCount(); intCt++) {
                //AuthInfo?
                //
                authInfoObj.setStrAccessToken(sdObj.getColAccessToken());
                //?
                authInfoObj.setLgAccessTokenExpire(sdObj.getColAccessTokenExpire());
                //
                authInfoObj.setStrRefreshToken(sdObj.getColRefreshToken());
                //
                authInfoObj.setStrLastUpdate(sdObj.getColLastUpdate());
                sdObj.moveToNext();
            }
            sdObj.close();
        } catch (SQLException e) {
            Log.e("ERROR", "MainCalendar selectAuthInfo DB Error", e);
            if (sdObj != null) {
                sdObj.close();
            }
            authInfoObj = null;
        } finally {
            if (sdObj != null) {
                sdObj.close();
            }
        }
        Log.d("DEBUG", "MainCalendar selectAuthInfo End");
        return authInfoObj;
    }

    /**
     * ???
     *
     * @return ?????true
     */
    private boolean selectChangeScheduleCount() {
        Log.d("DEBUG", "MainCalendar selectChangeScheduleCount Start");
        boolean blResult = true;
        ScheduleCursor scObj = null;
        try {
            String[] where_args = {};
            //??
            scObj = sdhDB.getChangeScheduleCount(where_args);
            //??
            startManagingCursor(scObj);
            for (int intCt = 0; intCt < scObj.getCount(); intCt++) {
                //
                intUnreflected = (int) scObj.getColScheduleCount();
                scObj.moveToNext();
            }
            scObj.close();
        } catch (SQLException e) {
            blResult = false;
            Log.e("ERROR", "MainCalendar selectChangeScheduleCount DB Error", e);
        } finally {
            if (scObj != null) {
                scObj.close();
            }
        }
        Log.d("DEBUG", "MainCalendar selectChangeScheduleCount End");
        return blResult;
    }

    /**
     * About?
     *
     * @param context 
     * @param title 
     * @param text 
     */
    //About?
    private static void showDialog(Context context, String title, String text) {
        Log.d("DEBUG", "MainCalendar showDialog Start");
        AlertDialog.Builder ad = new AlertDialog.Builder(context);
        ad.setTitle(title);
        ad.setMessage(text);
        ad.show();
        Log.d("DEBUG", "MainCalendar showDialog End");
    }

    /**
     * ??
     *
     * @param kEvent  
     * @return ?????true
     */
    @Override
    public boolean dispatchKeyEvent(KeyEvent kEvent) {
        Log.d("DEBUG", "MainCalendar dispatchKeyEvent Start");
        //?????
        if (kEvent.getAction() == KeyEvent.ACTION_DOWN) {
            //?????
            if (kEvent.getKeyCode() == KeyEvent.KEYCODE_BACK) {
                //?yes/no?
                showYesNoDialog(this, R.string.mes1_dialog, R.string.mes2_dialog,
                        new DialogInterface.OnClickListener() {
                            //??
                            public void onClick(DialogInterface dialog, int whith) {
                                if (whith == DialogInterface.BUTTON_POSITIVE) {
                                    //
                                    endActivity();
                                } else if (whith == DialogInterface.BUTTON_NEGATIVE) {
                                    //
                                    return;
                                }
                            }
                        });
            }
        }
        Log.d("DEBUG", "MainCalendar dispatchKeyEvent End");
        return super.dispatchKeyEvent(kEvent);
    }

    /**
     * ?yes/no?
     *
     * @param context 
     * @param titleMsg 
     * @param mainMsg 
     * @param listener  
     */
    private static void showYesNoDialog(Context context, int titleMsg, int mainMsg,
            DialogInterface.OnClickListener listener) {
        Log.d("DEBUG", "MainCalendar showYesNoDialog Start");
        AlertDialog.Builder ad = new AlertDialog.Builder(context);
        ad.setTitle(titleMsg);
        ad.setMessage(mainMsg);
        ad.setPositiveButton(R.string.yes_btn, listener);
        ad.setNegativeButton(R.string.no_btn, listener);
        ad.show();
        Log.d("DEBUG", "MainCalendar showYesNoDialog End");
    }

    /**
     * Activity?
     *
     */
    private void endActivity() {
        Log.d("DEBUG", "MainCalendar endActivity Start");
        //?
        finish();
        Log.d("DEBUG", "MainCalendar endActivity End");
    }

    /**
     * Activity??
     *
     * @param clsNext ?
     * @param strYMD ?
     * @param strYM 
     */
    public void nextActivity(Class clsNext, String strYMD, String strYM) {
        Log.d("DEBUG", "MainCalendar nextActivity Start");
        //?????
        Intent intent = new Intent(this, clsNext);
        //?
        //
        intent.putExtra("calym", strYM);
        //?
        intent.putExtra("calymd", strYMD);
        //?ID
        intent.putExtra("uiid", getString(R.string.uiid1));
        //ID
        intent.putExtra("keyid", 0l);
        //???
        startActivity(intent);
        Log.d("DEBUG", "MainCalendar nextActivity End");
        //?
        endActivity();
    }

    /**
     * onActivityResult
     *  ???Editor??????????
     * @param requestCode ???requestCode
     * @param resultCode ???Activity????
     * @param data ???Activity????Intent
     */
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.d("DEBUG", "MainCalendar onActivityResult Start");
        if (requestCode == BROWSER) {
            Log.d("DEBUG", "MainCalendar onActivityResult requestCode : BROWSER");
            //??????
            Intent intent = new Intent(MainCalendar.this, AuthCodeRegistration.class);
            startActivityForResult(intent, AUTH_CODE_REGISTRATION);
        } else if (requestCode == AUTH_CODE_REGISTRATION && resultCode == RESULT_OK) {
            Log.d("DEBUG", "MainCalendar onActivityResult requestCode : AUTH_CODE_REGISTRATION");
            //AuthCode???Intent?AuthCode?
            strAuthCode = data.getStringExtra(AUTH_CODE);
            //AuthCode?????????????syncCalendar
            syncCalendar();
        }
        Log.d("DEBUG", "MainCalendar onActivityResult End");
    }

    /**
     * ???
     *
     * @param newConfig ??
     */
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        Log.d("DEBUG", "MainCalendar onConfigurationChanged Start");
        super.onConfigurationChanged(newConfig);
        Log.d("DEBUG", "MainCalendar onConfigurationChanged End");
    }

    /**
     * ???
     *
     * @param outState ?
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        Log.d("DEBUG", "MainCalendar onSaveInstanceState Start");
        super.onSaveInstanceState(outState);
        outState.putString("calym", tvYearMonth.getText().toString());
        Log.d("DEBUG", "MainCalendar onSaveInstanceState End");
    }

    /**
     * onDestroy
     * ?
     */
    @Override
    public void onDestroy() {
        Log.d("DEBUG", "MainCalendar onDestroy Start");
        super.onDestroy();
        if (sdhDB != null) {
            sdhDB.close();
        }
        Log.d("DEBUG", "MainCalendar onDestroy End");
    }
}