How to get events from calendar for particular week in android? - android

I want to display the events for only one week in the listView,but I got all the events and it is displaying in the listview.
I am using this code to get the events for particular date ,but is not getting any events from calendar.The event count is 0.I am struct with this problem! How to get events for particular date or week?
public class Meeting extends Activity {
public ConferenceAdapter adapter;
ListView meetingListView;
static Cursor cursor;
private String description = null;
private String where = null;
public String[] number;
static List<GoogleCalendar> gCalendar = null;
private static String startString;
private static String endString;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ec_meeting);
adapter = new ConferenceAdapter(this);
readCalendar(this);
meetingListView = (ListView) findViewById(R.id.meetinglistView);
meetingListView.setAdapter(new MeetingListViewAdapter(Meeting.this, adapter, gCalendar));
meetingListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int arg2, long arg3) {
TextView descriptionId1 = ((TextView) view.findViewById(R.id.descriptionmeeting));
TextView where=((TextView) view.findViewById(R.id.wheretextView));
TextView tittle = ((TextView) view.findViewById(R.id.titlemeeting));
Meeting.this.where=where.getText().toString();
description = descriptionId1.getText().toString();
StringBuffer numbers =new StringBuffer();
String a=Meeting.this.where.replaceAll("-","").replaceAll(" ", "").replaceAll("\\(","").replaceAll("\\)","")+description.replaceAll("-","").replaceAll(" ", "").replaceAll("\\(","").replaceAll("\\)","");
if(a.isEmpty()){
Toast.makeText(getApplicationContext(),"Sorry no conference numbers found", Toast.LENGTH_LONG).show();
}else{
Pattern p = Pattern.compile("[0-9]+[0-9]");
Matcher m = p.matcher(a);
while (m.find()) {
Meeting.this.addComma(numbers,m.group().toString());
}
number = numbers.toString().split(",");
Intent intent = new Intent(Meeting.this,EcConferenceNumber.class);
intent.putExtra("strings", number);
startActivity(intent);
finish();
}
}
});
}
public void addComma(StringBuffer updatedString,String value){
if(updatedString.length() >0 && updatedString != null ){
updatedString.append(",");
}
updatedString.append(value);
}
public static void readCalendar(Context context) {
ContentResolver contentResolver = context.getContentResolver();
Calendar c_start = Calendar.getInstance();
c_start.set(2014,2,4,0,0); //Note that months start from 0 (January)
Calendar c_end = Calendar.getInstance();
c_end.set(2013,2,11,0,0); //Note that months start from 0 (January)
String selection = "((dtstart >= "+c_start.getTimeInMillis()+") AND (dtend <= "+c_end.getTimeInMillis()+"))";
String[] selectionArgs = new String[] {startString, endString};
cursor = contentResolver.query(Uri.parse("content://com.android.calendar/events"),
(new String[] { "calendar_id", "title", "description", "dtstart", "dtend", "eventLocation"})
,null,selectionArgs,selection);
gCalendar = new ArrayList<GoogleCalendar>();
try {
System.out.println("Count=" + cursor.getCount());
if (cursor.getCount() > 0) {
System.out.println("the control is just inside of the cursor.count loop");
while (cursor.moveToNext()) {
GoogleCalendar googleCalendar = new GoogleCalendar();
gCalendar.add(googleCalendar);
int calendar_id = cursor.getInt(0);
googleCalendar.setCalendar_id(calendar_id);
String title = cursor.getString(1);
googleCalendar.setTitle(title);
String description = cursor.getString(2);
googleCalendar.setDescription(description);
String dtstart = cursor.getString(3);
googleCalendar.setDtstart(dtstart);
String dtend = cursor.getString(4);
googleCalendar.setDtend(dtend);
String eventlocation = cursor.getString(5);
googleCalendar.setEventlocation(eventlocation);
}
}
} catch (AssertionError ex) {
ex.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
// inner class for setting the home screen value to the list view
class MeetingListViewAdapter extends BaseAdapter {
private List<GoogleCalendar> calendars = null;
LayoutInflater inflater = null;
public MeetingListViewAdapter(Activity activity, ConferenceAdapter adapter, List<GoogleCalendar> gCalendar) {
this.calendars = gCalendar;
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return calendars.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.calendar_events, null);
TextView titleNameTV = (TextView) vi.findViewById(R.id.titlemeeting);
TextView timeTV = (TextView) vi.findViewById(R.id.profileStepCountTV);
TextView whereTv=(TextView) vi.findViewById(R.id.wheretextView);
TextView descriptionTV = (TextView) vi.findViewById(R.id.descriptionmeeting);
GoogleCalendar calendar = calendars.get(position);
titleNameTV.setText(calendar.getTitle());
descriptionTV.setText(calendar.getDescription());
whereTv.setText(calendar.getEventlocation());
return vi;
}
}
Any answer will be helpfull for me to proceed.

Replace this code :
ContentResolver contentResolver = context.getContentResolver();
Calendar c_start = Calendar.getInstance();
c_start.set(2014,2,4,0,0); //Note that months start from 0 (January)
Calendar c_end = Calendar.getInstance();
c_end.set(2013,2,11,0,0); //Note that months start from 0 (January)
String selection = "((dtstart >= "+c_start.getTimeInMillis()+") AND (dtend <= "+c_end.getTimeInMillis()+"))";
String[] selectionArgs = new String[] {startString, endString};
cursor = contentResolver.query(Uri.parse("content://com.android.calendar/events"),
(new String[] { "calendar_id", "title", "description", "dtstart", "dtend", "eventLocation"})
,null,selectionArgs,selection);
With this:
Uri l_eventUri;
Calendar calendar = Calendar.getInstance();
if (Build.VERSION.SDK_INT >= 8) {
l_eventUri = Uri.parse("content://com.android.calendar/events");
} else {
l_eventUri = Uri.parse("content://calendar/events");
}
ContentResolver contentResolver = context.getContentResolver();
String dtstart = "dtstart";
String dtend = "dtend";
String[] l_projection = new String[] { "title", "dtstart", "dtend" };
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yy");
// Date dateCC = formatter.parse("04/27/2013");
Date dateCC = formatter.parse("11/13/2013");
calendar.setTime(dateCC);
long after = calendar.getTimeInMillis();
SimpleDateFormat formatterr = new SimpleDateFormat("MM/dd/yy hh:mm:ss");
Calendar endOfDay = Calendar.getInstance();
Date dateCCC = formatterr.parse("17/13/2013 23:59:59");
// Date dateCCC = formatterr.parse(startDate + " 23:59:59");
endOfDay.setTime(dateCCC);
cursor= contentResolver.query(l_eventUri, new String[] { "title",
"dtstart", "dtend" }, "(" + dtstart + ">" + after + " and "
+ dtend + "<" + endOfDay.getTimeInMillis() + ")", null,
"dtstart ASC");

Related

Calendar event color doesn't sync between my android app and google web calendar

After my android app sync event to google calendar and i see color google android calendar but doesn't change google web calendar event color. What i to do wrong?
Name is accountName.
protected void fetchCalendarForUser(String name) {
Cursor cur = null;
ContentResolver cr = getContentResolver();
Uri uri = CalendarContract.Calendars.CONTENT_URI;
String selection = "((" + CalendarContract.Calendars.ACCOUNT_NAME + " = ?) AND ("
+ CalendarContract.Calendars.ACCOUNT_TYPE + " = ?) AND ("
+ CalendarContract.Calendars.OWNER_ACCOUNT + " = ?))";
String[] selectionArgs = new String[] {name, "com.google", name};
cur = cr.query(uri, EVENT_PROJECTION, selection, selectionArgs, null);
cur.moveToNext();
long calID = 0;
String displayName = null;
String accountName = null;
String ownerName = null;
// Get the field values
calID = cur.getLong(PROJECTION_ID_INDEX);
displayName = cur.getString(PROJECTION_DISPLAY_NAME_INDEX);
accountName = cur.getString(PROJECTION_ACCOUNT_NAME_INDEX);
ownerName = cur.getString(PROJECTION_OWNER_ACCOUNT_INDEX);
int i = 0;
List<Date> laststart = new ArrayList<Date>();
List<Date> lastend = new ArrayList<Date>();
boolean equal=false;
for (Map.Entry<String, ArrayList<CalendarEntry>> item : calendarEntriesByDay.entrySet()) {
for (CalendarEntry entry : item.getValue()) {
for(int j=0;j<laststart.size();j++)
{
if(laststart.get(j) == entry.getStart()){
if(lastend.get(j) == entry.getEnd()){
equal=true;
}
}
}
if(equal==false) {
createEventOnCalendar(calID, entry);
i++;
}
else
{
equal=false;
}
laststart.add(entry.getStart());
lastend.add(entry.getEnd());
}
}
if (i > 0) {
Crouton.makeText(this, getResources().getString(eu.rerisoft.servicebus.R.string.google_calendar_add_success, displayName, String.valueOf(i)), Style.ALERT).show();
} else {
Crouton.makeText(this, eu.rerisoft.servicebus.R.string.google_calendar_add_error, Style.ALERT).show();
}
}
protected long createEventOnCalendar(long calID, CalendarEntry event) {
String colorString = getResources().getString(event.getColorRes());
int eventColor = Color.parseColor(colorString);
ContentResolver cr = getContentResolver();
ContentValues values = new ContentValues();
values.put(CalendarContract.Events.DTSTART, event.getStart().getTime());
values.put(CalendarContract.Events.DTEND, event.getEnd().getTime());
values.put(CalendarContract.Events.TITLE, event.getTitle());
values.put(CalendarContract.Events.EVENT_COLOR, eventColor);
values.put(CalendarContract.Events.DESCRIPTION, event.getDescription());
values.put(CalendarContract.Events.CALENDAR_ID, calID);
values.put(CalendarContract.Events.EVENT_TIMEZONE, TimeZone.getTimeZone("UTC").getDisplayName());
Uri uri = cr.insert(CalendarContract.Events.CONTENT_URI, values);
long eventID = Long.parseLong(uri.getLastPathSegment());
return eventID;
}
Sorry for bad english.
I have done same thing before 3 months:
String appointmentColorCode = "Color_which_Is_Currently_Getting_From_Calendar";
int mColorCode = 0;
mColorCode = (0xff000000 + Integer.parseInt(appointmentColorCode));
You have to give Color_which_Is_Currently_Getting_From_Calendar as you are getting from calendar.
mColorCode will be your final Color code.'
Done

How to refresh foreground Activity with incoming SMS?

I am developing SMS application. I have declared receiver in manifest as follows :
<receiver android:name="com.android.discrete.main.IncomingSMS" >
<intent-filter android:priority="1000" >
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
class for broadcastReceiver is as follows :
public class IncomingSMS extends BroadcastReceiver {
Context context;
DbManager DBmanager;
private long timestamp;
private String number;
static String body = "";
String msg="";
Cursor cursor;
String display_name;
String flag;
ChatActivity obj_chat;
#Override
public void onReceive(Context context, Intent intent) {
try {
final Bundle bundle = intent.getExtras();
if (bundle != null) {
//—retrieve the SMS message received—
Object messages[] = (Object[]) bundle.get("pdus");
SmsMessage smsMessage[] = new SmsMessage[messages.length];
for (int n = 0; n < messages.length; n++) {
smsMessage[n] = SmsMessage.createFromPdu((byte[]) messages[n]);
timestamp = smsMessage[n].getTimestampMillis();
number = smsMessage[n].getOriginatingAddress();
body += smsMessage[n].getDisplayMessageBody();
display_name = Util.getContactName(context, number);
DBmanager = new DbManager(context);
cursor = DBmanager.Return_All_Contacts();
String [] contactArr = showcontactsInfo(cursor);
Toast.makeText(context, contactArr[0]+"", 3000).show();
if(contactArr.length==0)
{}
else{
for(int i= 0;i<=contactArr.length;i++)
{
abortBroadcast();
}
blockMessage(context);
}
}
}
}
catch (Exception e) {
Log.e("SmsReceiver", "Exception smsReceiver" +e);
}
} // end for loop
// bundle is null
private String[] showcontactsInfo(Cursor cursor) {
String[] contact = new String [cursor.getCount()];
int i= 0;
while(cursor.moveToNext()){
contact[i] = cursor.getString(1);
i++;
}
return contact;
}
private void blockMessage(Context context) {
// instantiate DbMNager object to insert sms in database
//formating receiving time:
//SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-hh.mm.ss");
SimpleDateFormat formatter = new SimpleDateFormat("EEEE, MMMM d HH:mm:ss a");
String formatedTime = formatter.format(timestamp);
flag = "0";
DBmanager= new DbManager(context);
DBmanager.open();
DBmanager.Insert_sms_data(formatedTime ,display_name,body,flag);
DBmanager.close();
msg+= "SMS from " + number + " \n";
msg += body + " \n";
msg += formatedTime + " \n";
msg += flag + " \n";
Log.i("SmsReceiver", "senderNum: "+ display_name + "; message: " + body);
Toast.makeText(context,msg, Toast.LENGTH_LONG).show();
//Toast.makeText(context, "New message received in Discrete", Toast.LENGTH_LONG).show();
}
}
This works fine as i can receive SMS and save it in SQLite database.
Now i have another activity having ListView in which i want to update as soon as new SMS is received and activity is in foreground. Code is as follows:
public class ChatActivity extends Activity {
Context context;
DbManager DBmanager;
private long timestamp;
private String number;
static String body = "";
//String msg="";
Cursor cursor;
String display_name;
//String flag;
static MyListAdapter adapter;
static ArrayList<String> item_id;
static ArrayList<String> item_phone_num;
static ArrayList<String> item_msg_body;
static ArrayList<String> item_time;
static ArrayList<String> item_flag;
static ArrayList<String> items;
private Button btn_send;
DbManager manager;
Cursor Cursor,cursor_new;
//ViewHolder holder12;
String contact_for_chat;
String contact_no;
String message_body = "";
Calendar c;
SimpleDateFormat sdf;
String time;
EditText et_chat;
String flag;
String msg = "";
ListView lv_chat;
int position;
String[] from = new String[]{"Message_body","Time"};
int[] toIDs = new int[]{R.id.msg_body,R.id.time};
BroadcastReceiver IncomingSMS = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
updateList();
}};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
Bundle bundle = getIntent().getExtras();
contact_for_chat = bundle.getString("contact_name");
contact_for_chat = contact_for_chat.replace(" ", "");
contact_no = Util.getContactNumber(contact_for_chat, ChatActivity.this);
Toast.makeText(getApplicationContext(), contact_no, Toast.LENGTH_LONG).show();
manager = new DbManager(this);
Cursor = manager.Return_SMS(contact_for_chat);
c = Calendar.getInstance();
sdf = new SimpleDateFormat("dd:MMMM:yyyy HH:mm:ss a");
time = sdf.format(c.getTime());
item_id = new ArrayList<String>(Cursor.getCount());
item_phone_num = new ArrayList<String>(Cursor.getCount());
item_msg_body = new ArrayList<String>(Cursor.getCount());
item_time = new ArrayList<String>(Cursor.getCount());
item_flag = new ArrayList<String>(Cursor.getCount());
findViews();
showList();
//setActionBar();
btn_send.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
SendSMS();
showList();
//updateList() ;
}
});
lv_chat.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position,
long arg3) {
Toast.makeText(getApplicationContext(), ""+position, Toast.LENGTH_LONG).show();
int itemId = Integer.valueOf(String.valueOf(position));
Cursor.moveToPosition(itemId);
int messageId = Cursor.getInt(0);
deleteMessage(messageId);
}});
}
private void showList() {
showEvents(Cursor);
adapter = new MyListAdapter(this,R.layout.activity_chat, Cursor, from,
toIDs);
lv_chat.setAdapter(adapter);
//updateList() ;
}
private void findViews() {
et_chat = (EditText)findViewById(R.id.et_chat);
btn_send = (Button)findViewById(R.id.button1);
lv_chat = (ListView)findViewById(R.id.list);
lv_chat.setDivider(this.getResources().getDrawable(android.R.color.transparent));
}
protected void SendSMS() {
SmsManager sms_manager = SmsManager.getDefault();
message_body = et_chat.getText().toString();
ArrayList<String> parts = sms_manager.divideMessage(message_body);
sms_manager.sendMultipartTextMessage(contact_no, null, parts, null, null);
flag = "1";
manager.Insert_sms_data(time, contact_for_chat, message_body,flag);
if(message_body.length()>0)
{
et_chat.setText("");
}
updateList() ;
}
private void showEvents(Cursor cursor) {
int i=0;
while (cursor.moveToNext()) {
item_id.add(i+"");
item_time.add(cursor.getString(1));
item_msg_body.add(cursor.getString(3));
item_phone_num.add(cursor.getString(2));
item_flag.add(cursor.getString(4));
i++;
}
}
public class MyListAdapter extends SimpleCursorAdapter {
Cursor myCursor;
Context myContext;
public MyListAdapter(Context context, int layout,
Cursor c, String[] from, int[] to) {
super(context, layout, c, from, to);
myCursor = c;
myContext = context;
}
public int getCount() {
return item_msg_body.size();
}
public Object getItem(int position) {
return item_msg_body.get(position);
}
public long getItemId(int position) {
return item_msg_body.get(position).hashCode();
}
public View getView(final int position, View arg1, ViewGroup arg2) {
View v = arg1;
ViewHolder holder = null;
if (v == null) {
LayoutInflater layoutinf = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = layoutinf.inflate(R.layout.row_chat, null);
holder = new ViewHolder();
// holder.tv_contact = (TextView) v.findViewById(R.id.phone_num);
holder.tv_sms_body = (TextView) v.findViewById(R.id.msg_body);
holder.tv_time = (TextView) v.findViewById(R.id.time);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
if(item_flag.get(position).equals("1"))
{
RelativeLayout.LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT,RelativeLayout.TRUE);
RelativeLayout.LayoutParams dateparams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
dateparams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
dateparams.addRule(RelativeLayout.BELOW, R.id.msg_body);
holder.tv_sms_body.setBackgroundResource(R.drawable.bubble_green);
holder.tv_sms_body.setLayoutParams(params);
holder.tv_time.setLayoutParams(dateparams);
}
else if(item_flag.get(position).equals("0"))
{
holder.tv_sms_body.setBackgroundResource(R.drawable.bubble_yellow);
}
//holder.tv_contact.setText("" + item_phone_num.get(position));
holder.tv_sms_body.setText(item_msg_body.get(position));
holder.tv_time.setText(item_time.get(position));
return v;
}
}
public class ViewHolder {
private TextView tv_contact;
private TextView tv_sms_body;
private TextView tv_time;
}
public void updateList()
{
item_id.clear();
item_time.clear();
item_msg_body.clear();
item_phone_num.clear();
item_flag.clear();
Cursor = manager.Return_SMS(contact_for_chat);
showEvents(Cursor);
adapter = new MyListAdapter(this,R.layout.activity_chat, Cursor, from,
toIDs);
lv_chat.setAdapter(adapter);
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(IncomingSMS);
}
#Override
protected void onResume() {
//registerReceiver(IncomingSMS, null);
IntentFilter filter = new IntentFilter();
filter.addAction("android.provider.Telephony.SMS_RECEIVED");
registerReceiver(IncomingSMS, filter);
updateList();
super.onResume();
}
Problem is that when i receive SMS then ListView is updated automatically but result is not as expected.When SMS is received then it combines previous SMS with new one i.e see in this image fisrt SMS was "Hi" second SMS was "How are you" but its combines both SMS as "Hi How are you". What is the reason ? How it can be fixed ????
Any help will be appreciated .
I would suggest you to use Cursor Loader here are some tutorial :-
http://www.androiddesignpatterns.com/2012/07/understanding-loadermanager.html
http://www.vogella.com/tutorials/AndroidSQLite/article.html
so your app design would be like this :-
(new sms) ----> (broadcast reciever inserts into db) -----> (cursor loader will refresh your foreground activity)

Want to get only current week events from calendar in android?

I am new to android and creating a ListView that displays a calendar events.By,using the below code it is getting all the events from calendar.But i want only current week events to be displayed in the list view ,Any ideas or answers will be really helpfull for me to proceed in android.
public class Meeting extends Activity {
public ConferenceAdapter adapter;
ListView meetingListView;
static Cursor cursor;
private String description = null;
private String where = null;
public String[] number;
static List<GoogleCalendar> gCalendar = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ec_meeting);
adapter = new ConferenceAdapter(this);
readCalendar(this);
meetingListView = (ListView) findViewById(R.id.meetinglistView);
meetingListView.setAdapter(new MeetingListViewAdapter(Meeting.this, adapter, gCalendar));
meetingListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int arg2, long arg3) {
TextView descriptionId1 = ((TextView) view.findViewById(R.id.descriptionmeeting));
TextView where=((TextView) view.findViewById(R.id.wheretextView));
TextView tittle = ((TextView) view.findViewById(R.id.titlemeeting));
Meeting.this.where=where.getText().toString();
description = descriptionId1.getText().toString();
StringBuffer numbers =new StringBuffer();
String a=Meeting.this.where.replaceAll("-","").replaceAll(" ", "").replaceAll("\\(","").replaceAll("\\)","")+description.replaceAll("-","").replaceAll(" ", "").replaceAll("\\(","").replaceAll("\\)","");
if(a.isEmpty()){
Toast.makeText(getApplicationContext(),"Sorry no conference numbers found", Toast.LENGTH_LONG).show();
}else{
Pattern p = Pattern.compile("[0-9]+[0-9]");
Matcher m = p.matcher(a);
while (m.find()) {
Meeting.this.addComma(numbers,m.group().toString());
}
number = numbers.toString().split(",");
Intent intent = new Intent(Meeting.this,EcConferenceNumber.class);
intent.putExtra("strings", number);
startActivity(intent);
finish();
}
}
});
}
public void addComma(StringBuffer updatedString,String value){
if(updatedString.length() >0 && updatedString != null ){
updatedString.append(",");
}
updatedString.append(value);
}
public static void readCalendar(Context context) {
ConferenceAdapter cAdapter = null;
ContentResolver contentResolver = context.getContentResolver();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
String currentDateandTime = sdf.format(new Date());
String presentDate="dtstart.after("+currentDateandTime+")";
cursor = contentResolver.query(Uri.parse("content://com.android.calendar/events"),
(new String[] { "calendar_id", "title", "description", "dtstart", "dtend", "eventLocation"})
,null, null,null);
HashSet<String> calendarIds = new HashSet<String>();
gCalendar = new ArrayList<GoogleCalendar>();
try {
System.out.println("Count=" + cursor.getCount());
if (cursor.getCount() > 0) {
System.out.println("the control is just inside of the cursor.count loop");
while (cursor.moveToNext()) {
GoogleCalendar googleCalendar = new GoogleCalendar();
gCalendar.add(googleCalendar);
int calendar_id = cursor.getInt(0);
googleCalendar.setCalendar_id(calendar_id);
String title = cursor.getString(1);
googleCalendar.setTitle(title);
String description = cursor.getString(2);
googleCalendar.setDescription(description);
String dtstart = cursor.getString(3);
googleCalendar.setDtstart(dtstart);
String dtend = cursor.getString(4);
googleCalendar.setDtend(dtend);
String eventlocation = cursor.getString(5);
googleCalendar.setEventlocation(eventlocation);
}
}
} catch (AssertionError ex) {
ex.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
// inner class for setting the home screen value to the list view
class MeetingListViewAdapter extends BaseAdapter {
private List<GoogleCalendar> calendars = null;
LayoutInflater inflater = null;
public MeetingListViewAdapter(Activity activity, ConferenceAdapter adapter, List<GoogleCalendar> gCalendar) {
this.calendars = gCalendar;
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return calendars.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.calendar_events, null);
TextView titleNameTV = (TextView) vi.findViewById(R.id.titlemeeting);
TextView timeTV = (TextView) vi.findViewById(R.id.profileStepCountTV);
TextView whereTv=(TextView) vi.findViewById(R.id.wheretextView);
TextView descriptionTV = (TextView) vi.findViewById(R.id.descriptionmeeting);
GoogleCalendar calendar = calendars.get(position);
titleNameTV.setText(calendar.getTitle());
descriptionTV.setText(calendar.getDescription());
whereTv.setText(calendar.getEventlocation());
return vi;
}
}
I am having a doubt that,I have to insert all my calendar events in database and get the current week events by using a query or it can be done without inserting calendar events into database.As a beginner any idea will be usefull for me.
I have already answered for that SO i think it might work just pass two dates.
Code:
Calendar calendar = Calendar.getInstance();
if (Build.VERSION.SDK_INT >= 8) {
l_eventUri = Uri.parse("content://com.android.calendar/events");
} else {
l_eventUri = Uri.parse("content://calendar/events");
}
String dtstart = "dtstart";
String dtend = "dtend";
String[] l_projection = new String[] { "title", "dtstart", "dtend" };
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yy");
//StartDate is today 10/28/2013
Date dateCC = formatter.parse("10/28/2013");
calendar.setTime(dateCC);
long after = calendar.getTimeInMillis();
SimpleDateFormat formatterr = new SimpleDateFormat("MM/dd/yy hh:mm:ss");
Calendar endOfDay = Calendar.getInstance();
Date dateCCC = formatterr.parse("11/04/2013 23:59:59");
endOfDay.setTime(dateCCC);
Cursor eventCursorr = cr.query(l_eventUri, new String[] { "title",
"dtstart", "dtend" }, "(" + dtstart + ">" + after + " and "
+ dtend + "<" + endOfDay.getTimeInMillis() + ")", null,
"dtstart ASC");

Android Calendar Events

I am just making an operation with Calendar Content Provider, now I am failing at the point to display events for the particular date.
I know the Events URI for the < 2.1 version and 2.2 version, as below:
eventsUri = Uri.parse("content://calendar/events"); // < Android 2.1 version
eventsUri = Uri.parse("content://com.android.calendar/events"); // For Android Froyo 2.2 and later version
My doubts are:
How do I Fetch all the events?
How do I fetch events for the particular date?
So please, somebody with knowledge about the Calendar please help me and share your knowledge regarding this.
Thanx
These examples are for <= 2.1 version;
first; find out which calendars exist
Cursor cursor = cr.query(Uri.parse("content://calendar/calendars"), new String[]{ "_id", "displayname" }, null, null, null);
cursor.moveToFirst();
String[] CalNames = new String[cursor.getCount()];
int[] CalIds = new int[cursor.getCount()];
for (int i = 0; i < CalNames.length; i++) {
CalIds[i] = cursor.getInt(0);
CalNames[i] = cursor.getString(1);
cursor.moveToNext();
}
cursor.close();
Fetching all events, and particular event is done by specifying range
ContentResolver contentResolver = getContentResolver();
Uri.Builder builder = Uri.parse(getCalendarUriBase() + "/instances/when").buildUpon();
long now = new Date().getTime();
ContentUris.appendId(builder, now - DateUtils.MILLIS_PER_DAY*10000);
ContentUris.appendId(builder, now + DateUtils.MILLIS_PER_DAY * 10000);
and then let's say you wish to log events ID from calendar with ID = 1
Cursor eventCursor = contentResolver.query(builder.build(),
new String[] { "event_id"}, "Calendars._id=" + 1,
null, "startDay ASC, startMinute ASC");
// For a full list of available columns see http://tinyurl.com/yfbg76w
while (eventCursor.moveToNext()) {
String uid2 = eventCursor.getString(0);
Log.v("eventID : ", uid2);
}
// Here's a way for you to get all the Calendar events list
public static void readCalendarEvent(Context context) {
ContentResolver contentResolver = context.getContentResolver();
cursor = contentResolver.query(Uri.parse("content://com.android.calendar/events"), (new String[] { "_id", "title", "organizer", "dtstart", "dtend"}), null, null, null);
List<GoogleCalendar> gCalendar = new ArrayList<GoogleCalendar>();
try {
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
GoogleCalendar googleCalendar = new GoogleCalendar();
int event_ID = cursor.getInt(0);
googleCalendar.setEvent_id(event_ID);
String title = cursor.getString(1);
googleCalendar.setTitle(title);
String mOrganizer = cursor.getString(2);
googleCalendar.setOrganizer(mOrganizer);
String dtStart = cursor.getString(3);
googleCalendar.setDtstart(dtStart);
String dtEnd = cursor.getString(4);
googleCalendar.setDtend(dtEnd);
gCalendar.add(googleCalendar);
Log.d("CaledarM",googleCalendar.getTitle()+" name = "+googleCalendar.getOrganizer()+" dateStart = "+googleCalendar.getDtstart()+" Size = " + gCalendar.size());
}
}
} catch (AssertionError ex) {
ex.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
// class GoogleCalendar()
public class GoogleCalendar {
private int event_id;
private String title,
organizer,
dtstart,
dtend;
public GoogleCalendar()
{
}
public int getEvent_id() {
return event_id;
}
public void setEvent_id(int calendar_id) {
event_id = calendar_id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getOrganizer() {
return organizer;
}
public void setOrganizer(String description) {
this.organizer = description;
}
public String getDtstart() {
return dtstart;
}
public void setDtstart(String dtstart1) {
this.dtstart = dtstart1;
}
public String getDtend() {
return dtend;
}
public void setDtend(String dtend1) {
this.dtend = dtend1;
}
}
Use this code to get daily events,
public static void readCalendarEvent(Context context) throws ParseException {
ContentResolver contentResolver = context.getContentResolver();
Calendar calendar = Calendar.getInstance();
String dtstart = "dtstart";
String dtend = "dtend";
SimpleDateFormat displayFormatter = new SimpleDateFormat("MMMM dd, yyyy (EEEE)");
stime=displayFormatter.format(calendar.getTime());
SimpleDateFormat startFormatter = new SimpleDateFormat("MM/dd/yy");
String dateString = startFormatter.format(calendar.getTime());
long after = calendar.getTimeInMillis();
SimpleDateFormat formatterr = new SimpleDateFormat("hh:mm:ss MM/dd/yy");
Calendar endOfDay = Calendar.getInstance();
Date dateCCC = formatterr.parse("23:59:59 " + dateString);
endOfDay.setTime(dateCCC);
cursor = contentResolver.query(Uri.parse("content://com.android.calendar/events"), (new String[] { "calendar_id", "title", "description", "dtstart", "dtend","eventTimezone", "eventLocation" }), "(" + dtstart + ">" + after + " and " + dtend + "<" + endOfDay.getTimeInMillis() + ")", null, "dtstart ASC");
/*String[] COLS={"calendar_id", "title", "description", "dtstart", "dtend","eventTimezone", "eventLocation"};
cursor = contentResolver.query(
CalendarContract.Events.CONTENT_URI, COLS,null, null, null);*/
gCalendar = new ArrayList<GoogleCalendar>();
try {
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
GoogleCalendar googleCalendar = new GoogleCalendar();
gCalendar.add(googleCalendar);
int calendar_id = cursor.getInt(0);
googleCalendar.setCalendar_id(calendar_id);
String title = cursor.getString(1);
googleCalendar.setTitle(title);
String description = cursor.getString(2);
googleCalendar.setDescription(description);
String dtstart1 = cursor.getString(3);
dt=convertDate(dtstart1,"hh:mm:ss");
googleCalendar.setDtstart(dt);
String dtend1 = cursor.getString(4);
googleCalendar.setDtend(dtend1);
String eventTimeZone=cursor.getString(5);
googleCalendar.setEventTimeZone(eventTimeZone);
String eventlocation = cursor.getString(6);
googleCalendar.setEventlocation(eventlocation);
}
}
} catch (AssertionError ex) {
ex.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}

Android ContentObserver onChange() only returns false

I'm trying to implement a ContentObserver for CallLog.Calls content provider. I mean, If I make a call, or receive a call, etc, the observer must notify me that the CallLog.Calls content provider has changed. But the onchange method only returns false, even with the observers registered, and notified. Maybe I'm doing something wrong.
This is my code. It's an Activity.
package com.psyhclo;
public class RatedCalls extends ListActivity {
private static final String LOG_TAG = "RatedCallsObserver";
private Handler handler = new Handler();
private RatedCallsContentObserver callsObserver = null;
private SQLiteDatabase db;
private CallDataHelper dh = null;
StringBuilder sb = new StringBuilder();
OpenHelper openHelper = new OpenHelper(RatedCalls.this);
class RatedCallsContentObserver extends ContentObserver {
public RatedCallsContentObserver(Handler h) {
super(h);
}
public void onChange(boolean selfChange) {
Log.d(LOG_TAG, "RatedCallsContentObserver.onChange( " + selfChange
+ ")");
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
registerContentObservers();
fillList();
}
#Override
public void onStart() {
super.onStart();
registerContentObservers();
}
#Override
public void onStop() {
super.onStop();
unregisterContentObservers();
}
private void fillList() {
Cursor cursor = getContentResolver().query(
android.provider.CallLog.Calls.CONTENT_URI, null, null, null,
android.provider.CallLog.Calls.DATE + " DESC ");
cursor.setNotificationUri(getBaseContext().getContentResolver(),
android.provider.CallLog.Calls.CONTENT_URI);
dh = new CallDataHelper(this);
db = openHelper.getWritableDatabase();
startManagingCursor(cursor);
int numberColumnId = cursor
.getColumnIndex(android.provider.CallLog.Calls.NUMBER);
int durationId = cursor
.getColumnIndex(android.provider.CallLog.Calls.DURATION);
int contactNameId = cursor
.getColumnIndex(android.provider.CallLog.Calls.CACHED_NAME);
int dateId = cursor.getColumnIndex(android.provider.CallLog.Calls.DATE);
int numTypeId = cursor
.getColumnIndex(android.provider.CallLog.Calls.CACHED_NUMBER_TYPE);
// int contactIdColumnId =
// cursor.getColumnIndex(android.provider.ContactsContract.RawContacts.CONTACT_ID);
Date dt = new Date();
int hours = dt.getHours();
int minutes = dt.getMinutes();
int seconds = dt.getSeconds();
String currTime = hours + ":" + minutes + ":" + seconds;
ArrayList<String> callList = new ArrayList<String>();
if (cursor.moveToFirst()) {
do {
String contactNumber = cursor.getString(numberColumnId);
String contactName = cursor.getString(contactNameId);
String duration = cursor.getString(durationId);
String callDate = DateFormat.getDateInstance().format(dateId);
String numType = cursor.getString(numTypeId);
ContentValues values = new ContentValues();
values.put("contact_id", 1);
values.put("contact_name", contactName);
values.put("number_type", numType);
values.put("contact_number", contactNumber);
values.put("duration", duration);
values.put("date", callDate);
values.put("current_time", currTime);
values.put("cont", 1);
getBaseContext().getContentResolver().notifyChange(
android.provider.CallLog.Calls.CONTENT_URI, null);
this.db.insert(CallDataHelper.TABLE_NAME, null, values);
Toast.makeText(getBaseContext(), "Inserted!", Toast.LENGTH_LONG);
callList.add("Contact Number: " + contactNumber
+ "\nContact Name: " + contactName + "\nDuration: "
+ duration + "\nDate: " + callDate);
} while (cursor.moveToNext());
}
setListAdapter(new ArrayAdapter<String>(this, R.layout.listitem,
callList));
ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getApplicationContext(),
((TextView) view).getText(), Toast.LENGTH_SHORT).show();
}
});
}
private void registerContentObservers() {
ContentResolver cr = getContentResolver();
callsObserver = new RatedCallsContentObserver(handler);
cr.registerContentObserver(android.provider.CallLog.Calls.CONTENT_URI,
true, callsObserver);
}
private void unregisterContentObservers() {
ContentResolver cr = getContentResolver();
if (callsObserver != null) { // just paranoia
cr.unregisterContentObserver(callsObserver);
callsObserver = null;
}
}
}
This is the answer for this question.
Android onChange() method only returns false

Categories

Resources