2014年1月20日 星期一

Get number of days in month

Calendar mycal = new GregorianCalendar(1999, 2-1, 1);

// Get the number of days in that month
int daysInMonth = mycal.getActualMaximum(Calendar.DAY_OF_MONTH); // 28

// Try month in a leap year
mycal = new GregorianCalendar(2014, 2-1, 1);
int daysInMonth2= mycal.getActualMaximum(Calendar.DAY_OF_MONTH);  

Toast.makeText(getApplicationContext(), daysInMonth+" "+daysInMonth2,Toast.LENGTH_SHORT).show();

My Sort by Date

int pass;
String hold,hold2;

for (pass = 1; pass <= (combine_st_date.size() - 1); pass++)
for (int i = 0; i <= (combine_st_date.size() - 2); i++) {
try {
if (date_format.parse(combine_st_date.get(i)).after(
date_format.parse(combine_st_date.get(i + 1)))) {

hold = combine_st_date.get(i);
combine_st_date.set(i, combine_st_date.get(i + 1));
combine_st_date.set(i + 1, hold);

hold2 = combine_data.get(i);
combine_data.set(i, combine_data.get(i + 1));
combine_data.set(i + 1, hold2);
}
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

Sort int array

int a[] = {34,6,41,58,0,12,89,-2,45,25};
      int i, pass, hold;

      for(pass = 1; pass <= (a.length-1); pass++)
           for(i = 0; i <= (a.length-2); i++)
             if(a[i] > a[i + 1])
             {
                    hold = a[i];
                    a[i] = a[i + 1];
                    a[i + 1] = hold;
             }
      for(int i1=0;i1<10;i1++){
      Toast.makeText(getApplicationContext(), ""+a[i1],Toast.LENGTH_SHORT).show();
      }

2014年1月17日 星期五

Calendar RRule Library

package com.example.calen_test;

import java.text.ParseException;

import org.joda.time.LocalDate;
import com.google.ical.compat.jodatime.LocalDateIteratorFactory;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.Toast;

public class MainActivity extends Activity {

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

LocalDate start = new LocalDate(2001, 4, 13);

// Every friday the thirteenth.
String ical = "RRULE:FREQ=MONTHLY" + ";BYDAY=FR" // every Friday
+ ";BYMONTHDAY=13" // that occurs on the 13th of the month
+ ";COUNT=13"; // stop after 13 occurences

// Print out each date in the series.

try {
for (LocalDate date : LocalDateIteratorFactory
.createLocalDateIterable(ical, start, true)) {
// System.out.println(date);
Toast.makeText(getApplicationContext(), "" + date,
Toast.LENGTH_SHORT).show();
}
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

}

2014年1月10日 星期五

Calendar Events Listview

package com.example.test_cal;

import java.security.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

import android.net.Uri;
import android.os.Bundle;
import android.provider.CalendarContract;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.text.format.DateFormat;
import android.view.Menu;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.HashMap;
 
import android.app.Activity;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnCreateContextMenuListener;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.AdapterView.OnItemClickListener;

public class MainActivity extends Activity {
private String getDate(long timeStamp){

   try{
       SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
       Date netDate = (new Date(timeStamp));
       return sdf.format(netDate);
   }
   catch(Exception ex){
       return "xx";
   }
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);



//ListView "listView1"
        ListView list = (ListView) findViewById(R.id.listView1);//綁定Layout裡面的ListView
       
        //生成動態數組,加入數據
        ArrayList<HashMap<String, Object>> listItem = new ArrayList<HashMap<String, Object>>();

       
       


Context context = getApplicationContext();
ContentResolver contentResolver = context.getContentResolver();
// get current time
// needed to compare with event time from calendar
// all times are UTC so with one value we can check the date too
// see wiki for UTC time
// current time
long ntime = System.currentTimeMillis();
// read from the first calendar
Cursor cursr = contentResolver
.query(CalendarContract.Events.CONTENT_URI, new String[] {
"calendar_id", "title", "description", "dtstart",
"dtend", "eventLocation" }, null, null, CalendarContract.Instances.DTSTART + " ASC");
cursr.moveToFirst();
String[] CalNames = new String[cursr.getCount()];
int[] CalIds = new int[cursr.getCount()];
for (int i = 0; i < CalNames.length; i++) {
CalIds[i] = cursr.getInt(0);

String str_startdate = getDate(cursr.getLong(3));
String str_enddate = getDate(cursr.getLong(4));


CalNames[i] = "Event" + cursr.getInt(0) + ": \nTitle: "
+ cursr.getString(1) + "\nDescription: "
+ cursr.getString(2) + "\nStart Date: "
+  str_startdate+ "\nEnd Date : " + str_enddate
+ "\nLocation : " + cursr.getString(5);

HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("ItemImage", R.drawable.ic_launcher);//Photo ID
        map.put("ItemTitle", "Title: "+cursr.getString(1)); //Title
        map.put("ItemText", "Description: "+cursr.getString(2)+"\nStart Date: "
+  str_startdate+ "\nEnd Date : " + str_enddate); //Content

        listItem.add(map);

long StartTime = cursr.getLong(3);
long EndTime = cursr.getLong(4);
// do compare here
// if we are on the middle of something stop checking and leave the
// loop
if ((StartTime < ntime) && (ntime < EndTime)) {
System.out.println("In the middle of something");
break;
}
cursr.moveToNext();
}
cursr.close();


        //生成適配器的Item和動態數組對應的元素
        SimpleAdapter listItemAdapter = new SimpleAdapter(this,listItem,//數據源
            R.layout.list_item,//ListItem的XML實現
            //動態數組與ImageItem對應的子項      
            new String[] {"ItemImage","ItemTitle", "ItemText"},
            //ImageItem的XML文件裡面的一個ImageView,兩個TextView ID
            new int[] {R.id.ItemImage,R.id.ItemTitle,R.id.ItemText}
        );
     
        //Add and Show
        list.setAdapter(listItemAdapter);
       
        //One Click
        list.setOnItemClickListener(new OnItemClickListener() {

public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
//One Click To-Do
}
});
       
      //添加長按點擊
        list.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {

public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {
//Long Press To-Do
}
});
//End of ListView "listView1"
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

}



---------------------------------------------------
EndDate小過StartDate姐係要重複

Read calendar events

Many developers would like to check the user's calendar for events. In our example we are checking if the user is in the middle of something right now, if so we are printing a simple message.

This will work with android 2.1 and up. It will also work for all day events.

Please note that the android emulator doesn't have calendar installed! 
I test my projects on my android phone.

On with some code:

CalendarContract.Events.CONTENT_URI = "content://com.android.calendar/events"


         Context context = getApplicationContext();    
         ContentResolver contentResolver = context.getContentResolver();  
          //get current time  
              //needed to compare with event time from calendar  
              //all times are UTC so with one value we can check the date too  
              //see wiki for UTC time  
         //current time  
          long ntime = System.currentTimeMillis();  
              //read from the first calendar  
              Cursor cursr = contentResolver.query(Uri.parse("content://com.android.calendar/events"), new String[]{ "calendar_id", "title", "description", "dtstart", "dtend", "eventLocation" }, "calendar_id=1", null, null);       
              cursr.moveToFirst();  
          String[] CalNames = new String[cursr.getCount()];  
          int[] CalIds = new int[cursr.getCount()];  
          for (int i = 0; i < CalNames.length; i++) {  
            CalIds[i] = cursr.getInt(0);             
            CalNames[i] = "Event"+cursr.getInt(0)+": \nTitle: "+ cursr.getString(1)+"\nDescription: "+cursr.getString(2)+"\nStart Date: "+cursr.getLong(3)+"\nEnd Date : "+cursr.getLong(4)+"\nLocation : "+cursr.getString(5);  
            long StartTime = cursr.getLong(3);  
            long EndTime = cursr.getLong(4);  
            //do compare here  
            //if we are on the middle of something stop checking and leave the loop  
            if ((StartTime<ntime)&&(ntime<EndTime)) {  
                 System.out.println("In the middle of something");  
                 break;  
            }                  
            cursr.moveToNext();  
          }  
          cursr.close();  

Calendar get Date (timeStamp long to string)

private String getDate(long timeStamp){

    try{
        DateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
        Date netDate = (new Date(timeStamp));
        return sdf.format(netDate);
    }
    catch(Exception ex){
        return "xx";
    }
} 
Related Posts Plugin for WordPress, Blogger...