I have an application that adds an event to the calendar on the device. I have the following URLs for the Calendar ContentProvider:
Pre Froyo: content://calendar/calendars
Froyo: content://com.android.calendar/calendars
These urls work fine for Nexus One but do not return any calendars on HTC Desire/Incredible/Hero. Probably all phones with a Sense UI. This happens on 2.1 and 2.2.
Has anybody run into this problem before and has any workarounds?
use this code to get the URI for your platform
private String getCalendarUriBase() {
String calendarUriBase = null;
Uri calendars = Uri.parse("content://calendar/calendars");
Cursor managedCursor = null;
try {
managedCursor = 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 = managedQuery(calendars, null, null, null, null);
} catch (Exception e) {
}
if (managedCursor != null) {
calendarUriBase = "content://com.android.calendar/";
}
}
return calendarUriBase;
}
Related
I have an application that runs under system account and one of the features is create custom APNs depending the client's configurations.
The code below works fine, but just create the APN and set it as default for simcard 1. O would like to set it depending on simcards if the software is running on Android 5 or above. I could not find any documentation about it. Anyone knows something else about APNs?
public static int createNewApn(Context context, APN apn, boolean setAsDefaultAPN) {
int apnid = -1;
try {
if (apn != null) {
Uri APN_URI = Uri.parse("content://telephony/carriers");
ContentResolver resolver = context.getContentResolver();
ContentValues values = prepareValues(apn);
Cursor c = null;
Uri newRow = resolver.insert(APN_URI, values);
if (newRow != null) {
c = resolver.query(newRow, null, null, null, null);
int tableIndex = c.getColumnIndex("_id");
c.moveToFirst();
apnid = c.getShort(tableIndex);
}
if (c != null) {
c.close();
}
if (apnid > -1 && setAsDefaultAPN) {
ContentValues v = new ContentValues(1);
v.put("apn_id", apnid);
context.getContentResolver().update(APN_PREFER_URI, v, null, null);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return apnid;
}
Android 5.1.1 lollipop return null file path if image chosen from gallery. The below code works fine in all the devices below 5.1.1, but doesn't work in lollipop 5.1.1
Uri contentUri = data.getData();
Cursor cursor = null;
try {
String[] proj = {MediaStore.Images.Media.DATA};
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
cursor.getString(column_index) this returns null.
For now I have ended up with this for getting an image from gallery. I've tested it on 4.4, 5.0.1 and 5.1.1 but it should work on previous versions too (with new and old Google photo app), should be less hacky and doesn't require a check on Android version.
public static Uri handleImageUri(Uri uri) {
if (uri.getPath().contains("content")) {
Pattern pattern = Pattern.compile("(content://media/.*\\d)");
Matcher matcher = pattern.matcher(uri.getPath());
if (matcher.find())
return Uri.parse(matcher.group(1));
else
throw new IllegalArgumentException("Cannot handle this URI");
}
return uri;
}
And with this I used the same code I have ever used before for getting the image path:
public static String getRealPathFromURI(Context context, Uri uri) {
Cursor cursor = null;
try {
Uri newUri = handleImageUri(uri);
String[] proj = { MediaStore.Images.Media.DATA };
cursor = context.getContentResolver().query(newUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} catch (Exception e){
return null;
} finally {
if (cursor != null) {
cursor.close();
}
}
}
For a temporary hack-around for android lollipop 5.1.1. It Works fine now. But m not satisfied with this unofficial hack.
Uri selectedImage = data.getData();
if (Build.VERSION.SDK_INT == 22) {
if (selectedImage != null && selectedImage.toString().length() > 0) {
try {
final String extractUriFrom = selectedImage.toString();
String firstExtraction = extractUriFrom.contains("com.google.android.apps.photos.contentprovider") ? extractUriFrom.split("/1/")[1] : extractUriFrom;
firstExtraction = firstExtraction.contains("/ACTUAL") ? firstExtraction.replace("/ACTUAL", "").toString() : firstExtraction;
String secondExtraction = URLDecoder.decode(firstExtraction, "UTF-8");
selectedImage = Uri.parse(secondExtraction);
} catch (UnsupportedEncodingException e) {
} catch (Exception e) {
}
}
}
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
}
if there any method to get contact name by send contact number in android.if any one have idea .
private String getContactName(String string) {
String name=null;
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,null,null,null, null);
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
}
}
return name;
}
I am sending contact number to these method.How to get contact name.
use following method to get contact, from contact provider:
Uri contactUri = Uri.withAppendedPath(Contacts.Phones.CONTENT_FILTER_URL, Uri.encode(string));
Cursor cursor = mContext.getContentResolver().query(contactUri, null, null, null, null);
This cursor will have resultset having number same as string.
I got it by do like these.
public static String getContactName(final String phoneNumber,Context context) {
Uri uri;
String[] projection;
Uri mBaseUri = Contacts.Phones.CONTENT_FILTER_URL;
projection = new String[] { android.provider.Contacts.People.NAME };
try {
Class<?> c = Class
.forName("android.provider.ContactsContract$PhoneLookup");
mBaseUri = (Uri) c.getField("CONTENT_FILTER_URI").get(mBaseUri);
projection = new String[] { "display_name" };
} catch (Exception e) {
}
uri = Uri.withAppendedPath(mBaseUri, Uri.encode(phoneNumber));
Cursor cursor = context.getContentResolver().query(uri, projection, null,
null, null);
String contactName = "";
if (cursor.moveToFirst()) {
contactName = cursor.getString(0);
}
cursor.close();
cursor = null;
return contactName;
}
Try
Uri uri;
String[] projection;
Uri baseUri = Contacts.Phones.CONTENT_FILTER_URL;
projection = new String[] { android.provider.Contacts.People.NAME };
try {
Class<?> c = Class.forName("android.provider.ContactsContract$PhoneLookup");
baseUri = (Uri) c.getField("CONTENT_FILTER_URI").get(baseUri);
projection = new String[] { "display_name" };
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
uri = Uri.withAppendedPath(baseUri, Uri.encode(Uri
.encode(phoneNumber)));
Cursor cursor =mContext.getContentResolver().query(uri,
projection, null, null, null) ;
String fromDisplayName = null;
if (cursor != null) {
if (cursor.moveToFirst()){
fromDisplayName = cursor.getString(0);
}
else{
fromDisplayName="";
}
cursor.close();
} else {
fromDisplayName="";
}
return fromDisplayName;
The Uri android.provider.Contacts.People.NAME is deprecated. But android.provider.ContactsContract$PhoneLookup is available from API level 5 only. Hence it is better to use reflections to support all phones.
I am able to obtain a list of contacts and their basic information like: name. phones, emails, ims, notes, organizations for backup purposes by using ContactsContract.Contacts.CONTENT_URI for a list of Contacts and other specific URIs for different information type.
I need, in order to fully restore all the information two more fields:
ContactsContract.RawContacts.ACCOUNT_TYPE
ContactsContract.RawContacts.ACCOUNT_NAME
Can anyone guide me how to obtain this info, knowing the Contact Id from ContactsContract.Contacts.CONTENT_URI ?
Thank you
public ContactAccount getContactAccount(Long id,ContentResolver contentResolver) {
ContactAccount account = null;
Cursor cursor = null;
try {
cursor = contentResolver.query(ContactsContract.RawContacts.CONTENT_URI,
new String[]{ContactsContract.RawContacts.ACCOUNT_NAME, ContactsContract.RawContacts.ACCOUNT_TYPE},
ContactsContract.RawContacts.CONTACT_ID +"=?",
new String[]{String.valueOf(id)},
null);
if (cursor != null && cursor.getCount() >0)
{
cursor.moveToFirst();
account = new ContactAccount();
account.setAccountName(cursor.getString(cursor.getColumnIndex(ContactsContract.RawContacts.ACCOUNT_NAME)));
account.setAccountType(cursor.getString(cursor.getColumnIndex(ContactsContract.RawContacts.ACCOUNT_TYPE)));
cursor.close();
}
} catch (Exception e) {
Utils.log(this.getClass().getName(), e.getMessage());
} finally{
cursor.close();
}
return(account);
}
The above answer is perfect if you are looking for account information using the contactID column. But, often information is stored using rawContactID. So, if you want to access account information for a raw-contact-id then you can use this method below.
The key difference is that I am using the _ID column from the rawContacts table. This maps to the rawContactID that you will see in other tables
public int updateAccountInfoForContactData(String rawContactID) {
int accountPos = 0;
Cursor cursor = null;
String accountName = null;
String accountType = null;
Uri rawContactUri = ContactsContract.RawContacts.CONTENT_URI;
String[] syncColumns = new String[] {
ContactsContract.RawContacts.ACCOUNT_NAME,
ContactsContract.RawContacts.ACCOUNT_TYPE,
};
String whereClause = ContactsContract.RawContacts._ID +"=?";
String[] whereParams = new String[]{String.valueOf(rawContactID)};
//Uri rawContactUri = ContentUris.withAppendedId(ContactsContract.RawContacts.CONTENT_URI, longContactID);
try {
cursor = mContext.getContentResolver().query(
rawContactUri,
syncColumns,
whereClause,
whereParams,
null);
if (cursor != null && cursor.getCount() >0)
{
cursor.moveToFirst();
if(cursor.getColumnIndex(ContactsContract.RawContacts.ACCOUNT_NAME) >= 0) {
accountName = cursor.getString(cursor.getColumnIndex(ContactsContract.RawContacts.ACCOUNT_NAME));
}
if(cursor.getColumnIndex(ContactsContract.RawContacts.ACCOUNT_TYPE) >= 0) {
accountType = cursor.getString(cursor.getColumnIndex(ContactsContract.RawContacts.ACCOUNT_TYPE));
}
cursor.close();
cursor = null;
}
} catch (Exception e) {
Log.d(TAG, "getting account info failed");
} finally{
if(cursor != null) {
cursor.close();
}
cursor = null;
}
return(accountPos);
}