Example usage for android.database Cursor getColumnIndexOrThrow

List of usage examples for android.database Cursor getColumnIndexOrThrow

Introduction

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

Prototype

int getColumnIndexOrThrow(String columnName) throws IllegalArgumentException;

Source Link

Document

Returns the zero-based index for the given column name, or throws IllegalArgumentException if the column doesn't exist.

Usage

From source file:eu.codeplumbers.cosi.services.CosiSmsService.java

private void readSmsDatabase() {
    //Fetches the complete call log in descending order. i.e recent calls appears first.
    if (ActivityCompat.checkSelfPermission(this,
            Manifest.permission.READ_SMS) == PackageManager.PERMISSION_GRANTED) {
        Uri message = Uri.parse("content://sms/");
        ContentResolver cr = getContentResolver();

        Cursor c = cr.query(message, null, null, null, null);
        int totalSMS = c.getCount();

        if (c.moveToFirst()) {
            for (int i = 0; i < totalSMS; i++) {
                mBuilder.setProgress(totalSMS, i, false);
                mNotifyManager.notify(notification_id, mBuilder.build());
                EventBus.getDefault()//from w w  w .  ja  v  a2  s .c om
                        .post(new SmsSyncEvent(SYNC_MESSAGE, getString(R.string.lbl_sms_status_read_phone)));
                String systemId = c.getString(c.getColumnIndexOrThrow("_id"));
                String address = c.getString(c.getColumnIndexOrThrow("address"));
                String body = c.getString(c.getColumnIndexOrThrow("body"));
                String readState = c.getString(c.getColumnIndex("read"));
                String dateAndTime = c.getString(c.getColumnIndexOrThrow("date"));
                String type = c.getString(c.getColumnIndexOrThrow("type"));

                Sms sms = Sms.getBySystemId(systemId);

                if (sms == null) {
                    sms = new Sms();
                    sms.setRemoteId("");
                }

                sms.setBody(body);
                sms.setAddress(address.replace(" ", "").replace("-", ""));
                sms.setDateAndTime(DateUtils.formatDate(dateAndTime));
                sms.setSystemId(systemId);
                sms.setType(Integer.valueOf(type));
                sms.setReadState(Boolean.parseBoolean(readState));
                sms.setDeviceId(
                        sms.getRemoteId() != "" ? sms.getDeviceId() : Device.registeredDevice().getLogin());
                sms.save();

                allSms.add(sms);

                c.moveToNext();
            }
        }
        // else {
        // throw new RuntimeException("You have no SMS");
        // }
        c.close();
    } else {
        EventBus.getDefault().post(new SmsSyncEvent(SERVICE_ERROR, getString(R.string.permission_denied_sms)));
        stopSelf();
    }
}

From source file:com.kdao.cmpe235_project.UploadActivity.java

@SuppressLint("NewApi")
private String getPath(Uri uri) throws URISyntaxException {
    final boolean needToCheckUri = Build.VERSION.SDK_INT >= 19;
    String selection = null;//from   w  w  w .j  a  v a 2s .  co m
    String[] selectionArgs = null;
    // Uri is different in versions after KITKAT (Android 4.4), we need to
    // deal with different Uris.
    if (needToCheckUri && DocumentsContract.isDocumentUri(getApplicationContext(), uri)) {
        if (isExternalStorageDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            return Environment.getExternalStorageDirectory() + "/" + split[1];
        } else if (isDownloadsDocument(uri)) {
            final String id = DocumentsContract.getDocumentId(uri);
            uri = ContentUris.withAppendedId(Uri.parse(LOCAL_FOLDER_PATH), Long.valueOf(id));
        } else if (isMediaDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];
            if ("image".equals(type)) {
                uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            } else if ("video".equals(type)) {
                uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
            } else if ("audio".equals(type)) {
                uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
            }
            selection = "_id=?";
            selectionArgs = new String[] { split[1] };
        }
    }
    if ("content".equalsIgnoreCase(uri.getScheme())) {
        String[] projection = { MediaStore.Images.Media.DATA };
        Cursor cursor = null;
        try {
            cursor = getContentResolver().query(uri, projection, selection, selectionArgs, null);
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            if (cursor.moveToFirst()) {
                return cursor.getString(column_index);
            }
        } catch (Exception e) {
        }
    } else if ("file".equalsIgnoreCase(uri.getScheme())) {
        return uri.getPath();
    }
    return null;
}

From source file:com.amazonaws.mobileconnectors.s3.transferutility.TransferUtility.java

/**
 * Gets a list of TransferObserver instances which are observing records
 * with the given type.//from   w  ww  .  j  a  v  a  2s  .  c o m
 *
 * @param type The type of the transfer.
 * @param states A list of the the transfer states.
 * @return A list of TransferObserver of transfer records with the given
 *         type and state.
 */
public List<TransferObserver> getTransfersWithTypeAndStates(TransferType type, TransferState[] states) {
    final List<TransferObserver> transferObservers = new ArrayList<TransferObserver>();
    Cursor c = null;
    try {
        c = dbUtil.queryTransfersWithTypeAndStates(type, states);
        while (c.moveToNext()) {
            final int partNum = c.getInt(c.getColumnIndexOrThrow(TransferTable.COLUMN_PART_NUM));
            if (partNum != 0) {
                // skip parts of a multipart upload
                continue;
            }
            final int id = c.getInt(c.getColumnIndexOrThrow(TransferTable.COLUMN_ID));
            final TransferObserver to = new TransferObserver(id, dbUtil);
            to.updateFromDB(c);
            transferObservers.add(to);
        }
    } finally {
        if (c != null) {
            c.close();
        }
    }
    return transferObservers;
}

From source file:org.mythtv.service.dvr.v27.RecordedHelperV27.java

private void processProgramGroups(final Context context, final LocationProfile locationProfile,
        Program[] programs) throws RemoteException, OperationApplicationException {
    Log.v(TAG, "processProgramGroups : enter");

    if (null == context)
        throw new RuntimeException("RecordedHelperV27 is not initialized");

    Map<String, ProgramGroup> programGroups = new TreeMap<String, ProgramGroup>();
    for (Program program : programs) {

        if (null != program.getRecording()) {

            if (null != program.getRecording().getRecGroup()
                    && !"livetv".equalsIgnoreCase(program.getRecording().getRecGroup())
                    && !"deleted".equalsIgnoreCase(program.getRecording().getRecGroup())) {
                String cleaned = ArticleCleaner.clean(program.getTitle());
                if (!programGroups.containsKey(cleaned)) {

                    ProgramGroup programGroup = new ProgramGroup();
                    programGroup.setTitle(program.getTitle());
                    programGroup.setCategory(program.getCategory());
                    programGroup.setInetref(program.getInetref());
                    programGroup.setSort(0);

                    programGroups.put(cleaned, programGroup);
                }// www .java 2  s. com

            }

        }

    }

    int processed = -1;
    int count = 0;

    ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();

    Log.v(TAG, "processProgramGroups : adding 'All' program group in programGroups");
    ProgramGroup all = new ProgramGroup(null, "All", "All", "All", "", 1);
    programGroups.put(all.getProgramGroup(), all);

    String[] programGroupProjection = new String[] { ProgramGroupConstants._ID };
    String programGroupSelection = ProgramGroupConstants.FIELD_PROGRAM_GROUP + " = ?";

    programGroupSelection = appendLocationHostname(context, locationProfile, programGroupSelection, null);

    for (String key : programGroups.keySet()) {
        Log.v(TAG, "processProgramGroups : processing programGroup '" + key + "'");

        ProgramGroup programGroup = programGroups.get(key);

        ContentValues programValues = convertProgramGroupToContentValues(locationProfile, programGroup);
        Cursor programGroupCursor = context.getContentResolver().query(ProgramGroupConstants.CONTENT_URI,
                programGroupProjection, programGroupSelection, new String[] { key }, null);
        if (programGroupCursor.moveToFirst()) {

            Long id = programGroupCursor
                    .getLong(programGroupCursor.getColumnIndexOrThrow(ProgramGroupConstants._ID));
            ops.add(ContentProviderOperation
                    .newUpdate(ContentUris.withAppendedId(ProgramGroupConstants.CONTENT_URI, id))
                    .withValues(programValues).withYieldAllowed(true).build());

        } else {

            ops.add(ContentProviderOperation.newInsert(ProgramGroupConstants.CONTENT_URI)
                    .withValues(programValues).withYieldAllowed(true).build());
        }
        programGroupCursor.close();
        count++;

        if (count > 100) {
            Log.v(TAG, "processProgramGroups : applying batch for '" + count + "' transactions");

            processBatch(context, ops, processed, count);
        }

    }

    if (!ops.isEmpty()) {
        Log.v(TAG, "processProgramGroups : applying batch for '" + count + "' transactions");

        processBatch(context, ops, processed, count);
    }

    Log.v(TAG, "processProgramGroups : remove deleted program groups");
    ops = new ArrayList<ContentProviderOperation>();

    DateTime lastModified = new DateTime();
    lastModified = lastModified.minusHours(1);

    String deleteProgramGroupSelection = ProgramGroupConstants.FIELD_LAST_MODIFIED_DATE + " < ?";
    String[] deleteProgramGroupArgs = new String[] { String.valueOf(lastModified.getMillis()) };

    deleteProgramGroupSelection = appendLocationHostname(context, locationProfile, deleteProgramGroupSelection,
            ProgramGroupConstants.TABLE_NAME);

    ops.add(ContentProviderOperation.newDelete(ProgramGroupConstants.CONTENT_URI)
            .withSelection(deleteProgramGroupSelection, deleteProgramGroupArgs).withYieldAllowed(true).build());

    if (!ops.isEmpty()) {
        Log.v(TAG, "processProgramGroups : applying batch for '" + count + "' transactions");

        processBatch(context, ops, processed, count);
    }

    Log.v(TAG, "processProgramGroups : exit");
}

From source file:mobisocial.musubi.ui.fragments.FeedViewFragment.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mInputMethodManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
    mObserver = new ContentObserver(new Handler(mActivity.getMainLooper())) {
        @Override// w w w  . ja  va  2 s  . co  m
        public void onChange(boolean selfChange) {
            if (mObjects == null || mObjects.getCursor() == null || !isAdded()) {
                return;
            }

            // XXX Move this to WizardStepHandler-- register a content observer
            // there only when required.
            if (WizardStepHandler.isCurrentTask(mActivity, WizardStepHandler.TASK_EDIT_PICTURE)) {
                Cursor c = mObjects.getCursor();
                ObjectManager om = new ObjectManager(App.getDatabaseSource(mActivity));
                AppManager am = new AppManager(App.getDatabaseSource(mActivity));
                if (c.moveToFirst()) {
                    while (!c.isAfterLast()) {
                        long objId = c.getLong(c.getColumnIndexOrThrow(MObject.COL_ID));
                        MObject obj = om.getObjectForId(objId);
                        if (obj != null && am.getAppIdentifier(obj.appId_).startsWith("musubi.sketch")) {
                            WizardStepHandler.accomplishTask(mActivity, WizardStepHandler.TASK_EDIT_PICTURE);
                            break;
                        }
                        c.moveToNext();
                    }
                }
            }

            if (DBG)
                Log.d(TAG, "-- contentObserver observed change");
            getLoaderManager().restartLoader(0, getLoaderArgs(mTotal), FeedViewFragment.this);
        }
    };

    if (savedInstanceState != null) {
        mTotal = savedInstanceState.getInt(EXTRA_NUM_ITEMS);
        Log.d(TAG, "setting total from instance: " + mTotal);
    } else {
        Log.d(TAG, "using total " + mTotal);
    }

    if (DBG)
        Log.d(TAG, "-- onCreated");
    getLoaderManager().initLoader(0, getLoaderArgs(mTotal), this);
}

From source file:edu.stanford.mobisocial.dungbeetle.MessagingManagerThread.java

@Override
public void run() {
    ProfileScanningObjHandler profileScanningObjHandler = new ProfileScanningObjHandler();
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
    Set<Long> notSendingObjects = new HashSet<Long>();
    if (DBG)/*w  w  w. j a  va 2s  .  c om*/
        Log.i(TAG, "Running...");
    mMessenger.init();
    long max_sent = -1;
    while (!interrupted()) {
        mOco.waitForChange();
        mOco.clearChanged();
        Cursor objs = mHelper.queryUnsentObjects(max_sent);
        try {
            Log.i(TAG, "Sending " + objs.getCount() + " objects...");
            if (objs.moveToFirst())
                do {
                    Long objId = objs.getLong(objs.getColumnIndexOrThrow(DbObject._ID));
                    String jsonSrc = objs.getString(objs.getColumnIndexOrThrow(DbObject.JSON));

                    max_sent = objId.longValue();
                    JSONObject json = null;
                    if (jsonSrc != null) {
                        try {
                            json = new JSONObject(jsonSrc);
                        } catch (JSONException e) {
                            Log.e(TAG, "bad json", e);
                        }
                    } else {
                        json = new JSONObject();
                    }

                    if (json != null) {
                        /*
                         * if you update latest feed here then there is a
                         * race condition between when you put a message
                         * into your db, when you actually have a connection
                         * to send the message (which is here) when other
                         * people send you messages the processing gets all
                         * out of order, so instead we update latest
                         * immediately when you add messages into your db
                         * inside DBHelper.java addToFeed();
                         */
                        // mFeedModifiedObjHandler.handleObj(mContext,
                        // feedUri, objId);

                        // TODO: Don't be fooled! This is not truly an
                        // EncodedObj
                        // and does not yet have a hash.
                        DbObj signedObj = App.instance().getMusubi().objForId(objId);
                        if (signedObj == null) {
                            Log.e(TAG, "Error, object " + objId + " not found in database");
                            notSendingObjects.add(objId);
                            continue;
                        }
                        DbEntryHandler h = DbObjects.getObjHandler(json);
                        h.afterDbInsertion(mContext, signedObj);

                        // TODO: Constraint error thrown for now b/c local
                        // user not in contacts
                        profileScanningObjHandler.handleObj(mContext, h, signedObj);
                    }

                    OutgoingMessage m = new OutgoingMsg(objs);
                    if (m.contents().getRecipients().isEmpty()) {
                        Log.w(TAG, "No addressees for direct message " + objId);
                        notSendingObjects.add(objId);
                    } else {
                        mMessenger.sendMessage(m);
                    }
                } while (objs.moveToNext());
            if (notSendingObjects.size() > 0) {
                if (DBG)
                    Log.d(TAG, "Marking " + notSendingObjects.size() + " objects sent");
                mHelper.markObjectsAsSent(notSendingObjects);
                notSendingObjects.clear();
            }
        } catch (Exception e) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) {
                Log.wtf(TAG, "error running notify loop", e);
            } else {
                Log.e(TAG, "error running notify loop", e);
            }
        } finally {
            objs.close();
        }
    }
    mHelper.close();
}

From source file:com.amazonaws.mobileconnectors.s3.transferutility.TransferDBUtil.java

/**
 * Queries the transfer record specified by main upload id.
 *
 * @param mainUploadId The mainUploadId of a multipart upload task
 * @return The bytes already uploaded for this multipart upload task
 *//* ww  w  .j  av a 2  s  .c  om*/
public long queryBytesTransferredByMainUploadId(int mainUploadId) {
    Cursor c = null;
    long bytesTotal = 0;
    try {
        c = transferDBBase.query(getPartUri(mainUploadId), null, null, null, null);
        while (c.moveToNext()) {
            final String state = c.getString(c.getColumnIndexOrThrow(TransferTable.COLUMN_STATE));
            if (TransferState.PART_COMPLETED.equals(TransferState.getState(state))) {
                bytesTotal += c.getLong(c.getColumnIndexOrThrow(TransferTable.COLUMN_BYTES_TOTAL));
            }
        }
    } finally {
        if (c != null) {
            c.close();
        }
    }
    return bytesTotal;
}

From source file:com.uproot.trackme.LocationActivity.java

public void showData() throws IOException {

    SQLiteDatabase db = null;//from  w  w  w.j a v  a2s.co m
    Cursor cursor = null;
    db = openOrCreateDatabase(DATABASE_NAME, SQLiteDatabase.OPEN_READWRITE, null);
    cursor = db.rawQuery("SELECT * " + " FROM " + POINTS_TABLE_NAME + " ORDER BY GMTTIMESTAMP ASC", null);

    StringBuffer str = new StringBuffer(
            "<session id=\"chetan123\" userid=\"" + userid + "\" passkey=\"" + passkey + "\">");

    int latitudeColumnIndex = cursor.getColumnIndexOrThrow("LATITUDE");
    int longitudeColumnIndex = cursor.getColumnIndexOrThrow("LONGITUDE");
    int TSColumnIndex = cursor.getColumnIndexOrThrow("GMTTIMESTAMP");
    int ACCColumnIndex = cursor.getColumnIndexOrThrow("ACCURACY");
    if (cursor.moveToFirst()) {
        do {
            double latitude = cursor.getDouble(latitudeColumnIndex);
            double longitude = cursor.getDouble(longitudeColumnIndex);
            long timestamp = (long) cursor.getDouble(TSColumnIndex);
            long accuracy = (long) cursor.getDouble(ACCColumnIndex);
            str.append("<location latitude=\"");
            str.append(latitude);
            str.append("\" longitude=\"");
            str.append(longitude);
            str.append("\" accuracy=\"");
            str.append(accuracy);
            str.append("\" timestamp=\"");
            str.append(timestamp);
            str.append("\" />");
        } while (cursor.moveToNext());
        str.append("</session>");
        fileContents = str.toString();
    }
    db.close();
}

From source file:com.amazonaws.mobileconnectors.s3.transferutility.TransferDBUtil.java

/**
 * Queries all the PartETags of completed parts from the multipart upload
 * specified by the mainUploadId. The list of PartETags is used to complete
 * a multiart upload, so it's usually called after all partUpload tasks are
 * finished./* w  w  w  .  ja v  a 2s  .  com*/
 *
 * @param mainUploadId The mainUploadId of a multipart upload task
 * @return A list of PartEtag of completed parts
 */
public List<PartETag> queryPartETagsOfUpload(int mainUploadId) {
    final List<PartETag> partETags = new ArrayList<PartETag>();
    Cursor c = null;
    int partNum = 0;
    String eTag = null;
    try {
        c = transferDBBase.query(getPartUri(mainUploadId), null, null, null, null);
        while (c.moveToNext()) {
            partNum = c.getInt(c.getColumnIndexOrThrow(TransferTable.COLUMN_PART_NUM));
            eTag = c.getString(c.getColumnIndexOrThrow(TransferTable.COLUMN_ETAG));
            partETags.add(new PartETag(partNum, eTag));
        }
    } finally {
        if (c != null) {
            c.close();
        }
    }
    return partETags;
}

From source file:com.android.messaging.mmslib.pdu.PduPersister.java

/**
 * This method expects uri in the following format
 *     content://media/<table_name>/<row_index> (or)
 *     file://sdcard/test.mp4/*from ww w. ja  v a 2  s . co  m*/
 *     http://test.com/test.mp4
 *
 * Here <table_name> shall be "video" or "audio" or "images"
 * <row_index> the index of the content in given table
 */
public static String convertUriToPath(final Context context, final Uri uri) {
    String path = null;
    if (null != uri) {
        final String scheme = uri.getScheme();
        if (null == scheme || scheme.equals("") || scheme.equals(ContentResolver.SCHEME_FILE)) {
            path = uri.getPath();

        } else if (scheme.equals("http")) {
            path = uri.toString();

        } else if (scheme.equals(ContentResolver.SCHEME_CONTENT)) {
            final String[] projection = new String[] { MediaStore.MediaColumns.DATA };
            Cursor cursor = null;
            try {
                cursor = context.getContentResolver().query(uri, projection, null, null, null);
                if (null == cursor || 0 == cursor.getCount() || !cursor.moveToFirst()) {
                    throw new IllegalArgumentException("Given Uri could not be found" + " in media store");
                }
                final int pathIndex = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
                path = cursor.getString(pathIndex);
            } catch (final SQLiteException e) {
                throw new IllegalArgumentException(
                        "Given Uri is not formatted in a way " + "so that it can be found in media store.");
            } finally {
                if (null != cursor) {
                    cursor.close();
                }
            }
        } else {
            throw new IllegalArgumentException("Given Uri scheme is not supported");
        }
    }
    return path;
}