Example usage for android.content ContentUris parseId

List of usage examples for android.content ContentUris parseId

Introduction

In this page you can find the example usage for android.content ContentUris parseId.

Prototype

public static long parseId(Uri contentUri) 

Source Link

Document

Converts the last path segment to a long.

Usage

From source file:at.bitfire.ical4android.AndroidEvent.java

public Uri add() throws CalendarStorageException {
    BatchOperation batch = new BatchOperation(calendar.provider);
    final int idxEvent = add(batch);
    batch.commit();// w  w  w. ja  v a2s  . co  m

    Uri uri = batch.getResult(idxEvent).uri;
    id = ContentUris.parseId(uri);

    return uri;
}

From source file:com.example.android.sunshine.app.service.SunshineService.java

/**
 * Helper method to handle insertion of a new location in the weather database.
 *
 * @param locationSetting The location string used to request updates from the server.
 * @param cityName A human-readable city name, e.g "Mountain View"
 * @param lat the latitude of the city/*from   w w  w  .  j a  v a2  s  . c  om*/
 * @param lon the longitude of the city
 * @return the row ID of the added location.
 */

long addLocation(String locationSetting, String cityName, double lat, double lon) {
    long locationId;

    // First, check if the location with this city name exists in the db
    Cursor locationCursor = this.getContentResolver().query(WeatherContract.LocationEntry.CONTENT_URI,
            new String[] { WeatherContract.LocationEntry._ID },
            WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING + " = ?", new String[] { locationSetting },
            null);

    if (locationCursor.moveToFirst()) {
        int locationIdIndex = locationCursor.getColumnIndex(WeatherContract.LocationEntry._ID);
        locationId = locationCursor.getLong(locationIdIndex);
    } else {
        // Now that the content provider is set up, inserting rows of data is pretty simple.
        // First create a ContentValues object to hold the data you want to insert.
        ContentValues locationValues = new ContentValues();

        // Then add the data, along with the corresponding name of the data type,
        // so the content provider knows what kind of value is being inserted.
        locationValues.put(WeatherContract.LocationEntry.COLUMN_CITY_NAME, cityName);
        locationValues.put(WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING, locationSetting);
        locationValues.put(WeatherContract.LocationEntry.COLUMN_COORD_LAT, lat);
        locationValues.put(WeatherContract.LocationEntry.COLUMN_COORD_LONG, lon);

        // Finally, insert location data into the database.
        Uri insertedUri = this.getContentResolver().insert(WeatherContract.LocationEntry.CONTENT_URI,
                locationValues);

        // The resulting URI contains the ID for the row.  Extract the locationId from the Uri.
        locationId = ContentUris.parseId(insertedUri);
    }

    locationCursor.close();
    // Wait, that worked?  Yes!
    return locationId;
}

From source file:ceruleanotter.github.com.sunshine.FetchWeatherTask.java

private long insertLocationInDatabase(String locationSetting, String cityName, double lat, double lon) {

    Log.v(LOG_TAG, "inserting " + cityName + ", with coord: " + lat + ", " + lon);

    // First, check if the location with this city name exists in the db
    Cursor cursor = mContext.getContentResolver().query(LocationEntry.CONTENT_URI,
            new String[] { LocationEntry._ID }, LocationEntry.COLUMN_LOCATION_SETTING + " = ?",
            new String[] { locationSetting }, null);

    if (cursor.moveToFirst()) {
        Log.v(LOG_TAG, "Found it in the database!");
        int locationIdIndex = cursor.getColumnIndex(LocationEntry._ID);
        return cursor.getLong(locationIdIndex);
    } else {//  w w w  .j a v a2s.co  m
        Log.v(LOG_TAG, "Didn't find it in the database, inserting now!");
        ContentValues locationValues = new ContentValues();
        locationValues.put(LocationEntry.COLUMN_LOCATION_SETTING, locationSetting);
        locationValues.put(LocationEntry.COLUMN_CITY_NAME, cityName);
        locationValues.put(LocationEntry.COLUMN_COORD_LAT, lat);
        locationValues.put(LocationEntry.COLUMN_COORD_LONG, lon);

        Uri locationInsertUri = mContext.getContentResolver().insert(LocationEntry.CONTENT_URI, locationValues);

        return ContentUris.parseId(locationInsertUri);
    }
}

From source file:cz.maresmar.sfm.view.guide.WelcomeActivity.java

@UiThread
private void tryToMoveToNextPage() {
    Timber.i("FAB clicked on page %d", mViewPager.getCurrentItem());

    if (mViewPager.getCurrentItem() == HELP_FRAGMENT_ID) {
        startMainActivity();//  w  w  w .j  a  va 2 s . c o m
        return;
    }

    DataForm formFragment = (DataForm) mPagerAdapter.getFragment(mViewPager.getCurrentItem());
    if (formFragment == null) {
        // Skipping move forward when doing onRestoreInstanceState
        return;
    }
    if (formFragment.hasValidData()) {
        switch (mViewPager.getCurrentItem()) {
        case WELCOME_FRAGMENT_ID:
            moveToNextPage();
            break;
        case USER_FRAGMENT_ID: {
            mUserUri = formFragment.saveData();
            moveToNextPage();
            break;
        }
        case PORTAL_FRAGMENT_ID: {
            PortalDetailFragment portalDetailFragment = (PortalDetailFragment) formFragment;
            ((PortalDetailFragment) formFragment).saveAndTestData();
            mActiveToast = Toast.makeText(this, R.string.portal_checking_portal_data, Toast.LENGTH_LONG);
            mActiveToast.show();
            mSwipeRefreshLayout.setRefreshing(true);
            break;
        }
        case CREDENTIALS_FRAGMENT_ID: {
            CredentialDetailFragment credentialDetailFragment = (CredentialDetailFragment) formFragment;
            Uri credentialUri = credentialDetailFragment.saveData();
            mValidatedCredentialId = ContentUris.parseId(credentialUri);
            // Start plugin
            SyncHandler.startFullSync(this);
            mActiveToast = Toast.makeText(getBaseContext(), R.string.credential_detail_checking_credential_data,
                    Toast.LENGTH_LONG);
            mActiveToast.show();
            mSwipeRefreshLayout.setRefreshing(true);
            break;
        }
        default:
            throw new UnsupportedOperationException("Unsupported page " + mViewPager.getCurrentItem());

        }
    }
}

From source file:org.gege.caldavsyncadapter.caldav.entities.DavCalendar.java

/**
 * creates a new androidCalendar/*from   ww w. j a v a  2s.c o m*/
 * @param serverCalendar
 * @param index
 * @param context
 * @return the new androidCalendar or null if fails
 */
private DavCalendar createNewAndroidCalendar(DavCalendar serverCalendar, int index,
        android.content.Context context) {
    Uri newUri = null;
    DavCalendar Result = null;

    final ContentValues contentValues = new ContentValues();
    contentValues.put(DavCalendar.URI, serverCalendar.getURI().toString());
    contentValues.put(DavCalendar.SERVERURL, this.ServerUrl);

    contentValues.put(Calendars.VISIBLE, 1);
    contentValues.put(Calendars.CALENDAR_DISPLAY_NAME, serverCalendar.getCalendarDisplayName());
    contentValues.put(Calendars.ACCOUNT_NAME, mAccount.name);
    contentValues.put(Calendars.ACCOUNT_TYPE, mAccount.type);
    contentValues.put(Calendars.OWNER_ACCOUNT, mAccount.name);
    contentValues.put(Calendars.SYNC_EVENTS, 1);
    contentValues.put(Calendars.CALENDAR_ACCESS_LEVEL, Calendars.CAL_ACCESS_OWNER);

    if (!serverCalendar.getCalendarColorAsString().equals("")) {
        contentValues.put(Calendars.CALENDAR_COLOR, serverCalendar.getCalendarColor());
    } else {
        // find a color
        //int index = mList.size();
        index = index % CalendarColors.colors.length;
        contentValues.put(Calendars.CALENDAR_COLOR, CalendarColors.colors[index]);
    }

    try {
        newUri = mProvider.insert(asSyncAdapter(Calendars.CONTENT_URI, mAccount.name, mAccount.type),
                contentValues);
    } catch (RemoteException e) {
        e.printStackTrace();
    }

    // it is possible that this calendar already exists but the provider failed to find it within isCalendarExist()
    // the adapter would try to create a new calendar but the provider fails again to create a new calendar.
    if (newUri != null) {
        long newCalendarId = ContentUris.parseId(newUri);

        Cursor cur = null;
        Uri uri = Calendars.CONTENT_URI;
        String selection = "(" + Calendars._ID + " = ?)";
        String[] selectionArgs = new String[] { String.valueOf(newCalendarId) };

        // Submit the query and get a Cursor object back. 
        try {
            cur = mProvider.query(uri, null, selection, selectionArgs, null);
        } catch (RemoteException e) {
            e.printStackTrace();
        }

        if (cur != null) {
            while (cur.moveToNext()) {
                Result = new DavCalendar(mAccount, mProvider, cur, this.Source, this.ServerUrl);
                Result.foundServerSide = true;
            }
            cur.close();
            //if (Result != null)
            //   this.mList.add(Result);
        }
        Log.i(TAG, "New calendar created : URI=" + Result.getAndroidCalendarUri());
        NotificationsHelper.signalSyncErrors(context, "CalDAV Sync Adapter",
                "new calendar found: " + Result.getCalendarDisplayName());
        mNotifyList.add(Result.getAndroidCalendarUri());
    }

    return Result;
}

From source file:com.example.bdcoe.sunshine.FetchWeatherTask.java

private long addLocation(String locationSetting, String cityName, double lat, double lon) {
    Log.v(LOG_TAG, "inserting " + cityName + ", with coord: " + lat + ", " + lon);

    // First, check if the location with this city name exists in the db
    Cursor cursor = mContext.getContentResolver().query(WeatherContract.LocationEntry.CONTENT_URI,
            new String[] { WeatherContract.LocationEntry._ID },
            WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING + " = ?", new String[] { locationSetting },
            null);// ww w .ja  va 2  s .c  om
    if (cursor.moveToFirst()) {
        Log.v(LOG_TAG, "Found it in the database!");
        int locationIdIndex = cursor.getColumnIndex(WeatherContract.LocationEntry._ID);
        return cursor.getLong(locationIdIndex);
    } else {
        Log.v(LOG_TAG, "Didn't find it in the database, inserting now!");
        ContentValues locationValues = new ContentValues();
        locationValues.put(WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING, locationSetting);
        locationValues.put(WeatherContract.LocationEntry.COLUMN_CITY_NAME, cityName);
        locationValues.put(WeatherContract.LocationEntry.COLUMN_COORD_LAT, lat);
        locationValues.put(WeatherContract.LocationEntry.COLUMN_COORD_LONG, lon);

        Uri locationInsertUri = mContext.getContentResolver().insert(WeatherContract.LocationEntry.CONTENT_URI,
                locationValues);

        return ContentUris.parseId(locationInsertUri);

    }
}

From source file:mobisocial.socialkit.musubi.Musubi.java

/**
 * Returns all DbIdentities owned by the current user
 *//*from w w w.  jav a 2s.c om*/
public List<DbIdentity> users(Uri feedUri) {
    Uri uri;
    if (feedUri == null) {
        uri = uriForDir(DbThing.IDENTITY);
    } else {
        long feedId = ContentUris.parseId(feedUri);
        uri = uriForItem(DbThing.MEMBER, feedId);
    }
    String selection = DbIdentity.COL_OWNED + " = 1";
    String[] selectionArgs = null;
    String sortOrder = null;
    Cursor c = mContext.getContentResolver().query(uri, DbIdentity.COLUMNS, selection, selectionArgs,
            sortOrder);
    try {
        List<DbIdentity> identities = new LinkedList<DbIdentity>();
        if (c == null || c.getCount() == 0) {
            Log.w(TAG, "no local user for feed " + feedUri, new Throwable());
            return identities;
        }
        while (c.moveToNext()) {
            DbIdentity id = DbIdentity.fromStandardCursor(mContext, c);
            identities.add(id);
        }
        return identities;
    } finally {
        if (c != null) {
            c.close();
        }
    }
}

From source file:net.sf.diningout.content.SyncAdapter.java

/**
 * Insert new system contacts, delete orphaned app contacts, and synchronise any changes to
 * existing./* w  w  w. ja  v  a2s . co m*/
 */
private void refreshContacts(Context context, ContentProviderClient cp) throws RemoteException {
    /* get system contacts */
    String[] proj = { Email.ADDRESS, ContactsContract.Contacts.LOOKUP_KEY, RawContacts.CONTACT_ID,
            ContactsContract.Contacts.DISPLAY_NAME };
    String sel = Email.IN_VISIBLE_GROUP + " = 1 AND " + Email.ADDRESS + " <> ?";
    String[] args = { Accounts.selected().name };
    EasyCursor sys = new EasyCursor(cr().query(Email.CONTENT_URI, proj, sel, args, Email.ADDRESS));
    /* get app contacts */
    proj = new String[] { Contacts.EMAIL, Contacts.ANDROID_LOOKUP_KEY, Contacts.ANDROID_ID, Contacts.NAME, _ID,
            Contacts.FOLLOWING, Contacts.STATUS_ID };
    sel = Contacts.EMAIL + " IS NOT NULL";
    EasyCursor app = new EasyCursor(cp.query(CONTACTS_URI, proj, sel, null, Contacts.EMAIL));
    /* compare and sync */
    ContentValues vals = new ContentValues();
    for (CursorJoiner.Result result : new CursorJoiner(sys, new String[] { Email.ADDRESS }, app,
            new String[] { Contacts.EMAIL })) {
        switch (result) {
        case LEFT: // new system contact, insert into app contacts
            String email = sys.getString(Email.ADDRESS);
            String hash = BaseEncoding.base64()
                    .encode(Hashing.sha512().hashString(email.toLowerCase(ENGLISH), UTF_8).asBytes());
            long id = Contacts.idForHash(hash); // do we have this contact and not know it?
            /* insert or update values */
            vals.put(Contacts.ANDROID_LOOKUP_KEY, sys.getString(ContactsContract.Contacts.LOOKUP_KEY));
            vals.put(Contacts.ANDROID_ID, sys.getLong(RawContacts.CONTACT_ID));
            String name = sys.getString(ContactsContract.Contacts.DISPLAY_NAME);
            vals.put(Contacts.NAME, name);
            vals.put(Contacts.NORMALISED_NAME, SQLite.normalise(name));
            vals.put(Contacts.EMAIL, email);
            if (id <= 0) {
                vals.put(Contacts.EMAIL_HASH, hash);
                vals.put(Contacts.COLOR, Contacts.defaultColor());
                id = ContentUris.parseId(cp.insert(CONTACTS_URI, vals));
            } else {
                cp.update(ContentUris.withAppendedId(CONTACTS_URI, id), vals, null, null);
            }
            if (id > 0) {
                context.startService(new Intent(context, FriendColorService.class)
                        .putExtra(FriendColorService.EXTRA_ID, id));
            }
            break;
        case RIGHT: // orphaned app contact, delete unless user is following
            if (app.getInt(Contacts.FOLLOWING) == 0 && app.getInt(Contacts.STATUS_ID) == ACTIVE.id) {
                vals.put(Contacts.STATUS_ID, DELETED.id);
                vals.put(Contacts.DIRTY, 1);
                cp.update(Uris.appendId(CONTACTS_URI, app), vals, null, null);
            }
            break;
        case BOTH: // matching contacts, update details in app if needed
            String s = sys.getString(ContactsContract.Contacts.LOOKUP_KEY);
            if (!s.equals(app.getString(Contacts.ANDROID_LOOKUP_KEY))) {
                vals.put(Contacts.ANDROID_LOOKUP_KEY, s);
            }
            long l = sys.getLong(RawContacts.CONTACT_ID);
            if (l != app.getLong(Contacts.ANDROID_ID)) {
                vals.put(Contacts.ANDROID_ID, l);
            }
            s = sys.getString(ContactsContract.Contacts.DISPLAY_NAME);
            if (!s.equals(app.getString(Contacts.NAME))) {
                vals.put(Contacts.NAME, s);
                vals.put(Contacts.NORMALISED_NAME, SQLite.normalise(s));
            }
            if (app.getInt(Contacts.STATUS_ID) == DELETED.id) {
                vals.put(Contacts.STATUS_ID, ACTIVE.id);
                vals.put(Contacts.DIRTY, 1);
            }
            if (vals.size() > 0) {
                cp.update(Uris.appendId(CONTACTS_URI, app), vals, null, null);
                context.startService(new Intent(context, FriendColorService.class)
                        .putExtra(FriendColorService.EXTRA_ID, app.getLong(_ID)));
            }
            break;
        }
        vals.clear();
    }
    sys.close();
    app.close();
}

From source file:org.gege.caldavsyncadapter.caldav.entities.CalendarEvent.java

private ContentValues ReadAttendeeProperties(Property property, String Type) {
    ContentValues Attendee = null;/*from  w  w w. j  a  v  a  2  s  .  c  om*/

    ParameterList Parameters = property.getParameters();
    Parameter CN = Parameters.getParameter(Cn.CN);
    Parameter ROLE = Parameters.getParameter(Role.ROLE);
    Parameter CUTYPE = Parameters.getParameter(CuType.CUTYPE);
    //Parameter RSVP     = Parameters.getParameter("RSVP");
    Parameter PARTSTAT = Parameters.getParameter(PartStat.PARTSTAT);

    String strCN = "";
    String strROLE = "";
    String strCUTYPE = "";
    String strValue = property.getValue().replace("mailto:", "");
    String strPARTSTAT = "";

    if (strValue.startsWith(mstrcIcalPropertyError)) {
        strValue = strValue.replace(mstrcIcalPropertyError, "");
        try {
            strValue = URLDecoder.decode(strValue, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    if (CN != null)
        strCN = CN.getValue();
    if (ROLE != null)
        strROLE = ROLE.getValue();
    if (CUTYPE != null)
        strCUTYPE = CUTYPE.getValue();
    if (PARTSTAT != null)
        strPARTSTAT = PARTSTAT.getValue();

    if (strCN.equals("")) {
        if (!strValue.equals("")) {
            strCN = strValue;
        }
    }

    if (!strCN.equals("")) {
        if (strCUTYPE.equals("") || strCUTYPE.equals("INDIVIDUAL")) {
            Attendee = new ContentValues();

            Attendee.put(Attendees.EVENT_ID, ContentUris.parseId(mAndroidEventUri));

            Attendee.put(Attendees.ATTENDEE_NAME, strCN);
            Attendee.put(Attendees.ATTENDEE_EMAIL, strValue);

            if (strROLE.equals("OPT-PARTICIPANT"))
                Attendee.put(Attendees.ATTENDEE_TYPE, Attendees.TYPE_OPTIONAL);
            else if (strROLE.equals("NON-PARTICIPANT"))
                Attendee.put(Attendees.ATTENDEE_TYPE, Attendees.TYPE_NONE);
            else if (strROLE.equals("REQ-PARTICIPANT"))
                Attendee.put(Attendees.ATTENDEE_TYPE, Attendees.TYPE_REQUIRED);
            else if (strROLE.equals("CHAIR"))
                Attendee.put(Attendees.ATTENDEE_TYPE, Attendees.TYPE_REQUIRED);
            else
                Attendee.put(Attendees.ATTENDEE_TYPE, Attendees.TYPE_NONE);

            if (Type.equals(Property.ATTENDEE))
                Attendee.put(Attendees.ATTENDEE_RELATIONSHIP, Attendees.RELATIONSHIP_ATTENDEE);
            else if (Type.equals(Property.ORGANIZER))
                Attendee.put(Attendees.ATTENDEE_RELATIONSHIP, Attendees.RELATIONSHIP_ORGANIZER);
            else
                Attendee.put(Attendees.ATTENDEE_RELATIONSHIP, Attendees.RELATIONSHIP_NONE);

            if (strPARTSTAT.equals(PartStat.NEEDS_ACTION.getValue()))
                Attendee.put(Attendees.ATTENDEE_STATUS, Attendees.ATTENDEE_STATUS_INVITED);
            else if (strPARTSTAT.equals(PartStat.ACCEPTED.getValue()))
                Attendee.put(Attendees.ATTENDEE_STATUS, Attendees.ATTENDEE_STATUS_ACCEPTED);
            else if (strPARTSTAT.equals(PartStat.DECLINED.getValue()))
                Attendee.put(Attendees.ATTENDEE_STATUS, Attendees.ATTENDEE_STATUS_DECLINED);
            else if (strPARTSTAT.equals(PartStat.COMPLETED.getValue()))
                Attendee.put(Attendees.ATTENDEE_STATUS, Attendees.ATTENDEE_STATUS_NONE);
            else if (strPARTSTAT.equals(PartStat.TENTATIVE.getValue()))
                Attendee.put(Attendees.ATTENDEE_STATUS, Attendees.ATTENDEE_STATUS_TENTATIVE);
            else
                Attendee.put(Attendees.ATTENDEE_STATUS, Attendees.ATTENDEE_STATUS_INVITED);

        }
    }

    return Attendee;
}

From source file:com.fututel.db.DBProvider.java

@Override
public Uri insert(Uri uri, ContentValues initialValues) {
    int matched = URI_MATCHER.match(uri);
    String matchedTable = null;//from   w ww.j av  a  2  s.  c om
    Uri baseInsertedUri = null;
    switch (matched) {
    case ACCOUNTS:
    case ACCOUNTS_ID:
        matchedTable = SipProfile.ACCOUNTS_TABLE_NAME;
        baseInsertedUri = SipProfile.ACCOUNT_ID_URI_BASE;
        break;
    case CALLLOGS:
    case CALLLOGS_ID:
        matchedTable = SipManager.CALLLOGS_TABLE_NAME;
        baseInsertedUri = SipManager.CALLLOG_ID_URI_BASE;
        break;
    case FILTERS:
    case FILTERS_ID:
        matchedTable = SipManager.FILTERS_TABLE_NAME;
        baseInsertedUri = SipManager.FILTER_ID_URI_BASE;
        break;
    case MESSAGES:
    case MESSAGES_ID:
        matchedTable = SipMessage.MESSAGES_TABLE_NAME;
        baseInsertedUri = SipMessage.MESSAGE_ID_URI_BASE;
        break;
    case ACCOUNTS_STATUS_ID:
        long id = ContentUris.parseId(uri);
        synchronized (profilesStatus) {
            SipProfileState ps = new SipProfileState();
            if (profilesStatus.containsKey(id)) {
                ContentValues currentValues = profilesStatus.get(id);
                ps.createFromContentValue(currentValues);
            }
            ps.createFromContentValue(initialValues);
            ContentValues cv = ps.getAsContentValue();
            cv.put(SipProfileState.ACCOUNT_ID, id);
            profilesStatus.put(id, cv);
            Log.d(THIS_FILE, "Added " + cv);
        }
        getContext().getContentResolver().notifyChange(uri, null);
        return uri;
    default:
        break;
    }

    if (matchedTable == null) {
        throw new IllegalArgumentException(UNKNOWN_URI_LOG + uri);
    }

    ContentValues values;

    if (initialValues != null) {
        values = new ContentValues(initialValues);
    } else {
        values = new ContentValues();
    }

    SQLiteDatabase db = mOpenHelper.getWritableDatabase();

    long rowId = db.insert(matchedTable, null, values);

    // If the insert succeeded, the row ID exists.
    if (rowId >= 0) {
        // TODO : for inserted account register it here

        Uri retUri = ContentUris.withAppendedId(baseInsertedUri, rowId);
        getContext().getContentResolver().notifyChange(retUri, null);

        if (matched == ACCOUNTS || matched == ACCOUNTS_ID) {
            broadcastAccountChange(rowId);
        }
        if (matched == CALLLOGS || matched == CALLLOGS_ID) {
            db.delete(SipManager.CALLLOGS_TABLE_NAME,
                    CallLog.Calls._ID + " IN " + "(SELECT " + CallLog.Calls._ID + " FROM "
                            + SipManager.CALLLOGS_TABLE_NAME + " ORDER BY " + CallLog.Calls.DEFAULT_SORT_ORDER
                            + " LIMIT -1 OFFSET 500)",
                    null);
        }
        if (matched == ACCOUNTS_STATUS || matched == ACCOUNTS_STATUS_ID) {
            broadcastRegistrationChange(rowId);
        }
        if (matched == FILTERS || matched == FILTERS_ID) {
            Filter.resetCache();
        }

        return retUri;
    }

    throw new SQLException("Failed to insert row into " + uri);
}