Example usage for android.content ContentProviderOperation newInsert

List of usage examples for android.content ContentProviderOperation newInsert

Introduction

In this page you can find the example usage for android.content ContentProviderOperation newInsert.

Prototype

public static Builder newInsert(Uri uri) 

Source Link

Document

Create a Builder suitable for building an insert ContentProviderOperation .

Usage

From source file:saschpe.birthdays.service.CalendarSyncService.java

/**
 * Returns birthday calendar ID.//  w  w  w .  j  a v  a2s . com
 *
 * If no calendar is present, a new one is created.
 *
 * @return calendar id
 */
public static long getCalendar(Context context) {
    final Uri calenderUri = getCalendarUri(context, CalendarContract.Calendars.CONTENT_URI);

    final String selection = CalendarContract.Calendars.ACCOUNT_NAME + " = ? AND "
            + CalendarContract.Calendars.ACCOUNT_TYPE + " = ? AND " + CalendarContract.Calendars.NAME + " = ?";
    final String calendarName = context.getString(R.string.calendar_name);

    ContentResolver cr = context.getContentResolver();
    Cursor cursor = cr.query(calenderUri, new String[] { BaseColumns._ID }, selection, new String[] {
            context.getString(R.string.app_name), context.getString(R.string.account_type), calendarName },
            null);

    if (cursor != null && cursor.moveToNext()) {
        // Yay, calendar exists already. Just return it's id.
        long calendarId = cursor.getLong(0);
        cursor.close();
        return calendarId;
    } else {
        if (cursor != null) {
            cursor.close();
        }

        // So we've got to create a calendar first before we can return it's id.
        ContentProviderOperation.Builder builder = ContentProviderOperation.newInsert(calenderUri);
        builder.withValue(CalendarContract.Calendars.ACCOUNT_NAME, context.getString(R.string.app_name));
        builder.withValue(CalendarContract.Calendars.ACCOUNT_TYPE, context.getString(R.string.account_type));
        builder.withValue(CalendarContract.Calendars.NAME, calendarName);
        builder.withValue(CalendarContract.Calendars.CALENDAR_DISPLAY_NAME,
                context.getString(R.string.birthdays_and_anniversaries));
        builder.withValue(CalendarContract.Calendars.CALENDAR_COLOR,
                PreferencesHelper.getCalendarColor(context));
        builder.withValue(CalendarContract.Calendars.SYNC_EVENTS, PreferencesHelper.isCalendarSynced(context));
        builder.withValue(CalendarContract.Calendars.VISIBLE, 1);
        if (BuildConfig.DEBUG) {
            builder.withValue(CalendarContract.Calendars.CALENDAR_ACCESS_LEVEL,
                    CalendarContract.Calendars.CAL_ACCESS_EDITOR);
        } else {
            builder.withValue(CalendarContract.Calendars.CALENDAR_ACCESS_LEVEL,
                    CalendarContract.Calendars.CAL_ACCESS_READ);
        }
        builder.withValue(CalendarContract.Calendars.OWNER_ACCOUNT, context.getString(R.string.app_name));

        ArrayList<ContentProviderOperation> operations = new ArrayList<>();
        operations.add(builder.build());
        try {
            cr.applyBatch(CalendarContract.AUTHORITY, operations);
            Log.d(TAG, "Created calendar " + calendarName);
        } catch (RemoteException e) {
            Log.e(TAG, "Unable to create new calendar!", e);
            return -1;
        } catch (OperationApplicationException e) {
            Log.e(TAG, "Unable to create new calendar!", e);
            return -2;
        }

        // Try once again, this time we should find something in the database
        return getCalendar(context);
    }
}

From source file:org.sufficientlysecure.keychain.provider.KeyWritableRepository.java

private void writePublicKeyRing(CanonicalizedPublicKeyRing keyRing, long masterKeyId,
        ArrayList<ContentProviderOperation> operations) throws IOException {
    byte[] encodedKey = keyRing.getEncoded();
    mLocalPublicKeyStorage.writePublicKey(masterKeyId, encodedKey);

    ContentValues values = new ContentValues();
    values.put(KeyRingData.MASTER_KEY_ID, masterKeyId);
    if (encodedKey.length < MAX_CACHED_KEY_SIZE) {
        values.put(KeyRingData.KEY_RING_DATA, encodedKey);
    } else {/*from  w  w w. ja  v a2s .  c om*/
        values.put(KeyRingData.KEY_RING_DATA, (byte[]) null);
    }

    Uri uri = KeyRingData.buildPublicKeyRingUri(masterKeyId);
    operations.add(ContentProviderOperation.newInsert(uri).withValues(values).build());
}

From source file:es.example.contacts.ui.ContactDetailFragment.java

/**
 * Builds an address LinearLayout based on address information from the Contacts Provider.
 * Each address for the contact gets its own LinearLayout object; for example, if the contact
 * has three postal addresses, then 3 LinearLayouts are generated.
 *
 * @param addressType From/* w w  w  .j a  va 2s . c  o m*/
 * {@link android.provider.ContactsContract.CommonDataKinds.StructuredPostal#TYPE}
 * @param addressTypeLabel From
 * {@link android.provider.ContactsContract.CommonDataKinds.StructuredPostal#LABEL}
 * @param address From
 * {@link android.provider.ContactsContract.CommonDataKinds.StructuredPostal#FORMATTED_ADDRESS}
 * @param phone From
 * {@link android.provider.ContactsContract.CommonDataKinds.Phone#NUMBER}
 * @param data1 From
 * {@link android.provider.ContactsContract.Data#DATA1}
 * @param _id From
 * {@link android.provider.ContactsContract#}
 * @return A LinearLayout to add to the contact details layout,
 *         populated with the provided address details.
 */
private LinearLayout buildAddressLayout(int addressType, String addressTypeLabel, final String address,
        final String phone, final String data1, final String _id, final String _name) {

    // Inflates the address layout
    final LinearLayout addressLayout = (LinearLayout) LayoutInflater.from(getActivity())
            .inflate(R.layout.contact_detail_item, mDetailsLayout, false);

    // Gets handles to the view objects in the layout
    final TextView headerTextView = (TextView) addressLayout.findViewById(R.id.contact_detail_header);
    final TextView addressTextView = (TextView) addressLayout.findViewById(R.id.contact_detail_item);
    final ImageButton viewAddressButton = (ImageButton) addressLayout.findViewById(R.id.button_view_address);
    final TextView phoneTextView = (TextView) addressLayout.findViewById(R.id.contact_phone);
    final SeekBar levelSeekBar = (SeekBar) addressLayout.findViewById(R.id.contact_level);
    final ImageButton saveButton = (ImageButton) addressLayout.findViewById(R.id.button_save);

    Integer prioridad = Integer.parseInt(data1 == null ? "4" : data1);
    // If there's no addresses for the contact, shows the empty view and message, and hides the
    // header and button.
    if (addressTypeLabel == null && addressType == 0 && phone == null) {
        headerTextView.setVisibility(View.GONE);
        viewAddressButton.setVisibility(View.GONE);
        addressTextView.setText(R.string.no_address);
    } else {
        // Gets postal address label type
        CharSequence label = StructuredPostal.getTypeLabel(getResources(), addressType, addressTypeLabel);

        // Sets TextView objects in the layout
        headerTextView.setText(label);
        addressTextView.setText(address);
        phoneTextView.setText(phone);
        levelSeekBar.setProgress(prioridad);

        // Defines an onClickListener object for the address button
        viewAddressButton.setOnClickListener(new View.OnClickListener() {
            // Defines what to do when users click the address button
            @Override
            public void onClick(View view) {

                final Intent viewIntent = new Intent(Intent.ACTION_VIEW, constructGeoUri(address));

                // A PackageManager instance is needed to verify that there's a default app
                // that handles ACTION_VIEW and a geo Uri.
                final PackageManager packageManager = getActivity().getPackageManager();

                // Checks for an activity that can handle this intent. Preferred in this
                // case over Intent.createChooser() as it will still let the user choose
                // a default (or use a previously set default) for geo Uris.
                if (packageManager.resolveActivity(viewIntent, PackageManager.MATCH_DEFAULT_ONLY) != null) {
                    startActivity(viewIntent);
                } else {
                    // If no default is found, displays a message that no activity can handle
                    // the view button.
                    Toast.makeText(getActivity(), R.string.no_intent_found, Toast.LENGTH_SHORT).show();
                }
            }
        });

        // Defines an onClickListener object for the save button
        saveButton.setOnClickListener(new View.OnClickListener() {
            // Defines what to do when users click the address button
            @Override
            public void onClick(View view) {
                // Creates a new intent for sending to the device's contacts application
                // Creates a new array of ContentProviderOperation objects.
                ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();

                Integer prioridad = levelSeekBar.getProgress();
                Log.d("ContactDetalFragment", _id);

                ContentProviderOperation.Builder op;
                if (data1 == null) {
                    Uri uri = addCallerIsSyncAdapterParameter(Data.CONTENT_URI, true);
                    ops.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
                            .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null)
                            .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null).build());

                    ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                            .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
                            .withValue(ContactsContract.Data.MIMETYPE,
                                    ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
                            .withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, _name)
                            .build());

                    op = ContentProviderOperation.newInsert(Data.CONTENT_URI)
                            .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
                            .withValue(Data.DATA1, prioridad).withValue(Data.MIMETYPE, LEVEL_MIME_TYPE);

                } else {
                    String where = Data.MIMETYPE + " = ? ";
                    String[] params = new String[] { LEVEL_MIME_TYPE, };

                    op = ContentProviderOperation.newUpdate(Data.CONTENT_URI).withSelection(where, params)
                            .withValue(Data.DATA1, prioridad);

                }
                ops.add(op.build());
                try {
                    ContentProviderResult[] results = view.getContext().getContentResolver()
                            .applyBatch(ContactsContract.AUTHORITY, ops);
                } catch (Exception e) {
                    CharSequence txt = getString(R.string.contactUpdateFailure);
                    int duration = Toast.LENGTH_SHORT;
                    Toast toast = Toast.makeText(view.getContext(), txt, duration);
                    toast.show();
                    // Log exception
                    Log.e(TAG, "Exception encountered while inserting contact: " + e);
                }
            }
        });

    }
    return addressLayout;
}

From source file:at.bitfire.vcard4android.AndroidContact.java

protected void insertStructuredName(BatchOperation batch) {
    ContentProviderOperation.Builder builder = ContentProviderOperation.newInsert(dataSyncURI());
    if (id == null)
        builder.withValueBackReference(StructuredName.RAW_CONTACT_ID, 0);
    else//  w ww.j  a  v a2  s . c o  m
        builder.withValue(StructuredName.RAW_CONTACT_ID, id);
    builder.withValue(RawContacts.Data.MIMETYPE, CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
            .withValue(StructuredName.PREFIX, contact.prefix)
            .withValue(StructuredName.DISPLAY_NAME, contact.displayName)
            .withValue(StructuredName.GIVEN_NAME, contact.givenName)
            .withValue(StructuredName.MIDDLE_NAME, contact.middleName)
            .withValue(StructuredName.FAMILY_NAME, contact.familyName)
            .withValue(StructuredName.SUFFIX, contact.suffix)
            .withValue(StructuredName.PHONETIC_GIVEN_NAME, contact.phoneticGivenName)
            .withValue(StructuredName.PHONETIC_MIDDLE_NAME, contact.phoneticMiddleName)
            .withValue(StructuredName.PHONETIC_FAMILY_NAME, contact.phoneticFamilyName);
    batch.enqueue(builder.build());
}

From source file:id.ridon.keude.UpdateService.java

private ContentProviderOperation insertNewApk(final Apk apk) {
    ContentValues values = apk.toContentValues();
    Uri uri = ApkProvider.getContentUri();
    return ContentProviderOperation.newInsert(uri).withValues(values).build();
}

From source file:com.chatwing.whitelabel.managers.ChatboxModeManager.java

@Subscribe
public void onCreateBookmarkEvent(CreateBookmarkEvent event) {
    if (handleCreateBookmarkException(event)) {
        return;//from   w w w  . j  av  a  2  s .c  om
    }
    ArrayList<ContentProviderOperation> batch = new ArrayList<ContentProviderOperation>();
    SyncedBookmark syncedBookmark = event.getResponse().getData();
    ChatBox chatBox = syncedBookmark.getChatBox();
    //Update local chatbox
    batch.add(ContentProviderOperation.newUpdate(ChatWingContentProvider.getChatBoxWithIdUri(chatBox.getId()))
            .withValues(ChatBoxTable.getContentValues(chatBox, null)).build());

    //Update local bookmarks
    int chatBoxId = chatBox.getId();
    syncedBookmark.setIsSynced(true);
    if (ChatWingContentProvider.hasSyncedBookmarkInDB(mActivityDelegate.getActivity().getContentResolver(),
            chatBoxId)) {
        //Update existing bookmark
        Uri syncedBookmarkWithChatBoxIdUri = ChatWingContentProvider
                .getSyncedBookmarkWithChatBoxIdUri(chatBoxId);
        batch.add(ContentProviderOperation.newUpdate(syncedBookmarkWithChatBoxIdUri)
                .withValues(SyncedBookmarkTable.getContentValues(syncedBookmark)).build());
    } else {
        //Somehow local bookmark is deleted, it should be add back
        Uri syncedBookmarksUri = ChatWingContentProvider.getSyncedBookmarksUri();
        batch.add(ContentProviderOperation.newInsert(syncedBookmarksUri)
                .withValues(SyncedBookmarkTable.getContentValues(syncedBookmark)).build());
    }

    try {
        mActivityDelegate.getActivity().getContentResolver().applyBatch(ChatWingContentProvider.AUTHORITY,
                batch);
    } catch (RemoteException e) {
        mActivityDelegate.handle(e, R.string.error_failed_to_save_bookmark);
    } catch (OperationApplicationException e) {
        mActivityDelegate.handle(e, R.string.error_failed_to_save_bookmark);
    }
}

From source file:id.ridon.keude.UpdateService.java

private ContentProviderOperation insertNewApp(App app) {
    ContentValues values = app.toContentValues();
    Uri uri = AppProvider.getContentUri();
    return ContentProviderOperation.newInsert(uri).withValues(values).build();
}

From source file:com.ubuntuone.android.files.service.MetaService.java

/**
 * Given parents resource path and {@link ArrayList} of {@link NodeInfo}s of
 * its children, syncs cached info of these children. Updating children in
 * one method enables us to make use of database transaction.<br />
 * <ul>//from   w ww.j a v a 2 s.c o m
 * <li>- inserts if child is new</li>
 * <li>- updates if child has changed [thus marks is_cached = false]</li>
 * <li>- deletes if child is missing [dead node]</li>
 * </ul>
 * 
 * @param parentResourcePath
 *            the resource path of childrens parent
 * @param children
 *            {@link NodeInfo}s of the parents children
 * @throws OperationApplicationException 
 * @throws RemoteException 
 */
public void getDirectoryNode(final String resourcePath, final ResultReceiver receiver) {
    Log.i(TAG, "getDirectoryNode()");
    final String[] projection = new String[] { Nodes._ID, Nodes.NODE_RESOURCE_PATH, Nodes.NODE_GENERATION,
            Nodes.NODE_DATA };
    final String selection = Nodes.NODE_RESOURCE_PATH + "=?";

    final Set<Integer> childrenIds = MetaUtilities.getChildrenIds(resourcePath);

    final ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>();

    final Bundle data = new Bundle();
    data.putString(EXTRA_RESOURCE_PATH, resourcePath);

    api.listDirectory(resourcePath, new U1NodeListener() {
        @Override
        public void onStart() {
            if (receiver != null)
                receiver.send(Status.RUNNING, data);
        }

        @Override
        public void onSuccess(U1Node node) {
            if (node.getKind() == U1NodeKind.FILE && ((U1File) node).getSize() == null) {
                // Ignore files with null size.
                return;
            }
            final String[] selectionArgs = new String[] { node.getResourcePath() };
            final Cursor c = contentResolver.query(Nodes.CONTENT_URI, projection, selection, selectionArgs,
                    null);
            try {
                ContentValues values = Nodes.valuesFromRepr(node);
                if (c.moveToFirst()) {
                    final int id = c.getInt(c.getColumnIndex(Nodes._ID));
                    // Node is live.
                    childrenIds.remove(id);

                    // Update node.
                    final long generation = c.getLong(c.getColumnIndex(Nodes.NODE_GENERATION));
                    final long newGeneration = node.getGeneration();
                    if (generation < newGeneration) {
                        Log.v(TAG, "updating child node, new generation");
                        values.put(Nodes.NODE_IS_CACHED, false);
                        values.put(Nodes.NODE_DATA, "");

                        String data = c.getString(c.getColumnIndex(Nodes.NODE_DATA));
                        FileUtilities.removeSilently(data);

                        Uri uri = MetaUtilities.buildNodeUri(id);
                        ContentProviderOperation op = ContentProviderOperation.newUpdate(uri).withValues(values)
                                .build();
                        operations.add(op);
                        if (operations.size() > 10) {
                            try {
                                contentResolver.applyBatch(MetaContract.CONTENT_AUTHORITY, operations);
                                operations.clear();
                            } catch (RemoteException e) {
                                Log.e(TAG, "Remote exception", e);
                            } catch (OperationApplicationException e) {
                                MetaUtilities.setIsCached(resourcePath, false);
                                return;
                            }
                            Thread.yield();
                        }
                    } else {
                        Log.v(TAG, "child up to date");
                    }
                } else {
                    // Insert node.
                    Log.v(TAG, "inserting child");
                    ContentProviderOperation op = ContentProviderOperation.newInsert(Nodes.CONTENT_URI)
                            .withValues(values).build();
                    operations.add(op);
                    if (operations.size() > 10) {
                        try {
                            contentResolver.applyBatch(MetaContract.CONTENT_AUTHORITY, operations);
                            operations.clear();
                        } catch (RemoteException e) {
                            Log.e(TAG, "Remote exception", e);
                        } catch (OperationApplicationException e) {
                            MetaUtilities.setIsCached(resourcePath, false);
                            return;
                        }
                        Thread.yield();
                    }
                }
            } finally {
                c.close();
            }
        }

        @Override
        public void onUbuntuOneFailure(U1Failure failure) {
            MetaService.this.onUbuntuOneFailure(failure, receiver);
        }

        @Override
        public void onFailure(U1Failure failure) {
            MetaService.this.onFailure(failure, receiver);
        }

        @Override
        public void onFinish() {
            if (receiver != null)
                receiver.send(Status.FINISHED, data);
        }
    });

    // Remove nodes, which ids are left in childrenIds set.
    if (!childrenIds.isEmpty()) {
        Log.v(TAG, "childrenIDs not empty: " + childrenIds.size());
        final Iterator<Integer> it = childrenIds.iterator();
        while (it.hasNext()) {
            int id = it.next();
            Uri uri = MetaUtilities.buildNodeUri(id);
            ContentProviderOperation op = ContentProviderOperation.newDelete(uri).build();
            operations.add(op);
        }
    } else {
        Log.v(TAG, "childrenIDs empty");
    }

    try {
        long then = System.currentTimeMillis();
        contentResolver.applyBatch(MetaContract.CONTENT_AUTHORITY, operations);
        MetaUtilities.setIsCached(resourcePath, true);
        long now = System.currentTimeMillis();
        Log.d(TAG, "time to update children: " + (now - then));
        contentResolver.notifyChange(Nodes.CONTENT_URI, null);
    } catch (RemoteException e) {
        Log.e(TAG, "", e);
    } catch (OperationApplicationException e) {
        MetaUtilities.setIsCached(resourcePath, false);
        return;
    }
}

From source file:com.rukman.emde.smsgroups.syncadapter.SyncAdapter.java

private long updateSyncRecord(ContentProviderClient provider)
        throws RemoteException, OperationApplicationException {
    ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
    ContentProviderOperation op = ContentProviderOperation.newInsert(GMSSyncs.CONTENT_URI)
            .withValue(GMSSync.SYNC_DATE, System.currentTimeMillis()).build();
    ops.add(op);/*from   ww  w. j a v a 2  s . c  om*/
    ContentProviderResult[] results = provider.applyBatch(ops);
    return (results[0].uri != null) ? ContentUris.parseId(results[0].uri) : -1L;
}

From source file:org.sufficientlysecure.keychain.util.ContactHelper.java

/**
 * Creates a empty raw contact with a given masterKeyId
 *//*from w ww.  j av a2s.c  om*/
private void insertContact(ArrayList<ContentProviderOperation> ops, long masterKeyId) {
    ops.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
            .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, Constants.ACCOUNT_NAME)
            .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, Constants.ACCOUNT_TYPE)
            .withValue(ContactsContract.RawContacts.SOURCE_ID, Long.toString(masterKeyId)).build());
}