0

I am having an issue with selecting an account using the CalendarContract API. I get the following error:

Caused by: android.database.sqlite.SQLiteException: near "@iancorneli": syntax error (code 1): , while compiling: SELECT _id FROM Calendars WHERE (account_name = me@iancorneli.us account_type = LOCAL )

The code is as follows:

private void getAccounts() {
    AccountManager manager = AccountManager.get(context);
    Account[] accounts = manager.getAccountsByType("com.google");

    for (Account account : accounts) {
        accountName = account.name;
        accountType = account.type;
        break;
    }
}

private long getCalendarID() {
    getAccounts();
    String[] projection = new String[]{CalendarContract.Calendars._ID}; 
    String selection = 
        CalendarContract.Calendars.ACCOUNT_NAME + 
        " = " + accountName + " " + 
        CalendarContract.Calendars.ACCOUNT_TYPE + 
        " = " + CalendarContract.ACCOUNT_TYPE_LOCAL + " "; 
    String[] selArgs = 
        new String[]{
            CalendarContract.Calendars.ACCOUNT_NAME, 
            CalendarContract.ACCOUNT_TYPE_LOCAL
    }; 
    Cursor cursor = context.getContentResolver().query(
        CalendarContract.Calendars.CONTENT_URI, 
        projection, 
        selection, 
        selArgs, 
        null
    ); 
    if (cursor.moveToFirst()) { 
        return cursor.getLong(0); 
    } 
    return -1; 
}

Any assistance as to where I am going wrong?

1 Answers1

0

You seem to be using the selection args wrong - there should be a ? in your selection and those ? are replaced with the values from the selection args, wrapping them in quotes if necessary automatically:

String selection = 
    CalendarContract.Calendars.ACCOUNT_NAME + 
    " =? AND " + 
    CalendarContract.Calendars.ACCOUNT_TYPE + 
    " =?"; 
String[] selArgs = 
    new String[]{
        accountName, 
        CalendarContract.ACCOUNT_TYPE_LOCAL
}; 
ianhanniballake
  • 191,609
  • 30
  • 470
  • 443