Read events from android calendar - android

I have a little problem with my code .I use Android Studio .
I try to make an application to the phone's calendar events displaying time . I don't have any errors but when I tried to run it to my phone
Caused by:
java.lang.NullPointerException
at net.jimblackler.readcalendar.Example.readCalendar(Example.java:29)
at net.jimblackler.readcalendar.MainActivity.onCreate(MainActivity.java:14)
Here is my cod :
Java Class:
import java.util.Date;
import java.util.HashSet;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.text.format.DateUtils;
public class Example {
public static void readCalendar(Context context) {
ContentResolver contentResolver = context.getContentResolver();
// Fetch a list of all calendars synced with the device, their display names and whether the
// user has them selected for display.
final Cursor cursor = contentResolver.query(Uri.parse("content://calendar/calendars"),
(new String[] { "_id", "displayName", "selected" }), null, null, null);
HashSet<String> calendarIds = new HashSet<String>();
while (cursor.moveToNext()) {
final String _id = cursor.getString(0);
final String displayName = cursor.getString(1);
final Boolean selected = !cursor.getString(2).equals("0");
System.out.println("Id: " + _id + " Display Name: " + displayName + " Selected: " + selected);
calendarIds.add(_id);
}
// For each calendar, display all the events from the previous week to the end of next week.
for (String id : calendarIds) {
Uri.Builder builder = Uri.parse("content://calendar/instances/when").buildUpon();
long now = new Date().getTime();
ContentUris.appendId(builder, now - DateUtils.WEEK_IN_MILLIS);
ContentUris.appendId(builder, now + DateUtils.WEEK_IN_MILLIS);
Cursor eventCursor = contentResolver.query(builder.build(),
new String[] { "title", "begin", "end", "allDay"}, "Calendars._id=" + id,
null, "startDay ASC, startMinute ASC");
while (eventCursor.moveToNext()) {
final String title = eventCursor.getString(0);
final Date begin = new Date(eventCursor.getLong(1));
final Date end = new Date(eventCursor.getLong(2));
final Boolean allDay = !eventCursor.getString(3).equals("0");
System.out.println("Title: " + title + " Begin: " + begin + " End: " + end +
" All Day: " + allDay);
}
}
}
}
MainActivity:
package net.jimblackler.readcalendar;
import android.app.Activity;
import android.os.Bundle;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Example.readCalendar(this);
}
}

First, please check the uri address . For example 'content://calendar/calendars' , it's not used over Android 2.1.
Before Android 14:
calanderURL = "content://calendar/calendars";
calanderEventURL = "content://calendar/events";
calanderRemiderURL= "content://calendar/reminders";
After:
calanderURL = "content://com.android.calendar/calendars";
calanderEventURL = "content://com.android.calendar/events";
calanderRemiderURL = "content://com.android.calendar/reminders";
However, you'd better use like this:
private Uri calendarsUri = Calendars.CONTENT_URI;
private Uri eventsUri = Events.CONTENT_URI;
private Uri remindersUri = Reminders.CONTENT_URI;
private Uri attendeesUri = Attendees.CONTENT_URI;
Second , please check the table column name . You can print the following columns and have a look .
/** Calendars table columns */
public static final String[] CALENDARS_COLUMNS = new String[] {
Calendars._ID, // 0
Calendars.ACCOUNT_NAME, // 1
Calendars.CALENDAR_DISPLAY_NAME, // 2
Calendars.OWNER_ACCOUNT // 3
};
/** Events table columns */
public static final String[] EVENTS_COLUMNS = new String[] {
Events._ID,
Events.CALENDAR_ID,
Events.TITLE,
Events.DESCRIPTION,
Events.EVENT_LOCATION,
Events.DTSTART,
Events.DTEND,
Events.EVENT_TIMEZONE,
Events.HAS_ALARM,
Events.ALL_DAY,
Events.AVAILABILITY,
Events.ACCESS_LEVEL,
Events.STATUS,
};
/** Reminders table columns */
public static final String[] REMINDERS_COLUMNS = new String[] {
Reminders._ID,
Reminders.EVENT_ID,
Reminders.MINUTES,
Reminders.METHOD,
};
/** Reminders table columns */
public static final String[] ATTENDEES_COLUMNS = new String[] {
Attendees._ID,
Attendees.ATTENDEE_NAME,
Attendees.ATTENDEE_EMAIL,
Attendees.ATTENDEE_STATUS
};
Third, you code manner is very bad .You should declare these above parameters as 'static final' ones .

Related

how to get the data from the android calendar when we add events to it?

I am creating an event to a google calendar from inside of my application and as i press the SAVE button it will added to a calendar. what i need is want to fetch that data and sent it to server for future use. Is it possible to get that data??
Thanks
Create a class like this for the sole purpose of reading events from ur device calendar :
place an if condition for ur desired events inside the do while loop and store them in an array list and u can send this array to the server by making an http call :
import java.util.Date;
import java.util.HashSet;
import java.util.regex.Pattern;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.text.format.DateUtils;
public class ReadCalendar
{
static Cursor cursor;
public static void readCalendar(Context context) {
ContentResolver contentResolver = context.getContentResolver();
// Fetch a list of all calendars synced with the device, their display names and whether the
cursor = contentResolver.query(Uri.parse("content://com.android.calendar/calendars"),
(new String[] { "_id", "displayName", "selected"}), null, null, null);
HashSet<String> calendarIds = new HashSet<String>();
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()) {
String _id = cursor.getString(0);
String displayName = cursor.getString(1);
Boolean selected = !cursor.getString(2).equals("0");
System.out.println("Id: " + _id + " Display Name: " + displayName + " Selected: " + selected);
calendarIds.add(_id);
}
}
}
catch(AssertionError ex)
{
ex.printStackTrace();
}
catch(Exception e)
{
e.printStackTrace();
}
// For each calendar, display all the events from the previous week to the end of next week.
for (String id : calendarIds) {
Uri.Builder builder = Uri.parse("content://com.android.calendar/instances/when").buildUpon();
//Uri.Builder builder = Uri.parse("content://com.android.calendar/calendars").buildUpon();
long now = new Date().getTime();
ContentUris.appendId(builder, now - DateUtils.DAY_IN_MILLIS * 10000);
ContentUris.appendId(builder, now + DateUtils.DAY_IN_MILLIS * 10000);
Cursor eventCursor = contentResolver.query(builder.build(),
new String[] { "title", "begin", "end", "allDay"}, "Calendars._id=" + 1,
null, "startDay ASC, startMinute ASC");
System.out.println("eventCursor count="+eventCursor.getCount());
if(eventCursor.getCount()>0)
{
if(eventCursor.moveToFirst())
{
do
{
Object mbeg_date,beg_date,beg_time,end_date,end_time;
final String title = eventCursor.getString(0);
final Date begin = new Date(eventCursor.getLong(1));
final Date end = new Date(eventCursor.getLong(2));
final Boolean allDay = !eventCursor.getString(3).equals("0");
/* System.out.println("Title: " + title + " Begin: " + begin + " End: " + end +
" All Day: " + allDay);
*/
System.out.println("Title:"+title);
System.out.println("Begin:"+begin);
System.out.println("End:"+end);
System.out.println("All Day:"+allDay);
/* the calendar control metting-begin events Respose sub-string (starts....hare) */
Pattern p = Pattern.compile(" ");
String[] items = p.split(begin.toString());
String scalendar_metting_beginday,scalendar_metting_beginmonth,scalendar_metting_beginyear,scalendar_metting_begindate,scalendar_metting_begintime,scalendar_metting_begingmt;
scalendar_metting_beginday = items[0];
scalendar_metting_beginmonth = items[1];
scalendar_metting_begindate = items[2];
scalendar_metting_begintime = items[3];
scalendar_metting_begingmt = items[4];
scalendar_metting_beginyear = items[5];
String calendar_metting_beginday = scalendar_metting_beginday;
String calendar_metting_beginmonth = scalendar_metting_beginmonth.toString().trim();
int calendar_metting_begindate = Integer.parseInt(scalendar_metting_begindate.trim());
String calendar_metting_begintime = scalendar_metting_begintime.toString().trim();
String calendar_metting_begingmt = scalendar_metting_begingmt;
int calendar_metting_beginyear = Integer.parseInt(scalendar_metting_beginyear.trim());
System.out.println("calendar_metting_beginday="+calendar_metting_beginday);
System.out.println("calendar_metting_beginmonth ="+calendar_metting_beginmonth);
System.out.println("calendar_metting_begindate ="+calendar_metting_begindate);
System.out.println("calendar_metting_begintime="+calendar_metting_begintime);
System.out.println("calendar_metting_begingmt ="+calendar_metting_begingmt);
System.out.println("calendar_metting_beginyear ="+calendar_metting_beginyear);
/* the calendar control metting-begin events Respose sub-string (starts....ends) */
/* the calendar control metting-end events Respose sub-string (starts....hare) */
Pattern p1 = Pattern.compile(" ");
String[] enditems = p.split(end.toString());
String scalendar_metting_endday,scalendar_metting_endmonth,scalendar_metting_endyear,scalendar_metting_enddate,scalendar_metting_endtime,scalendar_metting_endgmt;
scalendar_metting_endday = enditems[0];
scalendar_metting_endmonth = enditems[1];
scalendar_metting_enddate = enditems[2];
scalendar_metting_endtime = enditems[3];
scalendar_metting_endgmt = enditems[4];
scalendar_metting_endyear = enditems[5];
String calendar_metting_endday = scalendar_metting_endday;
String calendar_metting_endmonth = scalendar_metting_endmonth.toString().trim();
int calendar_metting_enddate = Integer.parseInt(scalendar_metting_enddate.trim());
String calendar_metting_endtime = scalendar_metting_endtime.toString().trim();
String calendar_metting_endgmt = scalendar_metting_endgmt;
int calendar_metting_endyear = Integer.parseInt(scalendar_metting_endyear.trim());
System.out.println("calendar_metting_beginday="+calendar_metting_endday);
System.out.println("calendar_metting_beginmonth ="+calendar_metting_endmonth);
System.out.println("calendar_metting_begindate ="+calendar_metting_enddate);
System.out.println("calendar_metting_begintime="+calendar_metting_endtime);
System.out.println("calendar_metting_begingmt ="+calendar_metting_endgmt);
System.out.println("calendar_metting_beginyear ="+calendar_metting_endyear);
/* the calendar control metting-end events Respose sub-string (starts....ends) */
System.out.println("only date begin of events="+begin.getDate());
System.out.println("only begin time of events="+begin.getHours() + ":" +begin.getMinutes() + ":" +begin.getSeconds());
System.out.println("only date begin of events="+end.getDate());
System.out.println("only begin time of events="+end.getHours() + ":" +end.getMinutes() + ":" +end.getSeconds());
beg_date = begin.getDate();
mbeg_date = begin.getDate()+"/"+calendar_metting_beginmonth+"/"+calendar_metting_beginyear;
beg_time = begin.getHours();
System.out.println("the vaule of mbeg_date="+mbeg_date.toString().trim());
end_date = end.getDate();
end_time = end.getHours();
//CallHandlerUI.metting_begin_date.add(beg_date.toString());
//CallHandlerUI.metting_begin_mdate.add(mbeg_date.toString());
//CallHandlerUI.metting_begin_mtime.add(calendar_metting_begintime.toString());
//CallHandlerUI.metting_end_date.add(end_date.toString());
//CallHandlerUI.metting_end_time.add(end_time.toString());
//CallHandlerUI.metting_end_mtime.add(calendar_metting_endtime.toString());
}
while(eventCursor.moveToNext());
}
}
break;
}
}
}

Fill Gridview with SQL database

**EDIT: I'll use listview instead of Gridview. **
I've been learning Android since a couple of weeks and last days I've been struggling on getting my SQL-data in a gridview. I've been searching through many, many topics and I can't seem to find a fitting answer to my question. This is the code I've got so far:
package com.example.myfirstapp;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class DisplayMessageActivity extends AppCompatActivity {
public static ArrayList<String> ArrayofName = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_message);
SQLiteDatabase db = mDbHelper.getReadableDatabase();
String selectQuery = "SELECT * FROM " + MainActivity.FeedReaderContract.FeedEntry.TABLE_NAME;
Cursor cursor = db.rawQuery(selectQuery, null);
{
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
String id = cursor.getString(cursor.getColumnIndex("_ID"));
String title = cursor.getString(cursor.getColumnIndex("title"));
String subtitle = cursor.getString(cursor.getColumnIndex("subtitle"));
String name = id +"\n" + title +"\n"+ subtitle;
DisplayMessageActivity.ArrayofName.add(name);
} while (cursor.moveToNext());
}
}
GridView gridView = (GridView) findViewById(R.id.gridView1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, ArrayofName);
gridView.setAdapter(adapter);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Toast.makeText(getApplicationContext(),
((TextView) v).getText(), Toast.LENGTH_SHORT).show();
}
});
}
private static final String TEXT_TYPE = " TEXT";
private static final String COMMA_SEP = ",";
private static final String SQL_CREATE_ENTRIES =
"CREATE TABLE " + MainActivity.FeedReaderContract.FeedEntry.TABLE_NAME + " (" +
MainActivity.FeedReaderContract.FeedEntry._ID + " INTEGER PRIMARY KEY," +
MainActivity.FeedReaderContract.FeedEntry.COLUMN_NAME_TITLE + TEXT_TYPE + COMMA_SEP +
MainActivity.FeedReaderContract.FeedEntry.COLUMN_NAME_SUBTITLE + TEXT_TYPE + " )";
private static final String SQL_DELETE_ENTRIES = "DROP TABLE IF EXISTS '" + MainActivity.FeedReaderContract.FeedEntry.TABLE_NAME + "'";
public class FeedReaderDbHelper extends SQLiteOpenHelper {
// If you change the database schema, you must increment the database version.
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "FeedReader.db";
public FeedReaderDbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db) {
db.execSQL(SQL_CREATE_ENTRIES);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// This database is only a cache for online data, so its upgrade policy is
// to simply to discard the data and start over
db.execSQL(SQL_DELETE_ENTRIES);
onCreate(db);
}
}
DisplayMessageActivity.FeedReaderDbHelper mDbHelper = new FeedReaderDbHelper(this);
public void Test (View view) {
SQLiteDatabase db = mDbHelper.getReadableDatabase();
// Define a projection that specifies which columns from the database you will actually use after this query.
String[] projection = {MainActivity.FeedReaderContract.FeedEntry._ID, MainActivity.FeedReaderContract.FeedEntry.COLUMN_NAME_TITLE, MainActivity.FeedReaderContract.FeedEntry.COLUMN_NAME_SUBTITLE};
// Filter results WHERE "title" = 'My Title'
String selection = MainActivity.FeedReaderContract.FeedEntry.COLUMN_NAME_TITLE + " = ?";
String[] selectionArgs = {"A"};
// How you want the results sorted in the resulting Cursor
String sortOrder = MainActivity.FeedReaderContract.FeedEntry.COLUMN_NAME_SUBTITLE + " DESC";
Cursor c = db.query(
MainActivity.FeedReaderContract.FeedEntry.TABLE_NAME, // The table to query
projection, // The columns to return
selection, // The columns for the WHERE clause
selectionArgs, // The values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
sortOrder // The sort order
);
if (c.getCount()>0) {
c.moveToFirst();
int itemId = c.getInt(c.getColumnIndexOrThrow(MainActivity.FeedReaderContract.FeedEntry._ID));
String strTitel = c.getString(c.getColumnIndexOrThrow(MainActivity.FeedReaderContract.FeedEntry.COLUMN_NAME_TITLE));
String strSubtitel = c.getString(c.getColumnIndexOrThrow(MainActivity.FeedReaderContract.FeedEntry.COLUMN_NAME_SUBTITLE));
EditText edtID = (EditText) findViewById(R.id.txtInvoer);
edtID.setText(Integer.toString(itemId));
EditText edtTitle = (EditText) findViewById(R.id.txtTitel2);
edtTitle.setText(strTitel);
EditText edtSubtitle = (EditText) findViewById(R.id.txtSubtitel2);
edtSubtitle.setText(strSubtitel);
} else {
Toast.makeText(getApplicationContext(), "Geen data in db", Toast.LENGTH_LONG).show();
}
}
public void Vorige (View view) {
SQLiteDatabase db = mDbHelper.getReadableDatabase();
String[] projection = {MainActivity.FeedReaderContract.FeedEntry._ID, MainActivity.FeedReaderContract.FeedEntry.COLUMN_NAME_TITLE, MainActivity.FeedReaderContract.FeedEntry.COLUMN_NAME_SUBTITLE};
String selection = "_ID=?";
EditText edtGeselecteerdeID = (EditText) findViewById(R.id.txtInvoer);
int intVolgendeID=Integer.parseInt(edtGeselecteerdeID.getText().toString())-1;
String strVolgendeID=Integer.toString(intVolgendeID);
String[] selectionArgs = {strVolgendeID};
// How you want the results sorted in the resulting Cursor
String sortOrder = MainActivity.FeedReaderContract.FeedEntry.COLUMN_NAME_SUBTITLE + " DESC";
Cursor c = db.query(
MainActivity.FeedReaderContract.FeedEntry.TABLE_NAME, // The table to query
projection, // The columns to return
selection, // The columns for the WHERE clause
selectionArgs, // The values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
sortOrder // The sort order
);
if (c.getCount()>0) {
c.moveToFirst();
int itemId = c.getInt(c.getColumnIndexOrThrow(MainActivity.FeedReaderContract.FeedEntry._ID));
String strTitel = c.getString(c.getColumnIndexOrThrow(MainActivity.FeedReaderContract.FeedEntry.COLUMN_NAME_TITLE));
String strSubtitel = c.getString(c.getColumnIndexOrThrow(MainActivity.FeedReaderContract.FeedEntry.COLUMN_NAME_SUBTITLE));
EditText edtID = (EditText) findViewById(R.id.txtInvoer);
edtID.setText(Integer.toString(itemId));
EditText edtTitle = (EditText) findViewById(R.id.txtTitel2);
edtTitle.setText(strTitel);
EditText edtSubtitle = (EditText) findViewById(R.id.txtSubtitel2);
edtSubtitle.setText(strSubtitel);
} else {
Toast.makeText(getApplicationContext(), "Geen data in db", Toast.LENGTH_LONG).show();
}
}
public void Volgende (View view) {
SQLiteDatabase db = mDbHelper.getReadableDatabase();
String[] projection = {MainActivity.FeedReaderContract.FeedEntry._ID, MainActivity.FeedReaderContract.FeedEntry.COLUMN_NAME_TITLE, MainActivity.FeedReaderContract.FeedEntry.COLUMN_NAME_SUBTITLE};
String selection = MainActivity.FeedReaderContract.FeedEntry._ID + " = ?";
EditText edtGeselecteerdeID = (EditText) findViewById(R.id.txtInvoer);
int intVolgendeID=Integer.parseInt(edtGeselecteerdeID.getText().toString())+1;
String strVolgendeID=Integer.toString(intVolgendeID);
String[] selectionArgs = {strVolgendeID};
// How you want the results sorted in the resulting Cursor
String sortOrder = MainActivity.FeedReaderContract.FeedEntry.COLUMN_NAME_SUBTITLE + " DESC";
Cursor c = db.query(
MainActivity.FeedReaderContract.FeedEntry.TABLE_NAME, // The table to query
projection, // The columns to return
selection, // The columns for the WHERE clause
selectionArgs, // The values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
sortOrder // The sort order
);
if (c.getCount()>0) {
c.moveToFirst();
int itemId = c.getInt(c.getColumnIndexOrThrow(MainActivity.FeedReaderContract.FeedEntry._ID));
String strTitel = c.getString(c.getColumnIndexOrThrow(MainActivity.FeedReaderContract.FeedEntry.COLUMN_NAME_TITLE));
String strSubtitel = c.getString(c.getColumnIndexOrThrow(MainActivity.FeedReaderContract.FeedEntry.COLUMN_NAME_SUBTITLE));
EditText edtID = (EditText) findViewById(R.id.txtInvoer);
edtID.setText(Integer.toString(itemId));
EditText edtTitle = (EditText) findViewById(R.id.txtTitel2);
edtTitle.setText(strTitel);
EditText edtSubtitle = (EditText) findViewById(R.id.txtSubtitel2);
edtSubtitle.setText(strSubtitel);
} else {
Toast.makeText(getApplicationContext(), "Geen data in db", Toast.LENGTH_LONG).show();
}
}
}
So in MainActivity I've got code to add data into the database. 'DisplayMessageActivity' is for testing out new stuff. My database consists of 3 columns: ID, title and subtitle. I use the method 'Test' to display the data in Edittext objects, and the methods 'Vorige' and 'Volgende' to go through the data. Now I'm trying to display the data (id, title & subtitle) in a gridview or listview (I don't really know what to use). You can find all the code for my problem in the first onCreate class.
I'd like to achieve something like this:
So the first row displays the different column titles, and all the other rows display the data. The first row displaying the titles aren't even needed, I could easily add them by using EditText fields.
Can anyone help me out here? Other suggestions for improving my code are always welcome too ;)

Is there an standard way to access calendar events, call logs and inbox messages?

I've developed an application that accesses calendar events, call logs and inbox messages by using things like this:
cursor = this.contentResolver.query(CallLog.Calls.CONTENT_URI, projection, selection, null, order);
The app works perfectly in Galaxy SII but when I installed it in XPeria U it don't worked, probably because that phone manages calendars, calls and messages in a different way.
If I have to develop an application to each phone in the world, this is not a good business. I tried some Android classes like CalendarContract.Events but its API level is too hard and I don't want that because it won't work in most phones. Is there a good standard way to tho this that works on a high number of devices?
Thanks!
package bembibre.coolstar.windowsmobilewidget.backend;
import java.util.ArrayList;
import java.util.List;
import bembibre.coolstar.windowsmobilewidget.apiindependent.ApiIndependentCallLog;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.provider.CallLog;
import android.util.Log;
public class CallsContentResolver {
public static final String[] projection = {
CallLog.Calls.CACHED_NAME,
CallLog.Calls.DATE,
};
public static final String selection = "((" + CallLog.Calls.TYPE + " = " +
CallLog.Calls.MISSED_TYPE + ") AND NOT(" +
ApiIndependentCallLog.instance().CALLS_IS_READ + "))";
private static final int MAX_NUM_CALLS = 3;
private static final String order = CallLog.Calls.DATE + " DESC LIMIT " + MAX_NUM_CALLS;
private ContentResolver contentResolver;
public CallsContentResolver(Context ctx) {
this.contentResolver = ctx.getContentResolver();
}
public void readCursor(List<Call> calls, Cursor cursor){
while (cursor.moveToNext()) {
String cached_name = cursor.getString(cursor.getColumnIndex(
CallLog.Calls.CACHED_NAME)
);
long date = cursor.getLong(cursor.getColumnIndex(
CallLog.Calls.DATE)
);
Call call = new Call(cached_name, date);
calls.add(0, call);
}
}
public List<Call> getMissedCalls(){
List<Call> calls = new ArrayList<Call>();
Cursor cursor = null;
try{
cursor = this.contentResolver.query(CallLog.Calls.CONTENT_URI, projection, selection, null, order);
if(cursor.getCount() > 0) {
this.readCursor(calls, cursor);
}
}
catch(Exception e){
Log.d("EXCEPCIÓN", e.getMessage());
}
finally{
if(cursor != null){
cursor.close();
}
}
return calls;
}
}
have a look at Calendar Provider (http://developer.android.com/guide/topics/providers/calendar-provider.html) and Contacts Provider (http://developer.android.com/guide/topics/providers/contacts-provider.html).
You can fetch the calender event from this query where
long after = date.getTime();
long current = new Date().getTime();
long millisOfOne = 1000;
long millisOftwoFour = 1000 * 60 * 60 * 24;
long millisOfTodayLast = date.getTime() + millisOftwoFour
- millisOfOne;
Cursor cursor = context.getContentResolver().query(Uri.parse("content://com.android.calendar/events"),new String[] { "calendar_id", "title", "description","dtstart", "dtend", "eventLocation", "_id" },"dtstart >=" + after + " and dtstart<" + millisOfTodayLast,
null, "dtstart ASC");

Multiple Contact Picker List

I have a contact picker list with chckboxes of the contacts that have a phone number.
Now, my problem is that can't seem to get the checked contact's name and phone number.
Here is my code:
import android.app.ListActivity;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
public class Create_Group extends ListActivity implements OnClickListener{
// List variables
public String[] Contacts = {};
public int[] to = {};
public ListView myListView;
Button save_button;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create_group);
// Initializing the buttons according to their ID
save_button = (Button)findViewById(R.id.save_group_button);
// Defines listeners for the buttons
save_button.setOnClickListener(this);
Cursor mCursor = getContacts();
startManagingCursor(mCursor);
ListAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_multiple_choice, mCursor,
Contacts = new String[] {ContactsContract.Contacts.DISPLAY_NAME },
to = new int[] { android.R.id.text1 });
setListAdapter(adapter);
myListView = getListView();
myListView.setItemsCanFocus(false);
myListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
}
private Cursor getContacts() {
// Run query
Uri uri = ContactsContract.Contacts.CONTENT_URI;
String[] projection = new String[] { ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME};
String selection = ContactsContract.Contacts.HAS_PHONE_NUMBER + " = '"
+ ("1") + "'";
String[] selectionArgs = null;
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME
+ " COLLATE LOCALIZED ASC";
return managedQuery(uri, projection, selection, selectionArgs,
sortOrder);
}
public void onClick(View src) {
Intent i;
switch (src.getId())
{
case R.id.save_group_button:
int checked_Names_Counter = 0;
// Goes over the list of contacts and checks which were checked
for (int j = 0; j < myListView.getCount(); j++)
{
if (myListView.isItemChecked(j) == true)
{
Cursor cur = getContacts();
ContentResolver contect_resolver = getContentResolver();
cur.moveToFirst();
/**
* Here I tried to compare the IDs but each list has different IDs so it didn't really help me...
// Converts the current checked name ID into a String
String Checked_ID = String.valueOf(myListView.getCheckedItemIds()[checked_Names_Counter]);
// Checks if the current checked ID matches the cursors ID, if not move the cursor to the next name
while (Checked_ID != cur.getString(cur.getColumnIndexOrThrow(ContactsContract.Contacts._ID)))
{
cur.moveToNext();
}
*/
/**
* Here I tried to compare the names, even though it's not a good pratice, and it didn't work either...
String Checked_Name = myListView.getAdapter().getItem(checked_Names_Counter).toString();
// Checks if the current checked ID matches the cursors ID, if not move the cursor to the next name
while (Checked_Name != cur.getString(cur.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME)))
{
cur.moveToNext();
}
*/
String id = cur.getString(cur.getColumnIndexOrThrow(ContactsContract.Contacts._ID));
String name = "";
String no = "";
Cursor phoneCur = contect_resolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[] { id }, null);
name = phoneCur.getString(phoneCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
no = phoneCur.getString(phoneCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
id = null;
name = null;
no = null;
phoneCur = null;
checked_Names_Counter++;
}
}
// Goes back to the Manage Groups screen
i = new Intent(this, Manage_Groups.class);
startActivity(i);
break;
}
}
}
Any ideas?
Thanks!!
It looks like you are so close, I used ListView.getCheckedItemIds() to return unique ids of the selected contacts:
public void onClick(View view) {
long[] ids = myListView.getCheckedItemIds();
for(long id : ids) {
Cursor contact = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[] { id + "" }, null);
// Do whatever you want with the data
}
}
Addition
I have a quick question about this code:
// Goes back to the Manage Groups screen
i = new Intent(this, Manage_Groups.class);
startActivity(i);
Does this bring the user back to a previous Activity? If so you should use finish(); instead. finish() ends the current Activity, taking it off the stack and freeing up any memory (less memory wasted means a faster app.) It also allows the previous Activity to restore the saved state when it left (filled in EditTexts, previous Spinner selections, toggle button and checkmarks, etc.) The Activity resumes where the user left off.

how to integrate default app of android in our app programatically

Is it possible to integrate the default app(like Calendar) of Android in our app programatically .
Can anyone explain me in details....
The two classes that I am using are:
MainActivity.java
public class MainActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Example.readCalendar(this);
}
}
and another class Example.java
public class Example {
public static void readCalendar(Context context) {
ContentResolver contentResolver = context.getContentResolver();
// Fetch a list of all calendars synced with the device, their display names and whether the
// user has them selected for display.
final Cursor cursor = contentResolver.query(Uri.parse("content://calendar/calendars"),
(new String[] { "_id", "displayName", "selected" }), null, null, null);
// For a full list of available columns see http://tinyurl.com/yfbg76w
HashSet<String> calendarIds = new HashSet<String>();
while (cursor.moveToNext()) {
final String _id = cursor.getString(0);
final String displayName = cursor.getString(1);
final Boolean selected = !cursor.getString(2).equals("0");
System.out.println("Id: " + _id + " Display Name: " + displayName + " Selected: " + selected);
calendarIds.add(_id);
}
// For each calendar, display all the events from the previous week to the end of next week.
for (String id : calendarIds) {
Uri.Builder builder = Uri.parse("content://calendar/instances/when").buildUpon();
long now = new Date().getTime();
ContentUris.appendId(builder, now - DateUtils.WEEK_IN_MILLIS);
ContentUris.appendId(builder, now + DateUtils.WEEK_IN_MILLIS);
Cursor eventCursor = contentResolver.query(builder.build(),
new String[] { "title", "begin", "end", "allDay"}, "Calendars._id=" + id,
null, "startDay ASC, startMinute ASC");
// For a full list of available columns see http://tinyurl.com/yfbg76w
while (eventCursor.moveToNext()) {
final String title = eventCursor.getString(0);
final Date begin = new Date(eventCursor.getLong(1));
final Date end = new Date(eventCursor.getLong(2));
final Boolean allDay = !eventCursor.getString(3).equals("0");
System.out.println("Title: " + title + " Begin: " + begin + " End: " + end +
" All Day: " + allDay);
}
}
}
}
I have added the READ_CALENDAR permission also.
These articles might help you.
Working with the Android Calendar
Accessing the internal calendar database inside Google Android applications
Calendar API (android.provider.Calendar)
Example :
static String contentProvider;
static Uri remindersUri;
static Uri eventsUri;
static Uri calendars;
if(Build.VERSION.RELEASE.contains(”2.2″))
contentProvider = “com.android.calendar”;
else
contentProvider = “calendar”;
remindersUri = Uri.parse(String.format(”content://%s/reminders”,contentProvider));
eventsUri = Uri.parse(String.format(”content://%s/events”,contentProvider));
calendars = Uri.parse(String.format(”content://%s/calendars”,contentProvider));
Intent intent = new Intent(Intent.ACTION_EDIT);
intent.setType("vnd.android.cursor.item/event");
intent.putExtra("title", "Some title");
intent.putExtra("description", "Some description");
intent.putExtra("beginTime", eventStartInMillis);
intent.putExtra("endTime", eventEndInMillis);
startActivity(intent);

Categories

Resources