Example usage for android.database Cursor getLong

List of usage examples for android.database Cursor getLong

Introduction

In this page you can find the example usage for android.database Cursor getLong.

Prototype

long getLong(int columnIndex);

Source Link

Document

Returns the value of the requested column as a long.

Usage

From source file:com.ichi2.libanki.sync.Syncer.java

/**
 * Deletions ********************************************************************
 *//*from w  w w  . ja va 2  s. com*/

private JSONObject removed() {
    JSONArray cards = new JSONArray();
    JSONArray notes = new JSONArray();
    JSONArray decks = new JSONArray();
    Cursor cur = null;
    try {
        cur = mCol.getDb().getDatabase().rawQuery(
                "SELECT oid, type FROM graves WHERE usn" + (mCol.getServer() ? (" >= " + mMinUsn) : (" = -1")),
                null);
        while (cur.moveToNext()) {
            int type = cur.getInt(1);
            switch (type) {
            case Consts.REM_CARD:
                cards.put(cur.getLong(0));
                break;
            case Consts.REM_NOTE:
                notes.put(cur.getLong(0));
                break;
            case Consts.REM_DECK:
                decks.put(cur.getLong(0));
                break;
            }
        }
    } finally {
        if (cur != null && !cur.isClosed()) {
            cur.close();
        }
    }
    if (!mCol.getServer()) {
        mCol.getDb().execute("UPDATE graves SET usn=" + mMaxUsn + " WHERE usn=-1");
    }
    JSONObject o = new JSONObject();
    try {
        o.put("cards", cards);
        o.put("notes", notes);
        o.put("decks", decks);
    } catch (JSONException e) {
        throw new RuntimeException(e);
    }
    return o;
}

From source file:mobisocial.musubi.service.AddressBookUpdateHandler.java

public static void importFullAddressBook(Context context) {
    Log.d(TAG, "doing full import");
    SQLiteOpenHelper db = App.getDatabaseSource(context);
    DatabaseManager dbm = new DatabaseManager(context);
    IdentitiesManager idm = dbm.getIdentitiesManager();
    FeedManager fm = dbm.getFeedManager();
    MyAccountManager am = dbm.getMyAccountManager();
    long startTime = System.currentTimeMillis();
    String musubiAccountType = context.getString(R.string.account_type);
    long maxDataId = -1;
    long maxContactId = -1;
    assert (SYNC_EMAIL);
    String account_type_selection = getAccountSelectionString();

    Cursor c = context.getContentResolver().query(ContactsContract.Data.CONTENT_URI,
            new String[] { ContactsContract.Data.CONTACT_ID, ContactsContract.Contacts.DISPLAY_NAME,
                    ContactsContract.Data._ID, ContactsContract.Data.DATA_VERSION, ContactsContract.Data.DATA1,
                    ContactsContract.Data.MIMETYPE, ContactsContract.RawContacts.ACCOUNT_NAME,
                    ContactsContract.RawContacts.ACCOUNT_TYPE },
            "(" + ContactsContract.RawContacts.ACCOUNT_TYPE + "<>'" + musubiAccountType + "'" + ") AND ("
                    + NAME_OR_OTHER_SELECTION + account_type_selection + ")", // All known contacts.
            null, null);// w  w  w  . ja v a 2s  .c  om

    if (c == null) {
        Log.e(TAG, "no valid cursor", new Throwable());
        return;
    }

    sAddressBookTotal = c.getCount();
    sAddressBookPosition = 0;
    Log.d(TAG, "Scanning contacts...");

    final Map<String, MMyAccount> myAccounts = new HashMap<String, MMyAccount>();
    final Pattern emailPattern = getEmailPattern();
    final Pattern numberPattern = getNumberPattern();
    while (c.moveToNext()) {
        sAddressBookPosition++;
        String identityType = c.getString(5);
        String identityPrincipal = c.getString(4);
        long contactId = c.getLong(0);
        long dataId = c.getLong(2);
        String displayName = c.getString(1);
        byte[] thumbnail = null;

        String accountName = c.getString(6);
        String accountType = c.getString(7);
        if (accountName == null) {
            accountName = "null-account-name";
        }
        if (accountType == null) {
            accountType = "null-account-type";
        }
        String accountKey = accountName + "-" + accountType;
        MMyAccount myAccount = myAccounts.get(accountKey);
        if (myAccount == null) {
            myAccount = lookupOrCreateAccount(dbm, accountName, accountType);
            prepareAccountWhitelistFeed(am, fm, myAccount);
            myAccounts.put(accountKey, myAccount);
        }

        if (displayName == null || emailPattern.matcher(displayName).matches()
                || numberPattern.matcher(displayName).matches()) {
            continue;
        }

        IBIdentity ibid = ibIdentityForData(identityType, identityPrincipal);
        if (ibid == null) {
            //TODO: better selection
            //Log.d(TAG, "skipping " + displayName + " // " + identityPrincipal);
            continue;
        }
        Uri uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, contactId);
        InputStream is = ContactsContract.Contacts.openContactPhotoInputStream(context.getContentResolver(),
                uri);
        if (is != null) {
            //Log.d(TAG, "importing photo for " + displayName);
            try {
                thumbnail = IOUtils.toByteArray(is);
            } catch (IOException e) {
                thumbnail = null;
                //Log.e(TAG, "photo thumbnail failed to serialize", e);
            } finally {
                try {
                    is.close();
                } catch (IOException e) {
                }
            }
        } else {
            thumbnail = null;
        }
        MIdentity ident = addIdentity(context, idm, contactId, displayName, thumbnail, ibid);
        if (ident != null) {
            fm.ensureFeedMember(myAccount.feedId_, ident.id_);
            fm.acceptFeedsFromMember(context, ident.id_);
        }

        maxDataId = Math.max(maxDataId, dataId);
        maxContactId = Math.max(maxContactId, contactId);
    }
    c.close();
    long timeTaken = System.currentTimeMillis() - startTime;

    ContactDataVersionManager cdvm = new ContactDataVersionManager(db);
    cdvm.setMaxDataIdSeen(maxDataId);
    cdvm.setMaxContactIdSeen(maxContactId);
    Log.d(TAG, "full import took " + timeTaken / 1000 + " secs");
    context.getContentResolver().notifyChange(MusubiService.ADDRESS_BOOK_SCANNED, null);
}

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

private void processDeletedContacts(ContentProviderClient provider, String authToken, Account account,
        SyncResult syncResult) throws IOException, JSONException, RemoteException {
    Cursor contactCursor = null;
    try {//from  w w  w. j  a  v a 2 s  .  co m
        contactCursor = provider.query(GMSContacts.CONTENT_URI,
                new String[] { GMSContact._ID, GMSContact.CLOUD_ID, GMSContact.STATUS, GMSContact.GROUP_ID },
                GMSContact.STATUS + "=?", new String[] { String.valueOf(GMSContact.STATUS_DELETED) }, null);
        if (contactCursor == null) {
            syncResult.databaseError = true;
            return;
        }
        while (contactCursor.moveToNext()) {
            Cursor groupCursor = null;
            try {
                groupCursor = provider.query(
                        ContentUris.withAppendedId(GMSGroups.CONTENT_URI, contactCursor.getLong(3)),
                        new String[] { GMSGroup.CLOUD_ID }, null, null, null);
                if (groupCursor == null || !groupCursor.moveToFirst()) {
                    syncResult.databaseError = true;
                    break;
                }
                if (NetworkUtilities.removeGroupContact(authToken, groupCursor.getString(0),
                        contactCursor.getString(1)) == null) {
                    syncResult.stats.numIoExceptions++;
                } else {
                    syncResult.stats.numDeletes++;
                }
            } finally {
                if (groupCursor != null) {
                    groupCursor.close();
                }
            }
        }
    } finally {
        if (contactCursor != null) {
            contactCursor.close();
        }
    }

}

From source file:com.polyvi.xface.extension.telephony.XTelephonyExt.java

/**
 * ?id?/*w  w w. ja  v  a 2  s  . c om*/
 *
 * @param[in] callRecordType ?
 * @param[in] callRecordIndex ?
 * @return ?JSON
 */
private JSONObject getCallRecord(String callRecordType, int recordIndex) {
    int callType = getCallRecordType(callRecordType);
    Cursor c = mContentResolver.query(CallLog.Calls.CONTENT_URI,
            new String[] { CallLog.Calls.NUMBER, CallLog.Calls._ID, CallLog.Calls.CACHED_NAME,
                    CallLog.Calls.TYPE, CallLog.Calls.DATE, CallLog.Calls.DURATION },
            CallLog.Calls.TYPE + "=" + callType, null, CallLog.Calls.DEFAULT_SORT_ORDER);
    String callRecordAddress = "";
    String callRecordId = "";
    String callRecordName = "";
    long durationSeconds = 0;
    long startTime = 0;
    JSONObject callRecord = new JSONObject();
    if (null != c) {
        if (c.moveToPosition(recordIndex)) {
            callRecordAddress = c.getString(0);
            callRecordId = c.getString(1);
            callRecordName = c.getString(2);
            startTime = c.getLong(4);
            durationSeconds = c.getLong(5);
        }
        c.close();
        try {
            callRecord.put("callRecordAddress", callRecordAddress);
            callRecord.put("callRecordId", callRecordId);
            callRecord.put("callRecordName", callRecordName);
            callRecord.put("durationSeconds", durationSeconds);
            callRecord.put("startTime", startTime);
            callRecord.put("callRecordType", callRecordType);
        } catch (JSONException e) {
            XLog.e(CLASS_NAME, e.getMessage());
        }
    }
    return callRecord;
}

From source file:com.example.jumpnote.android.SyncAdapter.java

public void reconcileSyncedNotes(ContentProviderClient provider, Account account,
        List<ModelJava.Note> changedNotes, SyncStats syncStats)
        throws RemoteException, OperationApplicationException {
    Cursor noteCursor;
    ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>();
    for (ModelJava.Note changedNote : changedNotes) {
        Uri noteUri = null;//from  w  ww .ja va2  s .c o m

        if (changedNote.getId() != null) {
            noteUri = addCallerIsSyncAdapterParameter(
                    JumpNoteContract.buildNoteUri(account.name, Long.parseLong(changedNote.getId())));
        } else {
            noteCursor = provider.query(JumpNoteContract.buildNoteListUri(account.name), PROJECTION,
                    JumpNoteContract.Notes.SERVER_ID + " = ?", new String[] { changedNote.getServerId() },
                    null);

            if (noteCursor.moveToNext()) {
                noteUri = addCallerIsSyncAdapterParameter(
                        JumpNoteContract.buildNoteUri(account.name, noteCursor.getLong(0)));
            }

            noteCursor.close();
        }

        if (changedNote.isPendingDelete()) {
            // Handle server-side delete.
            if (noteUri != null) {
                operations.add(ContentProviderOperation.newDelete(noteUri).build());
                syncStats.numDeletes++;
            }
        } else {
            ContentValues values = changedNote.toContentValues();
            if (noteUri != null) {
                // Handle server-side update.
                operations.add(ContentProviderOperation.newUpdate(noteUri).withValues(values).build());
                syncStats.numUpdates++;
            } else {
                // Handle server-side insert.
                operations
                        .add(ContentProviderOperation
                                .newInsert(addCallerIsSyncAdapterParameter(
                                        JumpNoteContract.buildNoteListUri(account.name)))
                                .withValues(values).build());
                syncStats.numInserts++;
            }
        }
    }

    provider.applyBatch(operations);
}

From source file:net.exclaimindustries.geohashdroid.services.WikiService.java

private ImageInfo readImageInfo(Uri uri, Location locationIfNoneSet) {
    // We're hoping this is something that MediaStore understands.  If not,
    // or if the image doesn't exist anyway, we're returning null, which is
    // interpreted by the intent handler to mean there's no image here, so
    // an error should be thrown.
    ImageInfo toReturn = null;//w  ww.  j  a  v a2  s . co m

    if (uri != null) {
        Cursor cursor;
        cursor = getContentResolver().query(uri,
                new String[] { MediaStore.Images.ImageColumns.DATA, MediaStore.Images.ImageColumns.LATITUDE,
                        MediaStore.Images.ImageColumns.LONGITUDE, MediaStore.Images.ImageColumns.DATE_TAKEN },
                null, null, null);

        if (cursor == null || cursor.getCount() < 1) {
            if (cursor != null)
                cursor.close();
            return null;
        }

        cursor.moveToFirst();

        toReturn = new ImageInfo();
        toReturn.uri = uri;
        toReturn.filename = cursor.getString(0);
        toReturn.timestamp = cursor.getLong(3);

        // These two could very well be null or empty.  Nothing wrong with
        // that.  But if they're good, make a Location out of them.
        String lat = cursor.getString(1);
        String lon = cursor.getString(2);

        Location toSet;
        try {
            double llat = Double.parseDouble(lat);
            double llon = Double.parseDouble(lon);
            toSet = new Location("");
            toSet.setLatitude(llat);
            toSet.setLongitude(llon);
        } catch (Exception ex) {
            // If we get an exception, we got it because of the number
            // parser.  Assume it's invalid and we're using the user's
            // current location, if that's even known (that might ALSO be
            // null, in which case we just don't have any clue where the
            // user is, which seems a bit counterintuitive to how
            // Geohashing is supposed to work).
            toSet = locationIfNoneSet;
        }

        // Now toss the location into the info.
        toReturn.location = toSet;

        cursor.close();
    }

    return toReturn;
}

From source file:net.olejon.mdapp.NotesEditActivity.java

private void getMedications() {
    try {//www .j  a  va  2s . c om
        int medicationsJsonArrayLength = mPatientMedicationsJsonArray.length();

        if (medicationsJsonArrayLength == 0) {
            mPatientMedicationsTextView.setVisibility(View.GONE);
        } else {
            mPatientMedicationsTextView.setVisibility(View.VISIBLE);

            final ArrayList<String> medicationsNamesArrayList = new ArrayList<>();
            final ArrayList<String> medicationsManufacturersArrayList = new ArrayList<>();

            final String[] medicationsNamesStringArrayList = new String[medicationsJsonArrayLength + 2];

            medicationsNamesStringArrayList[0] = getString(R.string.notes_edit_medications_dialog_interactions);
            medicationsNamesStringArrayList[1] = getString(R.string.notes_edit_medications_dialog_remove_all);

            for (int i = 0; i < medicationsJsonArrayLength; i++) {
                JSONObject medicationJsonObject = mPatientMedicationsJsonArray.getJSONObject(i);

                String name = medicationJsonObject.getString("name");
                String manufacturer = medicationJsonObject.getString("manufacturer");

                medicationsNamesArrayList.add(name);
                medicationsManufacturersArrayList.add(manufacturer);

                medicationsNamesStringArrayList[i + 2] = name;
            }

            String medicationsNames = "";

            for (int n = 0; n < medicationsNamesArrayList.size(); n++) {
                medicationsNames += medicationsNamesArrayList.get(n) + ", ";
            }

            medicationsNames = medicationsNames.replaceAll(", $", "");

            mPatientMedicationsTextView.setText(Html.fromHtml("<u>" + medicationsNames + "</u>"));

            mPatientMedicationsTextView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    new MaterialDialog.Builder(mContext)
                            .title(getString(R.string.notes_edit_medications_dialog_title))
                            .items(medicationsNamesStringArrayList)
                            .itemsCallback(new MaterialDialog.ListCallback() {
                                @Override
                                public void onSelection(MaterialDialog materialDialog, View view, int i,
                                        CharSequence charSequence) {
                                    if (i == 0) {
                                        String medicationsInteractions = "";

                                        for (int n = 0; n < medicationsNamesArrayList.size(); n++) {
                                            medicationsInteractions += medicationsNamesArrayList.get(n)
                                                    .split(" ")[0] + " ";
                                        }

                                        medicationsInteractions = medicationsInteractions.trim();

                                        Intent intent = new Intent(mContext, InteractionsCardsActivity.class);
                                        intent.putExtra("search", medicationsInteractions);
                                        startActivity(intent);
                                    } else if (i == 1) {
                                        try {
                                            mPatientMedicationsJsonArray = new JSONArray("[]");

                                            getMedications();
                                        } catch (Exception e) {
                                            Log.e("NotesEditActivity", Log.getStackTraceString(e));
                                        }
                                    } else {
                                        int position = i - 2;

                                        String medicationName = medicationsNamesArrayList.get(position);
                                        String medicationManufacturer = medicationsManufacturersArrayList
                                                .get(position);

                                        SQLiteDatabase sqLiteDatabase = new SlDataSQLiteHelper(mContext)
                                                .getReadableDatabase();

                                        String[] queryColumns = { SlDataSQLiteHelper.MEDICATIONS_COLUMN_ID };
                                        Cursor cursor = sqLiteDatabase.query(
                                                SlDataSQLiteHelper.TABLE_MEDICATIONS, queryColumns,
                                                SlDataSQLiteHelper.MEDICATIONS_COLUMN_NAME + " = "
                                                        + mTools.sqe(medicationName) + " AND "
                                                        + SlDataSQLiteHelper.MEDICATIONS_COLUMN_MANUFACTURER
                                                        + " = " + mTools.sqe(medicationManufacturer),
                                                null, null, null, null);

                                        if (cursor.moveToFirst()) {
                                            long id = cursor.getLong(cursor.getColumnIndexOrThrow(
                                                    SlDataSQLiteHelper.MEDICATIONS_COLUMN_ID));

                                            Intent intent = new Intent(mContext, MedicationActivity.class);

                                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                                                if (mTools.getDefaultSharedPreferencesBoolean(
                                                        "MEDICATION_MULTIPLE_DOCUMENTS"))
                                                    intent.setFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK
                                                            | Intent.FLAG_ACTIVITY_NEW_DOCUMENT);
                                            }

                                            intent.putExtra("id", id);
                                            startActivity(intent);
                                        }

                                        cursor.close();
                                        sqLiteDatabase.close();
                                    }
                                }
                            }).itemColorRes(R.color.dark_blue).show();
                }
            });
        }
    } catch (Exception e) {
        Log.e("NotesEditActivity", Log.getStackTraceString(e));
    }
}

From source file:com.yuntongxun.ecdemo.storage.IMessageSqlManager.java

/**
 * @param threadId//  ww  w .  j  ava2  s . co m
 * @param lastTime
 * @return
 */
public static ArrayList<ECMessage> queryIMessageListAfter(long threadId, String lastTime) {
    ArrayList<ECMessage> al = null;
    Cursor cursor = null;
    StringBuffer sb = new StringBuffer();
    if (lastTime != null && !lastTime.equals("") && !lastTime.equals("0")) {
        sb.append(IMessageColumn.CREATE_DATE + " > ").append(lastTime);
    } else {
        sb.append("1=1");
    }
    sb.append(" and " + IMessageColumn.OWN_THREAD_ID + " = ").append(threadId);
    sb.append(" and  " + IMessageColumn.BOX_TYPE + " != 3");
    try {
        cursor = getInstance().sqliteDB().query(false, DatabaseHelper.TABLES_NAME_IM_MESSAGE, null,
                sb.toString(), null, null, null, IMessageColumn.RECEIVE_DATE + " asc", null);
        if (cursor != null) {
            if (cursor.getCount() == 0) {
                return null;
            }
            al = new ArrayList<ECMessage>();
            while (cursor.moveToNext()) {

                long id = cursor.getLong(cursor.getColumnIndex(IMessageColumn.ID));
                String sender = cursor.getString(cursor.getColumnIndexOrThrow(IMessageColumn.sender));
                String msgId = cursor.getString(cursor.getColumnIndexOrThrow(IMessageColumn.MESSAGE_ID));
                long ownThreadId = cursor.getLong(cursor.getColumnIndexOrThrow(IMessageColumn.OWN_THREAD_ID));
                long createDate = cursor.getLong(cursor.getColumnIndexOrThrow(IMessageColumn.CREATE_DATE));
                long receiveDate = cursor.getLong(cursor.getColumnIndexOrThrow(IMessageColumn.RECEIVE_DATE));
                String userData = cursor.getString(cursor.getColumnIndexOrThrow(IMessageColumn.USER_DATA));
                int read = cursor.getInt(cursor.getColumnIndexOrThrow(IMessageColumn.READ_STATUS));
                int boxType = cursor.getInt(cursor.getColumnIndexOrThrow(IMessageColumn.BOX_TYPE));
                int msgType = cursor.getInt(cursor.getColumnIndexOrThrow(IMessageColumn.MESSAGE_TYPE));
                int sendStatus = cursor.getInt(cursor.getColumnIndexOrThrow(IMessageColumn.SEND_STATUS));

                ECMessage ecMessage = null;
                if (msgType == ECMessage.Type.TXT.ordinal()) {
                    String content = cursor.getString(cursor.getColumnIndexOrThrow(IMessageColumn.BODY));
                    ecMessage = ECMessage.createECMessage(ECMessage.Type.TXT);
                    ECTextMessageBody textBody = new ECTextMessageBody(content);
                    ecMessage.setBody(textBody);
                } else {
                    /*
                    * String fileUrl =
                    * cursor.getString(cursor.getColumnIndexOrThrow
                    * (IMessageColumn.FILE_URL)); String fileLocalPath =
                    * cursor
                    * .getString(cursor.getColumnIndexOrThrow(IMessageColumn
                    * .FILE_PATH));
                    * 
                    * if (msgType == ECMessage.Type.VOICE.ordinal()) { int
                    * duration =
                    * cursor.getInt(cursor.getColumnIndexOrThrow(
                    * IMessageColumn.DURATION)); ECVoiceMessageBody
                    * voiceBody = new ECVoiceMessageBody(new
                    * File(fileLocalPath), 0);
                    * voiceBody.setRemoteUrl(fileUrl);
                    * ecMessage.setBody(voiceBody); ecMessage =
                    * ECMessage.createECMessage(ECMessage.Type.VOICE); }
                    * else if (msgType == ECMessage.Type.IMAGE.ordinal() ||
                    * msgType == ECMessage.Type.FILE.ordinal()) {
                    * ECFileMessageBody fileBody = new } else { continue; }
                    */
                }
                ecMessage.setId(id);
                ecMessage.setFrom(sender);
                ecMessage.setMsgId(msgId);
                ecMessage.setMsgTime(createDate);
                ecMessage.setUserData(userData);
                ecMessage.setDirection(getMessageDirect(boxType));
                al.add(0, ecMessage);
            }
        }
    } catch (Exception e) {
        LogUtil.e(TAG + " " + e.toString());
        e.printStackTrace();
    } finally {
        if (cursor != null) {
            cursor.close();
            cursor = null;
        }
    }
    return al;
}

From source file:com.samsung.android.remindme.SyncAdapter.java

public void reconcileSyncedAlerts(ContentProviderClient provider, Account account,
        List<ModelJava.Alert> changedAlerts, SyncStats syncStats)
        throws RemoteException, OperationApplicationException {
    Cursor alertCursor;
    ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>();
    for (ModelJava.Alert changedAlert : changedAlerts) {
        Uri alertUri = null;//from   ww w .j  a va2  s .co  m

        if (changedAlert.getId() != null) {
            alertUri = addCallerIsSyncAdapterParameter(
                    RemindMeContract.buildAlertUri(account.name, Long.parseLong(changedAlert.getId())));
        } else {
            alertCursor = provider.query(RemindMeContract.buildAlertListUri(account.name), PROJECTION,
                    RemindMeContract.Alerts.SERVER_ID + " = ?", new String[] { changedAlert.getServerId() },
                    null);

            if (alertCursor.moveToNext()) {
                alertUri = addCallerIsSyncAdapterParameter(
                        RemindMeContract.buildAlertUri(account.name, alertCursor.getLong(0)));
            }

            alertCursor.close();
        }

        if (changedAlert.isPendingDelete()) {
            // Handle server-side delete.
            if (alertUri != null) {
                operations.add(ContentProviderOperation.newDelete(alertUri).build());
                syncStats.numDeletes++;
            }
        } else {
            ContentValues values = changedAlert.toContentValues();
            if (alertUri != null) {
                // Handle server-side update.
                operations.add(ContentProviderOperation.newUpdate(alertUri).withValues(values).build());
                syncStats.numUpdates++;
            } else {
                // Handle server-side insert.
                operations
                        .add(ContentProviderOperation
                                .newInsert(addCallerIsSyncAdapterParameter(
                                        RemindMeContract.buildAlertListUri(account.name)))
                                .withValues(values).build());
                syncStats.numInserts++;
            }
        }
    }

    provider.applyBatch(operations);
}

From source file:com.ubuntuone.android.files.provider.MetaUtilities.java

public static ArrayList<U1Node> getPhotoNodesFromDirectory(String directoryResourcePath) {
    String[] projection = Nodes.getDefaultProjection();
    String selection = Nodes.NODE_PARENT_PATH + "=? AND " + Nodes.NODE_MIME + "=?";
    String[] selectionArgs = new String[] { directoryResourcePath, "image/jpeg" };

    Cursor c = sResolver.query(Nodes.CONTENT_URI, projection, selection, selectionArgs, null);

    ArrayList<U1Node> photoNodes = null;
    if (c != null) {
        photoNodes = new ArrayList<U1Node>();
        try {/*from www  .  ja  va 2  s.c  o  m*/
            if (c.moveToFirst()) {
                do {
                    String resourcePath;
                    String key;
                    U1NodeKind kind;
                    Boolean isLive = true;
                    String path;
                    String parentPath;
                    String volumePath;
                    Date whenCreated;
                    Date whenChanged;
                    Long generation;
                    Long generationCreated;
                    String contentPath;

                    resourcePath = c.getString(c.getColumnIndex(Nodes.NODE_RESOURCE_PATH));
                    key = c.getString(c.getColumnIndex(Nodes.NODE_KEY));
                    kind = U1NodeKind
                            .valueOf(c.getString(c.getColumnIndex(Nodes.NODE_KIND)).toUpperCase(Locale.US));
                    isLive = c.getInt(c.getColumnIndex(Nodes.NODE_IS_LIVE)) != 0;
                    path = c.getString(c.getColumnIndex(Nodes.NODE_PATH));
                    parentPath = c.getString(c.getColumnIndex(Nodes.NODE_PARENT_PATH));
                    volumePath = c.getString(c.getColumnIndex(Nodes.NODE_VOLUME_PATH));
                    whenCreated = new Date(c.getLong(c.getColumnIndex(Nodes.NODE_WHEN_CREATED)));
                    whenChanged = new Date(c.getLong(c.getColumnIndex(Nodes.NODE_WHEN_CHANGED)));
                    generation = c.getLong(c.getColumnIndex(Nodes.NODE_GENERATION));
                    generationCreated = c.getLong(c.getColumnIndex(Nodes.NODE_GENERATION_CREATED));
                    contentPath = c.getString(c.getColumnIndex(Nodes.NODE_CONTENT_PATH));

                    U1Node node = new U1Node(resourcePath, kind, isLive, path, parentPath, volumePath, key,
                            whenCreated, whenChanged, generation, generationCreated, contentPath);
                    photoNodes.add(node);
                } while (c.moveToNext());
            }
        } finally {
            c.close();
        }
    }
    return photoNodes;
}