Getting calendar events in android 4.0 and above - android

I am new to the android development. I am working on calender application where i need to add/delete and get all events in between the date range. I have add and delete the events successufully but problem is when i am getting the calender events in between the date range. I am getting the calender events but when i go to SPlanner i can see those events are not added in the calender as i have already deleted them. I do not know from where i am getting those events.Please suggest. Here is the code i have written to get the calender events:-
public void onGetEvent (final String fullCallbackName, String title,String startDate,String endDate) throws JSONException
{
try
{
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
final ArrayList<JSONObject> calEvents = new ArrayList();
if(calEvents.size() !=0)
{
calEvents.clear();
}
ContentResolver contentResolver = getContentResolver();
String selection = "((dtstart >= "+(dateFormat.parse(startDate).getTime())+") AND (dtend <= "+(dateFormat.parse(endDate).getTime())+"))";
Cursor cursor = contentResolver.query(Uri.parse(getCalendarUriBase() + "events"),
(new String[] { "_id", "title", "dtstart","dtend","eventLocation","description"}), selection, null, null);
Log.e("cursor.getCount before:","callbackFuncName:" + cursor.getCount());
while (cursor.moveToNext()) {
String _id = cursor.getString(0);
String displayName = cursor.getString(1);
Log.e("cursor.getCount before:","callbackFuncName:" + displayName);
String[] separated = displayName.split(":");
if(separated[0]!= null && title.equals(separated[0]))
{
JSONObject dictionary = new JSONObject();
String dstart = dateFormat.format(new Date(Long.parseLong(cursor.getString(2))));//cursor.getString(2);
String dEnd = dateFormat.format(new Date(Long.parseLong(cursor.getString(3))));//cursor.getString(3);
String eventlocation = cursor.getString(4);
String description = cursor.getString(5);
dictionary.put("identifier", _id);
dictionary.put("title", displayName);
dictionary.put("startDate", dstart);
dictionary.put("endDate", dEnd);
dictionary.put("venue", eventlocation);
dictionary.put("notes", description);
calEvents.add(dictionary);
}
}
if(fullCallbackName != null && !fullCallbackName.equals(""))
{
runOnUiThread(new Runnable() {
public void run()
{
webView.loadUrl("javascript:"+fullCallbackName+" ("+calEvents+")") ;
}
});
}
}
catch(Exception e)
{
Log.e("string", e.toString());
}
}
}
code for getting the calender DB is:-
private String getCalendarUriBase() {
String calendarUriBase = null;
Uri calendars = Uri.parse("content://calendar/calendars");
Cursor cursor = null;
try {
cursor = managedQuery(calendars, null, null, null, null);
} catch (Exception e) {
// eat
}
if (cursor != null) {
calendarUriBase = "content://calendar/";
} else {
calendars = Uri.parse("content://com.android.calendar/calendars");
try {
cursor = managedQuery(calendars, null, null, null, null);
} catch (Exception e) {
// eat
}
if (cursor != null) {
calendarUriBase = "content://com.android.calendar/";
}
}
Log.d("Sandeep",
calendarUriBase);
// managedCursor.close();
return calendarUriBase;
}

With your query you will see deleted events because they are still in the database (for being able to sync the deletion whenever the next sync is due). That's what the DELETED column is for.
To find all events between a start and end date use the Instances class of the CalendarContract API as in the code below. This code returns only visible events!
I've written a blog post about the CalendarContract content provider detailing this and other stuff.
long begin = // starting time in milliseconds; for you probably cursor.getLong(2)
long end = // ending time in milliseconds; cursor.getLong(3)
String[] proj =
new String[]{
Instances._ID,
Instances.TITLE,
Instances.BEGIN,
Instances.END,
Instances.EVENT_LOCATION,
Instances.DESCRIPTION,
Instances.EVENT_ID};
Cursor cursor =
Instances.query(getContentResolver(), proj, begin, end);
if (cursor.getCount() > 0) {
// do your JSON thing
}

Related

Pick a number from calllog without repeating the same number

I want user to select a number from calllog and that number get selected and come in the activity. So I created custom calllog list. I used this code but it is not showing the call log list in right order
first thing it is showing the callhistory of the first number fully that it gets in the calllog list
second I wnt to show the name also, I tried a lot but I am not able to do
Can anyone tell what amendments i make in this code to make it right
The code I used is:
String[] callLogFields = { android.provider.CallLog.Calls._ID,
android.provider.CallLog.Calls.NUMBER,
android.provider.CallLog.Calls.CACHED_NAME };
String viaOrder = android.provider.CallLog.Calls.DATE + " DESC";
String WHERE = android.provider.CallLog.Calls.NUMBER + " >0"; /*filter out private/unknown numbers */
final Cursor callLog_cursor = this.getContentResolver().query(
android.provider.CallLog.Calls.CONTENT_URI, callLogFields,
WHERE, null, viaOrder);
AlertDialog.Builder myversionOfCallLog = new AlertDialog.Builder(this);
android.content.DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int item) {
callLog_cursor.moveToPosition(item);
Log.v("number", callLog_cursor.getString(callLog_cursor
.getColumnIndex(android.provider.CallLog.Calls.NUMBER)));
callLog_cursor.close();
}
};
myversionOfCallLog.setCursor(callLog_cursor, listener,
android.provider.CallLog.Calls.NUMBER);
myversionOfCallLog.setTitle("Choose from Call Log");
myversionOfCallLog.create().show();
You can add the Contact Numbers in a Set, which will prevent adding duplicate contact numbers. Then add the Set's data to listview as you want.
Set<String> setNumbers = new HashSet<String>();
String callNumber = cursor.getString(cursor.getColumnIndex(
android.provider.CallLog.Calls.NUMBER));
setNumbers.add(callNumber);
Hope this helps.
For saving numbers without duplicates, as MysticMagic suggested, use 'Set' as per the link given in the comment.
For getting the contact name from the phone number, use code :
(Reference)
private String getContactName(Context context, String number) {
String name = null;
// define the columns I want the query to return
String[] projection = new String[] {
ContactsContract.PhoneLookup.DISPLAY_NAME,
ContactsContract.PhoneLookup._ID};
// encode the phone number and build the filter URI
Uri contactUri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
// query time
Cursor cursor = context.getContentResolver().query(contactUri, projection, null, null, null);
if(cursor != null) {
if (cursor.moveToFirst()) {
name = cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
Log.v(TAG, "Started uploadcontactphoto: Contact Found # " + number);
Log.v(TAG, "Started uploadcontactphoto: Contact name = " + name);
} else {
Log.v(TAG, "Contact Not Found # " + number);
}
cursor.close();
}
return name;
}
Also refer here for another method to fetch name in phone call history
Uri allCalls = Uri.parse("content://call_log/calls");
Cursor c = managedQuery(allCalls, null, null, null, null);
String num= c.getString(c.getColumnIndex(CallLog.Calls.NUMBER));// for number
String name= c.getString(c.getColumnIndex(CallLog.Calls.CACHED_NAME));// for name
String duration = c.getString(c.getColumnIndex(CallLog.Calls.DURATION));// for duration
int type = Integer.parseInt(c.getString(c.getColumnIndex(CallLog.Calls.TYPE)));// for call type, Incoming or out going
Finally this is the code that worked with the help of MysticMagic and Nishanthi Grashia
Set setA;
setA = new HashSet();
public void getCallLog() {
try {
final String[] projection = null;
final String selection = null;
final String[] selectionArgs = null;
final String sortOrder = "DATE DESC";
final Cursor cursor = this.getContentResolver().query(
Uri.parse("content://call_log/calls"), projection,
selection, selectionArgs, sortOrder);
if (cursor != null) {
// Loop through the call log.
while (cursor.moveToNext()) {
// Common Call Log Items
String callNumber = cursor
.getString(cursor
.getColumnIndex(android.provider.CallLog.Calls.NUMBER));
setA.add(callNumber);
}
generateList();
}
} catch (Exception e) {
}
}
#SuppressLint("NewApi")
private void generateList() {
// TODO Auto-generated method stub
try {
Object[] calllist = new String[setA.size()];
calllist = setA.toArray();
String scalllist[] = Arrays.copyOf(calllist, calllist.length,
String[].class);
for (int i = 0; i < scalllist.length; i++) {
scalllist[i] = scalllist[i] + " "
+ getContactName(this, scalllist[i]);
}
final Dialog d = new Dialog(this);
d.setContentView(R.layout.dialog1);
d.setTitle("Choose from Call Log...");
final ListView lv1 = (ListView) d.findViewById(R.id.listView1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1,
scalllist);
lv1.setAdapter(adapter);
lv1.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
String clickednumber[] = (lv1.getItemAtPosition(arg2)
.toString()).split(" ");
usernumber.setText(clickednumber[0]);
try {
username.setText(clickednumber[1]);
} catch (ArrayIndexOutOfBoundsException e) {
username.setText(" ");
}
d.dismiss();
}
});
d.show();
} catch (Exception e) {
}
}
private String getContactName(Context context, String number) {
String name = null;
try {
// define the columns I want the query to return
String[] projection = new String[] {
ContactsContract.PhoneLookup.DISPLAY_NAME,
ContactsContract.PhoneLookup._ID };
// encode the phone number and build the filter URI
Uri contactUri = Uri.withAppendedPath(
ContactsContract.PhoneLookup.CONTENT_FILTER_URI,
Uri.encode(number));
// query time
Cursor cursor = context.getContentResolver().query(contactUri,
projection, null, null, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
name = cursor
.getString(cursor
.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
} else {
name = " ";
}
cursor.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return name;
}

How to query all the details of the Contact at once

EDIT:A list of what I consider important contact details:
1.NAME
2.PHONE NUMBER
3.EMAIL ADDRESS
4.WEBSITE
5.PHYSICAL ADDRESS
I would prefer to do this using a pre-fetched contactId...using only one cursor to get all of the data specified.I,preferably would like to find the right query to do this:
I would like to get all of the important details of a Contact at once,I am using the following code to do this:
public void getAllDataByContactId(int contactId)
{
Log.d(TAG, "Seriously scared it might not work");
String phoneNo="Phone disconnected";
String email="Email could not be delivered";
String website="Website 404";
String address="Number 13,Dark Street,Area 51,Bermuda Trianlge";
String name="Clint Eastwood";
int hasPhoneNumber;
String selection=ContactsContract.Data.CONTACT_ID+"=?";
String[] selectionArgs={String.valueOf(contactId)};
Cursor c=context.getContentResolver().query(ContactsContract.Data.CONTENT_URI, null,selection, selectionArgs,ContactsContract.Data.TIMES_CONTACTED);
if(c!=null && c.getCount()>0)
{
while(c.moveToNext())
{
phoneNo=c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
Log.d(TAG, "Phone number: "+phoneNo);
email=c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Email.ADDRESS));
Log.d(TAG, "Email: "+email);
website=c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Website.URL));
Log.d(TAG, "Website :"+website);
address=c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS));
name=c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME));
Log.d(TAG, "Name :"+name);
}
}
}
However,although this does not throw an error it shows many rows consisting of an empty string interspresed with the actual values.How do I write a query that cuts out the noise?
I have tried this and this gets me all the values:
String selection=ContactsContract.Data.CONTACT_ID+"=? AND "+ContactsContract.Data.MIMETYPE+"=? OR "+ContactsContract.Data.MIMETYPE+"=? OR "+ContactsContract.Data.MIMETYPE+"=? OR "+ContactsContract.Data.MIMETYPE+"=? OR "+ContactsContract.Data.MIMETYPE+"=?";
String[] selectionArgs={String.valueOf(contactId),ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE,ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE,ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE,ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE,ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE};
Too late to answer, but maybe it can help someone in the future.
My solution for this question with only one while cycle and query:
private void fetchContacts(ContentResolver contentResolver) {
if (contentResolver == null) return;
Cursor cursor = contentResolver.query(ContactsContract.Data.CONTENT_URI,
null, null, null, null);
if (cursor == null || cursor.getCount() <= 0) {
return;
}
String prevId = "";
String contactId = "";
PersonContact personContact = null;
while (cursor.moveToNext()) {
String company = "";
String columnName = cursor.getString(cursor.getColumnIndex("mimetype"));
if (columnName.equals(ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE)) {
company = cursor.getString(cursor.getColumnIndex("data1"));
}
String email = "";
if (columnName.equals(ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)) {
email = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
}
String phone = "";
if (columnName.equals(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)) {
phone = cursor.getString(cursor.getColumnIndex("data1"));
}
String first = "";
String last = "";
if (columnName.equals(ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)) {
first = cursor.getString(cursor.getColumnIndex("data2"));
last = cursor.getString(cursor.getColumnIndex("data3"));
}
if (!prevId.equals(contactId)) {
if (!TextUtils.isEmpty(prevId)) {
addFilteredList(personContact);
allContacts.put(prevId, personContact);
}
prevId = contactId;
personContact = new PersonContact();
} else {
if (personContact != null) {
personContact.id = prevId;
if (TextUtils.isEmpty(personContact.company)) personContact.company = company;
if (TextUtils.isEmpty(personContact.firstName)) personContact.firstName = first;
if (TextUtils.isEmpty(personContact.lastName)) personContact.lastName = last;
if (!TextUtils.isEmpty(email) && personContact.emails.size() == 0) {
personContact.emails.add(email);
}
if (!TextUtils.isEmpty(phone) && personContact.phoneNumbers.size() == 0) {
personContact.phoneNumbers.add(phone);
}
}
}
contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
}
cursor.close();
}
As you can see, I used the prevId field, because cursor.moveToNext performs several times for one contact (once for first and last names, one for phone, etc.). After each iteration, I check the previous contact identifier with the current identifier and, if it is false, I update the fields in the personContact model.
May not be the best solution. But this is how I achieved it.
ArrayList<String> fnameList = new ArrayList<>();
ArrayList<String> lnameList = new ArrayList<>();
ArrayList<String> mnumList = new ArrayList<>();
ArrayList<String> hnumList = new ArrayList<>();
ArrayList<String> wnumList = new ArrayList<>();
ArrayList<String> mailList = new ArrayList<>();
final DynamoDBMapper dynamoDBMapper = AWSMobileClient.defaultMobileClient().getDynamoDBMapper();
final ContactsDO firstItem = new ContactsDO(); // Initialize the Notes Object
firstItem.setUserId(AWSMobileClient.defaultMobileClient().getIdentityManager().getCachedUserID());
String email = null;
Uri CONTENT_URI = ContactsContract.Contacts.CONTENT_URI;
String _ID = ContactsContract.Contacts._ID;
String HAS_PHONE_NUMBER = ContactsContract.Contacts.HAS_PHONE_NUMBER;
Uri EmailCONTENT_URI = ContactsContract.CommonDataKinds.Email.CONTENT_URI;
String EmailCONTACT_ID = ContactsContract.CommonDataKinds.Email.CONTACT_ID;
String DATA = ContactsContract.CommonDataKinds.Email.DATA;
StringBuffer output = new StringBuffer();
ContentResolver contentResolver = this.getContentResolver();
Cursor cursor = contentResolver.query(CONTENT_URI, null, null, null, null);
// Loop for every contact in the phone
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex(HAS_PHONE_NUMBER)));
if (hasPhoneNumber > 0) {
String contact_id = cursor.getString(cursor.getColumnIndex(_ID));
// Query and loop for every phone number of the contact
Cursor pCur = contentResolver.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
new String[]{contact_id}, ContactsContract.CommonDataKinds.Phone.NUMBER);
int flag = 0;
assert pCur != null;
while (pCur.moveToNext()) {
String mobileNum = pCur.getString(pCur.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.NUMBER));
if (flag == 0) {
if(mobileNum!=null){
mnumList.add(mobileNum);}
} else if (flag == 1) {
if(mobileNum!=null){
hnumList.add(mobileNum);}
} else if (flag == 2) {
if(mobileNum!=null){
wnumList.add(mobileNum);}
}
flag++;
}
if(flag==1){
hnumList.add("");
wnumList.add("");
Log.e("Set","Both added");
}
if(flag==2){
wnumList.add("");
Log.e("Set","W added");
}
pCur.close();
}
}
}
cursor.close();
String MIME = ContactsContract.Data.MIMETYPE + "=?";
String[] params = new String[]{ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE};
final Cursor nameCur = contentResolver.query(
ContactsContract.Data.CONTENT_URI,
null,
MIME,
params,
ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME);
assert nameCur != null;
int i = 0;
while (nameCur.moveToNext()){
String fname = "";
String lname = "";
fname = nameCur.getString(nameCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME));
lname = nameCur.getString(nameCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME));
Log.e("In While","All the time");
if(fname!=null){
fnameList.add(fname);
Log.e("Put","Value Fname "+fname);}
if(lname!=null) {
lnameList.add(lname);
Log.e("Put","Value Lname "+lname);
}
if(fname==null){
fnameList.add(" ");
}
if(lname==null){
lnameList.add(" ");
}
i++;
}
nameCur.close();
Cursor cursorB = contentResolver.query(CONTENT_URI, null, null, null, null);
// Loop for every contact in the phone
if (cursorB.getCount() > 0) {
while (cursorB.moveToNext()) {
// Query and loop for every email of the contact
String[] paramEmail = new String[]{ContactsContract.CommonDataKinds.Email.CONTENT_TYPE};
Cursor emailCursor = contentResolver.query(EmailCONTENT_URI, null, ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?", paramEmail, ContactsContract.CommonDataKinds.Email.DISPLAY_NAME);
int j=0;
while (emailCursor.moveToNext()) {
email = emailCursor.getString(emailCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.ADDRESS));
mailList.add(email);
Log.e("Email",email);
j++;
}
if(j==0){
mailList.add("");
Log.e("Email","Dummy Added");
}
emailCursor.close();
output.append("\n");
}
}cursorB.close();
Cursor cursorD = contentResolver.query(CONTENT_URI, null, null, null, null);
// Loop for every contact in the phone
if (cursorD.getCount() > 0) {
while (cursorD.moveToNext()) {
String contact_id = cursorD.getString(cursorD.getColumnIndex(_ID));
//for url
String newNoteUrl = "";
String whereName3 = ContactsContract.Data.MIMETYPE + " = ?";
String[] whereNameParams3 = new String[]{ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE};
ContentResolver contentResolverUrl = this.getContentResolver();
try {
Cursor cursorUrl = contentResolverUrl.query(ContactsContract.Data.CONTENT_URI, null, whereName3, new String[]{contact_id}, ContactsContract.CommonDataKinds.Website.URL);
while (cursorUrl.moveToNext()) {
newNoteUrl = cursorUrl.getString(cursorUrl.getColumnIndex(ContactsContract.CommonDataKinds.Website.URL));
Log.e("URL",newNoteUrl);
}
Log.e("URL","Not Getting");
output.append("\nurl " + newNoteUrl);
firstItem.setUrl(newNoteUrl);
cursorUrl.close();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}}cursorD.close();
Log.e("#######","##########################");
for(int m=0;m<fnameList.size();m++){
Log.e("Contact Val ",fnameList.get(m)+" , "+lnameList.get(m)+" , "+mnumList.get(m)+" , "+hnumList.get(m)+" , "+wnumList.get(m)+" , "+mailList.get(m));
ContactsDO item = new ContactsDO();
item.setUserId(AWSMobileClient.defaultMobileClient().getIdentityManager().getCachedUserID());
item.setFirstName(fnameList.get(m));
item.setLastName(lnameList.get(m));
item.setMobileNumber(mnumList.get(m));
item.setHomeNumber(hnumList.get(m));
item.setWorkNumber(wnumList.get(m));
item.setEmail(mailList.get(m));
try {
//saving to the database
dynamoDBMapper.save(item);
} catch (final AmazonClientException ex) {
Log.e(TAG, "Failed saving item : " + ex.getMessage(), ex);
}
}

arraylist is not updating correctly

I am using contentobserver to monitor SMS. It all works fine. When I try to save these SMS to a database, it shows an error error near "t" syntax error for a particular SMS. When I delete this particular SMS there is no problem. After installing, it shows all the messages correctly in order. But the error is sent to the end of my arraylist. Also the SMS sent from my phone after this are updated in between the list, not on the last position. Please help.
adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1,list);
setListAdapter(adapter);
data = Incoming_outgoing_smsActivity.this.openOrCreateDatabase("Messages", MODE_PRIVATE, null);
data.execSQL("CREATE TABLE IF NOT EXISTS recor(text varchar(300));");
Cursor cur = data.rawQuery("SELECT * FROM recor", null);
while(cur.moveToNext()) {
String content = cur.getString(cur.getColumnIndex("text"));
backward_list.add(content);
list.add(content);
}
adapter.notifyDataSetChanged();
Cursor cursor = getContentResolver().query(Uri.parse("content://sms"), null, null, null, null);
while(cursor.moveToNext()) {
String number = cursor.getString(cursor.getColumnIndex("address"));
String[] projection = new String[] {ContactsContract.PhoneLookup.DISPLAY_NAME};
Uri contactUri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
Cursor cursor_name = getContentResolver().query(contactUri, projection, null, null, null);
String body = cursor.getString(cursor.getColumnIndex("body"));
String type = cursor.getString(cursor.getColumnIndex("type"));
long date1= cursor.getLong(cursor.getColumnIndex("date"));
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss.SSS");
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(date1);
try {
int n = cursor.getInt(cursor.getColumnIndex("type"));
switch (n) {
case 1:
String message = "FROM "+number+"\n"+formatter.format(calendar.getTime())+"\n"+"Message:-"+body;
if(backward_list.contains(message)) {
continue;
} else {
list.add(message);
backward_list.add(message);
data.execSQL("INSERT INTO recor VALUES('"+message+"')");
}
break;
case 2:
String messag = "TO "+number+"\n"+formatter.format(calendar.getTime())+"\n"+"Message:-"+body;
if(backward_list.contains(messag)) {
continue;
} else {
list.add(messag);
backward_list.add(messag);
data.execSQL("INSERT INTO recor VALUES('"+messag+"')");
}
break;
default:
break;
}
}
catch (Exception e) {
// TODO: handle exception
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
continue;
}
}
The above code saves the current SMS in your inbox to the database. The code below is used to update your inbox when a new SMS arrives. It does toast the arrived messages but doesn't insert them into the database.
data = Incoming_outgoing_smsActivity.this.openOrCreateDatabase("Messages", MODE_PRIVATE, null);
data.execSQL("CREATE TABLE IF NOT EXISTS recor(text varchar(300));");
super.onChange(selfChange);
Cursor cursor = getContentResolver().query(Uri.parse("content://sms"), null, null, null, null);
while(cursor.moveToNext()) {
String number = cursor.getString(cursor.getColumnIndex("address"));
String[] projection = new String[] {
ContactsContract.PhoneLookup.DISPLAY_NAME};
Uri contactUri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
Cursor cursor_name = getContentResolver().query(contactUri, projection, null, null, null);
if(cursor_name.moveToFirst()) {
name = cursor_name.getString(cursor_name.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
}
String body = cursor.getString(cursor.getColumnIndex("body"));
String type = cursor.getString(cursor.getColumnIndex("type"));
long date1= cursor.getLong(cursor.getColumnIndex("date"));
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss.SSS");
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(date1);
int n = cursor.getInt(cursor.getColumnIndex("type"));
switch (n) {
case 1:
String message = "FROM "+number+"\n"+formatter.format(calendar.getTime())+"\n"+"Message:-"+body;
if(backward_list.contains(message)) {
continue;
} else {
list.add(message);
backward_list.add(message);
data.execSQL("INSERT INTO recor VALUES('"+message+"')");
}
break;
case 2:
String messag = "TO "+number+"\n"+formatter.format(calendar.getTime())+"\n"+"Message:-"+body;
if(backward_list.contains(messag)) {
continue;
} else {
list.add(messag);
backward_list.add(messag);
data.execSQL("INSERT INTO recor VALUES('"+messag+"')");
}
break;
default:
break;
}
At a guess there was some sort of restricted character/word in the one SMS.
You should use prepared statements to take care of the issue.
See this SO Answer for an example.
For your second issue about the order of display, change/use an ORDER BY in your query to set the proper order.

How do update the calendar dynamically from my Android code

I need to be able to create an event in the Google Calendar from my Android app. I believe there is a Calendar API but I have never used it. I'm fairly new to Android development so I've found a few examples from browsing earlier and used the following code to try to update my Android Calendar.
public static boolean updateCalendar(Context context,String cal_Id,String eventId)
{
try{
Uri CALENDAR_URI = Uri.parse(CAL_URI+"events");
Cursor c = context.getContentResolver().query(CALENDAR_URI, null, null, null, null);
String[] s = c.getColumnNames();
if (c.moveToFirst())
{
while (c.moveToNext())
{
String _id = c.getString(c.getColumnIndex("_id"));
String CalId = c.getString(c.getColumnIndex("calendar_id"));
if ((_id==null) && (CalId == null))
{
return false;
}
else
{
if (_id.equals(eventId) && CalId.equals(cal_Id))
{
Uri uri = ContentUris.withAppendedId(CALENDAR_URI, Integer.parseInt(_id));
context.getContentResolver().update(uri, null, null, null);// need to give your data here
return true;
}
}
}
}
}
finally
{
return true;
}
}
However when I run it the getColumnNames doesn't get called and the code jumps straight to the line context.getContentResolver().update(uri, null, null, null); and then exits.
I put a couple of test events in my Calendar, why is the code not picking them up?
use this to add event to calender to particular date and time
Uri event1;
long epoch;
long epoch1;
Uri EVENTS_URI = Uri.parse(getCalendarUriBase(this) + "events");
ContentResolver cr = getContentResolver();
ContentValues values = new ContentValues();
try
{
epoch = new java.text.SimpleDateFormat ("yyyy-MM-dd hh:mm").parse(YourStartDate+" "+YourStratTime).getTime();
//epoch=epoch;
Log.e("epoch",String.valueOf(epoch));
epoch1 = new java.text.SimpleDateFormat ("yyyy-MM-dd hh:mm").parse(YourStartDate+" "+YourEndDate).getTime();
//epoch1=epoch1;
Log.e("epoch1",String.valueOf(epoch1));
} catch (ParseException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
values.put("calendar_id", 1);
values.put("title", "Appoitment");
values.put("allDay", 0);
values.put("dtstart",epoch); // event starts at 11 minutes from now
values.put("dtend", epoch1 ); // ends 60 minutes from now
values.put("description", "Your consulting date and time ");
values.put("visibility", 0);
values.put("hasAlarm", 1);
if(EVENTS_URI!=null)
{
event1 = cr.insert(EVENTS_URI, values);
}
// reminder insert
Uri REMINDERS_URI = Uri.parse(getCalendarUriBase(this) + "reminders");
values = new ContentValues();
values.put( "event_id", Long.parseLong(event1.getLastPathSegment()));
values.put( "method", 1 );
values.put( "minutes", 10 );
if(REMINDERS_URI!=null)
{
cr.insert( REMINDERS_URI, values );
}
getCalendarUroBase function:
private String getCalendarUriBase(Activity act) {
String calendarUriBase = null;
Uri calendars = Uri.parse("content://calendar/calendars");
Cursor managedCursor = null;
try {
managedCursor = act.managedQuery(calendars, null, null, null, null);
} catch (Exception e) {
}
if (managedCursor != null) {
calendarUriBase = "content://calendar/";
} else {
calendars = Uri.parse("content://com.android.calendar/calendars");
try {
managedCursor = act.managedQuery(calendars, null, null, null, null);
} catch (Exception e) {
}
if (managedCursor != null) {
calendarUriBase = "content://com.android.calendar/";
}
}
return calendarUriBase;
}
Note: As per Sample Date should be in yyyy-MM-dd, time should be in hh:mm formats

Insert StatusUpdates into a specified contact, but always insert to a random contact

sample contacts:
_ID DISPLAY_NAME PHONE
1 contact1 11111111
2 contact2 22222222
Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode("22222222"));
Cursor c = this.getContentResolver().query(uri, new String[] {Data._ID}, null, null, null);
long profileId = 0;
if (c.moveToFirst())
{
profileId = c.getLong(0);
}
c.close();
c = null;
final ContentValues values = new ContentValues();
if (profileId > 0) {
values.put(StatusUpdates.DATA_ID, profileId);
values.put(StatusUpdates.STATUS, "HELLO WORLD!");
values.put(StatusUpdates.PROTOCOL, Im.PROTOCOL_CUSTOM);
values.put(StatusUpdates.CUSTOM_PROTOCOL, CUSTOM_IM_PROTOCOL);
values.put(StatusUpdates.PRESENCE, 4); //
values.put(StatusUpdates.STATUS_RES_PACKAGE, this.getPackageName());
values.put(StatusUpdates.STATUS_LABEL, R.string.label);
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
ops.add(ContentProviderOperation.newInsert(StatusUpdates.CONTENT_URI)
.withValues(values).build());
try{
this.getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
}
catch(RemoteException e)
{Log.e...}
catch(OperationApplicationException e)
{Log.e...}
}
I'm trying to insert status to the specified contact "contact2", but it doesn't work correctly, and always insert to "contact1".
Please help me, many thanks.
from sample sync adapter example :
public static long lookupRawContact(ContentResolver resolver, String userId)
{
long authorId = 0;
final Cursor c =
resolver.query(RawContacts.CONTENT_URI, UserIdQuery.PROJECTION,
UserIdQuery.SELECTION, new String[] {userId},
null);
try {
if (c.moveToFirst()) {
authorId = c.getLong(UserIdQuery.COLUMN_ID);
}
} finally {
if (c != null) {
c.close();
}
}
return authorId;
}
This will return the correct profile ID or 0 if not found

Categories

Resources