Example usage for android.content ContentResolver insert

List of usage examples for android.content ContentResolver insert

Introduction

In this page you can find the example usage for android.content ContentResolver insert.

Prototype

public final @Nullable Uri insert(@RequiresPermission.Write @NonNull Uri url, @Nullable ContentValues values) 

Source Link

Document

Inserts a row into a table at the given URL.

Usage

From source file:com.akop.bach.parser.PsnUsParser.java

protected void parseFriendSummary(PsnAccount account, String friendOnlineId)
        throws ParserException, IOException {
    long updated = System.currentTimeMillis();
    long started = updated;

    GamerProfileInfo gpi = parseGamerProfile(account, friendOnlineId);

    ContentResolver cr = mContext.getContentResolver();
    Cursor c = cr.query(Friends.CONTENT_URI, FRIEND_ID_PROJECTION,
            Friends.ACCOUNT_ID + "=" + account.getId() + " AND " + Friends.ONLINE_ID + "=?",
            new String[] { friendOnlineId }, null);

    long friendId = -1;

    try {/*  w  w  w. j a v a 2  s .c  om*/
        if (c != null && c.moveToFirst())
            friendId = c.getLong(0);
    } finally {
        if (c != null)
            c.close();
    }

    ContentValues cv = new ContentValues(15);

    cv.put(Friends.ONLINE_ID, gpi.OnlineId);
    cv.put(Friends.ICON_URL, gpi.AvatarUrl);
    cv.put(Friends.LEVEL, gpi.Level);
    cv.put(Friends.PROGRESS, gpi.Progress);
    cv.put(Friends.ONLINE_STATUS, gpi.OnlineStatus);
    cv.put(Friends.TROPHIES_PLATINUM, gpi.PlatinumTrophies);
    cv.put(Friends.TROPHIES_GOLD, gpi.GoldTrophies);
    cv.put(Friends.TROPHIES_SILVER, gpi.SilverTrophies);
    cv.put(Friends.TROPHIES_BRONZE, gpi.BronzeTrophies);
    cv.put(Friends.PLAYING, gpi.Playing);
    cv.put(Friends.LAST_UPDATED, updated);

    if (friendId < 0) {
        // New
        cv.put(Friends.ACCOUNT_ID, account.getId());
        cr.insert(Friends.CONTENT_URI, cv);
    } else {
        cr.update(ContentUris.withAppendedId(Friends.CONTENT_URI, friendId), cv, null, null);
    }

    if (App.getConfig().logToConsole())
        started = displayTimeTaken("Friend page processing", started);

    cr.notifyChange(ContentUris.withAppendedId(Friends.CONTENT_URI, friendId), null);
}

From source file:com.ichi2.anki.tests.ContentProviderTest.java

/**
 * Check that an Exception is thrown when unsupported operations are performed
 *///from   w w w  . j a va2s .co m
public void testUnsupportedOperations() {
    final ContentResolver cr = getContext().getContentResolver();
    ContentValues dummyValues = new ContentValues();
    Uri[] updateUris = {
            // Can't update most tables in bulk -- only via ID
            FlashCardsContract.Note.CONTENT_URI, FlashCardsContract.Model.CONTENT_URI,
            FlashCardsContract.Deck.CONTENT_ALL_URI,
            FlashCardsContract.Note.CONTENT_URI.buildUpon().appendPath("1234").appendPath("cards").build(), };
    for (Uri uri : updateUris) {
        try {
            cr.update(uri, dummyValues, null, null);
            fail("Update on " + uri + " was supposed to throw exception");
        } catch (UnsupportedOperationException e) {
            // This was expected ...
        } catch (IllegalArgumentException e) {
            // ... or this.
        }
    }
    Uri[] deleteUris = { FlashCardsContract.Note.CONTENT_URI,
            // Only note/<id> is supported
            FlashCardsContract.Note.CONTENT_URI.buildUpon().appendPath("1234").appendPath("cards").build(),
            FlashCardsContract.Note.CONTENT_URI.buildUpon().appendPath("1234").appendPath("cards")
                    .appendPath("2345").build(),
            FlashCardsContract.Model.CONTENT_URI,
            FlashCardsContract.Model.CONTENT_URI.buildUpon().appendPath("1234").build(), };
    for (Uri uri : deleteUris) {
        try {
            cr.delete(uri, null, null);
            fail("Delete on " + uri + " was supposed to throw exception");
        } catch (UnsupportedOperationException e) {
            // This was expected
        }
    }
    Uri[] insertUris = {
            // Can't do an insert with specific ID on the following tables
            FlashCardsContract.Note.CONTENT_URI.buildUpon().appendPath("1234").build(),
            FlashCardsContract.Note.CONTENT_URI.buildUpon().appendPath("1234").appendPath("cards").build(),
            FlashCardsContract.Note.CONTENT_URI.buildUpon().appendPath("1234").appendPath("cards")
                    .appendPath("2345").build(),
            FlashCardsContract.Model.CONTENT_URI.buildUpon().appendPath("1234").build(), };
    for (Uri uri : insertUris) {
        try {
            cr.insert(uri, dummyValues);
            fail("Insert on " + uri + " was supposed to throw exception");
        } catch (UnsupportedOperationException e) {
            // This was expected ...
        } catch (IllegalArgumentException e) {
            // ... or this.
        }
    }
}

From source file:com.hhunj.hhudata.SearchBookContentsActivity.java

public void updatedb(List<SearchBookContentsResult> items) {
    int max_alarm_time_span = 60;
    ContentResolver resolver = getApplicationContext().getContentResolver();

    ContentValues values = new ContentValues();

    for (int i = 0; i < items.size(); i++) {

        SearchBookContentsResult res = items.get(i);
        long stationid = Long.parseLong(res.getPageNumber());

        values.put(NotePad.Notes.TITLE, res.getName());
        values.put(NotePad.Notes.NOTE, "");

        values.put(NotePad.Notes.LONGITUTE, 108.0);
        values.put(NotePad.Notes.LATITUDE, 32.0);
        values.put(NotePad.Notes.SPEED, 55);
        values.put(NotePad.Notes.ALTITUDE, 55);

        values.put(NotePad.Notes.CREATEDDATE, res.getRectime().getTime());

        values.put(NotePad.Notes._ID, stationid);//id

        Uri urlNote = NotePad.Notes.CONTENT_URI;

        Uri myUri = ContentUris.withAppendedId(NotePad.Notes.CONTENT_URI, stationid);

        Cursor cur = resolver.query(myUri, NotePad.Notes.PROJECTION, null, null, null);

        if (cur != null && cur.moveToFirst()) {
            try {
                long id = cur.getLong(NotePad.Notes._ID_COLUMN);
                Date oldtime = new Date(cur.getLong(cur.getColumnIndex(NotePad.Notes.CREATEDDATE)));
                boolean oldalarm = (cur.getInt(NotePad.Notes.ALARM_COLUMN) == 0) ? false : true;

                long dif = (res.getRectime().getTime() - oldtime.getTime()) / (60 * 1000);

                dif = ((new Date()).getTime() - oldtime.getTime()) / (60 * 1000);

                if (dif > max_alarm_time_span) {
                    //...
                    if (oldalarm == false) {
                        Log.w(TAG, "over time err--------");
                        String phoneNumber = "13338620269";
                        String message = "over time err--------";
                        sendSMS(phoneNumber, message);
                        values.put(NotePad.Notes.ALARM, true);
                    }//from www  . j  a v a 2  s  . co m

                } else {
                    values.put(NotePad.Notes.ALARM, false);
                }

            } catch (Exception e) {
                int aa = 0;

            }

            int count = resolver.update(myUri, values, null, null);
            //  resolver.update( myUri, values, NotePad.Notes._ID + " = " +res.getPageNumber(), null);
            if (count == 0) {

            }
        } else {
            try {
                myUri = resolver.insert(urlNote, values);
            } catch (IllegalArgumentException e) {
                throw e;
            }
        }
    }

}

From source file:de.vanita5.twittnuker.util.Utils.java

public static ParcelableStatus findStatus(final Context context, final long account_id, final long status_id)
        throws TwitterException {
    if (context == null || account_id <= 0 || status_id <= 0)
        return null;
    final ParcelableStatus p_status = findStatusInDatabases(context, account_id, status_id);
    if (p_status != null)
        return p_status;
    final Twitter twitter = getTwitterInstance(context, account_id, true);
    if (twitter == null)
        return null;
    final Status status = twitter.showStatus(status_id);
    if (status == null || status.getId() <= 0)
        return null;
    final String where = Statuses.ACCOUNT_ID + " = " + account_id + " AND " + Statuses.STATUS_ID + " = "
            + status.getId();//from   w ww .  j  a  v  a 2  s  . c  om
    final ContentResolver resolver = context.getContentResolver();
    resolver.delete(CachedStatuses.CONTENT_URI, where, null);
    resolver.insert(CachedStatuses.CONTENT_URI,
            ContentValuesCreator.makeStatusContentValues(status, account_id));
    return new ParcelableStatus(status, account_id, false);
}

From source file:com.stockita.stockitapointofsales.salespack.pendingpack.SalesPendingListFragmentUI.java

/**
 * This method will insert the current Sales Detail Pending into a local database
 * so later can be query by {@link SalesPendingCheckoutDialogFragment}
 *//*from w  w  w.j  a va 2 s.  c  o  m*/
private void packTheCurrentSalesDetailPendingInToLocalDatabase() {

    // Delete all data in the local database before we insert new data
    final ContentResolver contentResolver = getActivity().getContentResolver();
    contentResolver.delete(ContractData.SalesDetailPendingEntry.CONTENT_URI, null, null);

    // Get the reference to ../SalesDetailPending/...
    DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child(mUserUid)
            .child(Constants.FIREBASE_SALES_DETAIL_PENDING_LOCATION);
    databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

            if (!dataSnapshot.hasChildren()) {
                return;
            }

            // Iterate
            for (DataSnapshot snap : dataSnapshot.getChildren()) {

                // Initialize the content values
                ContentValues values = new ContentValues();

                // Initialize the model
                SalesDetailModel model = snap.getValue(SalesDetailModel.class);

                // Get the state
                String key = snap.getKey();
                String itemNumber = model.getItemNumber();
                String itemDesc = model.getItemDesc();
                String itemUnit = model.getItemUnit();
                String itemPrice = model.getItemPrice();
                String itemQty = model.getItemQuantity();
                String itemDiscount = model.getItemDiscount();
                String itemDiscountAmount = model.getItemDiscountAmout();
                String itemAmount = model.getItemAmount();

                // Pack into ContentValues object
                values.put(ContractData.SalesDetailPendingEntry.COLUMN_PUSH_KEY, key);
                values.put(ContractData.SalesDetailPendingEntry.COLUMN_ITEM_NUMBER, itemNumber);
                values.put(ContractData.SalesDetailPendingEntry.COLUMN_ITEM_DESC, itemDesc);
                values.put(ContractData.SalesDetailPendingEntry.COLUMN_ITEM_UNIT, itemUnit);
                values.put(ContractData.SalesDetailPendingEntry.COLUMN_ITEM_PRICE, itemPrice);
                values.put(ContractData.SalesDetailPendingEntry.COLUMN_ITEM_QUANTITY, itemQty);
                values.put(ContractData.SalesDetailPendingEntry.COLUMN_ITEM_DISCOUNT, itemDiscount);
                values.put(ContractData.SalesDetailPendingEntry.COLUMN_ITEM_DISCOUNT_AMOUNT,
                        itemDiscountAmount);
                values.put(ContractData.SalesDetailPendingEntry.COLUMN_ITEM_AMOUNT, itemAmount);

                // Insert into local database
                try {
                    contentResolver.insert(ContractData.SalesDetailPendingEntry.CONTENT_URI, values);
                } catch (Exception e) {
                    Log.e(TAG_LOG, e.getMessage());
                }
            }

        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {
            Log.e(TAG_LOG, databaseError.getMessage());
        }
    });

}

From source file:com.hhunj.hhudata.ForegroundService.java

private String updatedb(List<SearchBookContentsResult> items) {

    String sMessage = "";
    ContentResolver resolver = getApplicationContext().getContentResolver();

    ContentValues values = new ContentValues();

    for (int i = 0; i < items.size(); i++) {

        SearchBookContentsResult res = items.get(i);
        if (res == null)
            continue;
        long stationid = Long.parseLong(res.getPageNumber());

        values.put(NotePad.Notes.TITLE, res.getName());
        values.put(NotePad.Notes.NOTE, "");

        values.put(NotePad.Notes.LONGITUTE, 108.0);
        values.put(NotePad.Notes.LATITUDE, 32.0);
        values.put(NotePad.Notes.SPEED, 55);
        values.put(NotePad.Notes.ALTITUDE, 55);

        values.put(NotePad.Notes.CREATEDDATE, res.getRectime().getTime());

        values.put(NotePad.Notes._ID, stationid);// id

        Uri urlNote = NotePad.Notes.CONTENT_URI;

        Uri myUri = ContentUris.withAppendedId(NotePad.Notes.CONTENT_URI, stationid);

        //?????/*from  w  ww. j av a2  s .c om*/
        Cursor cur = resolver.query(myUri, NotePad.Notes.PROJECTION, null, null, null);
        if (cur == null) {
            // 
        }
        if (cur != null && cur.moveToFirst()) {
            long id = cur.getLong(NotePad.Notes._ID_COLUMN);
            Date oldtime = new Date(cur.getLong(cur.getColumnIndex(NotePad.Notes.CREATEDDATE)));
            boolean oldalarm = (cur.getInt(NotePad.Notes.ALARM_COLUMN) == 0) ? false : true;

            long dif = (res.getRectime().getTime() - oldtime.getTime()) / (60 * 1000);

            // 
            dif = ((new Date()).getTime() - oldtime.getTime()) / (60 * 1000);
            boolean newalarm = false;//
            if (dif > m_alamspan) {
                // ...
                if (oldalarm == false) {
                    Log.w(TAG, "over time err--------");
                    // String phoneNumber ="13338620269";
                    sMessage += "---" + id + "---";
                    newalarm = true;
                } else {
                    newalarm = true;
                }

            }

            values.put(NotePad.Notes.ALARM, newalarm);
            int count = resolver.update(myUri, values, null, null);
            if (count == 0) {

            }

        } else {
            values.put(NotePad.Notes.ALARM, false);
            try {
                myUri = resolver.insert(urlNote, values);
            } catch (IllegalArgumentException e) {
                throw e;
            } catch (SQLException e2) {
                int aa = 0;
                throw e2;
            }
        }
    }
    return sMessage;
}

From source file:com.stockita.stockitapointofsales.salespack.openpack.OpenSalesDetailFragmentUI.java

/**
 * This method will insert the current Sales Detail Open into a local database
 * so later can be query by {@link OpenSalesCheckoutDialogFragment}
 *//*from   w w  w  .j  a  v a 2  s. c o m*/
private void packTheCurrentSalesDetailOpenInToLocalDatabase() {

    // Delete all data in the local database before we insert new data
    final ContentResolver contentResolver = getActivity().getContentResolver();
    contentResolver.delete(ContractData.SalesDetailPendingEntry.CONTENT_URI, null, null);

    // Get the reference to ../openSalesDetail/...
    DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child(mUserUid)
            .child(Constants.FIREBASE_OPEN_SALES_DETAIL_LOCATION).child(mSalesHeaderKey);
    databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

            // Iterate
            for (DataSnapshot snap : dataSnapshot.getChildren()) {

                // Initialize the content values
                ContentValues values = new ContentValues();

                // Initialize the model
                SalesDetailModel model = snap.getValue(SalesDetailModel.class);

                // Get the state
                String key = snap.getKey();
                String itemNumber = model.getItemNumber();
                String itemDesc = model.getItemDesc();
                String itemUnit = model.getItemUnit();
                String itemPrice = model.getItemPrice();
                String itemQty = model.getItemQuantity();
                String itemDiscount = model.getItemDiscount();
                String itemDiscountAmount = model.getItemDiscountAmout();
                String itemAmount = model.getItemAmount();

                // Pack into ContentValues object
                values.put(ContractData.SalesDetailPendingEntry.COLUMN_PUSH_KEY, key);
                values.put(ContractData.SalesDetailPendingEntry.COLUMN_ITEM_NUMBER, itemNumber);
                values.put(ContractData.SalesDetailPendingEntry.COLUMN_ITEM_DESC, itemDesc);
                values.put(ContractData.SalesDetailPendingEntry.COLUMN_ITEM_UNIT, itemUnit);
                values.put(ContractData.SalesDetailPendingEntry.COLUMN_ITEM_PRICE, itemPrice);
                values.put(ContractData.SalesDetailPendingEntry.COLUMN_ITEM_QUANTITY, itemQty);
                values.put(ContractData.SalesDetailPendingEntry.COLUMN_ITEM_DISCOUNT, itemDiscount);
                values.put(ContractData.SalesDetailPendingEntry.COLUMN_ITEM_DISCOUNT_AMOUNT,
                        itemDiscountAmount);
                values.put(ContractData.SalesDetailPendingEntry.COLUMN_ITEM_AMOUNT, itemAmount);

                // Insert into local database
                try {
                    contentResolver.insert(ContractData.SalesDetailPendingEntry.CONTENT_URI, values);
                } catch (Exception e) {
                    Log.e(TAG_LOG, e.getMessage());
                }
            }
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {
            Log.e(TAG_LOG, databaseError.getMessage());
        }
    });
}

From source file:de.ub0r.android.websms.WebSMSReceiver.java

/**
 * Save Message to internal database.//from w  w w  .jav a 2 s  . c  om
 *
 * @param context {@link android.content.Context}
 * @param specs   {@link de.ub0r.android.websms.connector.common.ConnectorSpec}
 * @param command {@link de.ub0r.android.websms.connector.common.ConnectorCommand}
 * @param msgType sent or draft?
 */
static void saveMessage(final Context context, final ConnectorSpec specs, final ConnectorCommand command,
        final int msgType) {
    if (command.getType() != ConnectorCommand.TYPE_SEND) {
        return;
    }
    if (PreferenceManager.getDefaultSharedPreferences(context).getBoolean(WebSMS.PREFS_DROP_SENT, false)) {
        Log.i(TAG, "drop sent messages");
        return;
    }

    // save message to android's internal sms database
    final ContentResolver cr = context.getContentResolver();
    assert cr != null;
    final ContentValues values = new ContentValues();
    values.put(TYPE, msgType);

    if (msgType == MESSAGE_TYPE_SENT) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {

            if (isRealSMS(specs)) {
                // drop messages from "SMS" connector. it gets saved internally.
                return;
            }

            try {
                // API19+ does not allow writing to content://sms anymore
                // anyway, give it a try, if SMSdroid is not installed
                // AppOps might let the app write the message
                if (Telephony.Sms.getDefaultSmsPackage(context).equals("de.ub0r.android.smsdroid")) {
                    sendMessageToSMSdroid(context, specs, command);
                    return;
                }
            } catch (NullPointerException e) {
                Log.w(TAG, "there is no telephony service!");
                // fall back saving the message the old fashion way. it might work..
            }
        }

        final String[] uris = command.getMsgUris();
        if (uris != null && uris.length > 0) {
            for (String s : uris) {
                final Uri u = Uri.parse(s);
                try {
                    final int updated = cr.update(u, values, null, null);
                    Log.d(TAG, "updated: " + updated);
                    if (updated > 0 && specs != null && !isRealSMS(specs)) {
                        sendMessageToCallMeter(context, specs, u);
                    }
                } catch (SQLiteException e) {
                    Log.e(TAG, "error updating sent message: " + u, e);
                    Toast.makeText(context, R.string.log_error_saving_message, Toast.LENGTH_LONG).show();
                }
            }
            return; // skip legacy saving
        }
    } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        return; // skip saving drafts on API19+
    }

    final String text = command.getText();

    Log.d(TAG, "save message(s):");
    Log.d(TAG, "type: " + msgType);
    Log.d(TAG, "TEXT: " + text);
    values.put(READ, 1);
    values.put(BODY, text);
    if (command.getSendLater() > 0) {
        values.put(DATE, command.getSendLater());
        Log.d(TAG, "DATE: " + command.getSendLater());
    }
    final String[] recipients = command.getRecipients();
    final ArrayList<String> inserted = new ArrayList<String>(recipients.length);
    for (String recipient : recipients) {
        if (recipient == null || recipient.trim().length() == 0) {
            continue; // skip empty recipients

        }
        String address = Utils.getRecipientsNumber(recipient);
        Log.d(TAG, "TO: " + address);
        try {
            final Cursor c = cr.query(
                    URI_SMS, PROJECTION_ID, TYPE + " = " + MESSAGE_TYPE_DRAFT + " AND " + ADDRESS + " = '"
                            + address + "' AND " + BODY + " like '" + text.replace("'", "_") + "'",
                    null, DATE + " DESC");
            if (c != null && c.moveToFirst()) {
                final Uri u = URI_SENT.buildUpon().appendPath(c.getString(0)).build();
                assert u != null;
                Log.d(TAG, "skip saving draft: " + u);
                inserted.add(u.toString());
            } else {
                final ContentValues cv = new ContentValues(values);
                cv.put(ADDRESS, address);
                // save sms to content://sms/sent
                Uri u = cr.insert(URI_SENT, cv);
                if (u != null) {
                    inserted.add(u.toString());
                    if (msgType == MESSAGE_TYPE_SENT) {
                        // API19+ code may reach this point
                        // SMSdroid is not default app
                        // but message was saved as sent somehow
                        sendMessageToCallMeter(context, specs, u);
                    }
                }
            }
            if (c != null && !c.isClosed()) {
                c.close();
            }
        } catch (SQLiteException e) {
            Log.e(TAG, "failed saving message", e);
        } catch (IllegalArgumentException e) {
            Log.e(TAG, "failed saving message", e);
            Toast.makeText(context, R.string.log_error_saving_message, Toast.LENGTH_LONG).show();
        }
    }
    if (msgType == MESSAGE_TYPE_DRAFT && inserted.size() > 0) {
        command.setMsgUris(inserted.toArray(new String[inserted.size()]));
    }
}

From source file:org.getlantern.firetweet.util.Utils.java

@NonNull
public static ParcelableStatus findStatus(final Context context, final long accountId, final long statusId)
        throws TwitterException {
    if (context == null)
        throw new NullPointerException();
    final ParcelableStatus cached = findStatusInDatabases(context, accountId, statusId);
    if (cached != null)
        return cached;
    final Twitter twitter = getTwitterInstance(context, accountId, true);
    if (twitter == null)
        throw new TwitterException("Account does not exist");
    final Status status = twitter.showStatus(statusId);
    final String where = Expression.and(Expression.equals(Statuses.ACCOUNT_ID, accountId),
            Expression.equals(Statuses.STATUS_ID, statusId)).getSQL();
    final ContentResolver resolver = context.getContentResolver();
    resolver.delete(CachedStatuses.CONTENT_URI, where, null);
    resolver.insert(CachedStatuses.CONTENT_URI, ContentValuesCreator.createStatus(status, accountId));
    return new ParcelableStatus(status, accountId, false);
}