Example usage for android.database Cursor getColumnIndex

List of usage examples for android.database Cursor getColumnIndex

Introduction

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

Prototype

int getColumnIndex(String columnName);

Source Link

Document

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

Usage

From source file:com.QuarkLabs.BTCeClient.UpdateWidgetsTask.java

@Override
protected JSONObject doInBackground(Void... params) {
    Set<String> set = new HashSet<>();
    JSONObject response = null;/*  www .  ja  v a 2s  . c  om*/
    for (int x : mMap.keySet()) {
        set.add(mMap.get(x));
    }
    try {
        response = App.getPairInfo(set.toArray(new String[set.size()]));
        response = response == null ? new JSONObject() : response;
        Context context = mContext.get();
        if (context == null) {
            return null;
        }
        DBWorker dbWorker = DBWorker.getInstance(context);
        String[] columns = { "pair", "last" };
        Cursor cursor = dbWorker.pullWidgetData(columns);
        Map<String, Double> values = new HashMap<>();
        if (cursor.moveToFirst()) {
            while (!cursor.isAfterLast()) {
                values.put(cursor.getString(cursor.getColumnIndex(columns[0])),
                        cursor.getDouble(cursor.getColumnIndex(columns[1])));
                cursor.moveToNext();
            }
        }
        cursor.close();
        for (@SuppressWarnings("unchecked")
        Iterator<String> x = response.keys(); x.hasNext();) {
            String pair = x.next();
            String pairInDB = pair.replace("_", "/").toUpperCase(Locale.US);
            ContentValues cv = new ContentValues(4);
            double last = response.getJSONObject(pair).getDouble("last");
            double sell = response.getJSONObject(pair).getDouble("sell");
            double buy = response.getJSONObject(pair).getDouble("buy");
            cv.put("last", last);
            cv.put("buy", buy);
            cv.put("sell", sell);
            if (values.containsKey(pairInDB)) {
                if (last >= values.get(pairInDB)) {
                    response.getJSONObject(pair).put("color", "green");
                } else {
                    response.getJSONObject(pair).put("color", "red");
                }
            } else {
                response.getJSONObject(pair).put("color", "green");
            }

            int result = dbWorker.updateWidgetData(cv, pair.replace("_", "/").toUpperCase(Locale.US));
            if (result == 0) {
                cv.put("pair", pair.replace("_", "/").toUpperCase(Locale.US));
                dbWorker.insertToWidgetData(cv);
            }
        }

    } catch (JSONException e) {
        e.printStackTrace();
    }
    return response;
}

From source file:de.tudarmstadt.dvs.myhealthassistant.myhealthhub.services.transformationmanager.database.LocalTransformationDBMS.java

public ArrayList<String> getAllAvalDate() {
    ArrayList<String> list = new ArrayList<String>();
    String q = "SELECT * FROM " + LocalTransformationDB.TABLE_DATE_TO_TRAFFIC + " ORDER BY "
            + LocalTransformationDB.COLUMN_DATE_ID + ";";
    Cursor cursor = database.rawQuery(q, null);
    if (cursor.moveToFirst()) {
        do {// www  .  java 2  s  .  c  o m
            String date = cursor.getString(cursor.getColumnIndex(LocalTransformationDB.COLUMN_DATE_TEXT));
            if (!list.contains(date))
                list.add(date);
        } while (cursor.moveToNext());
    }
    cursor.close();

    Collections.sort(list, new Comparator<String>() {

        @Override
        public int compare(String arg0, String arg1) {
            SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
            int compareResult = 0;
            try {
                Date arg0Date = format.parse(arg0);
                Date arg1Date = format.parse(arg1);
                compareResult = arg0Date.compareTo(arg1Date);
            } catch (ParseException e) {
                e.printStackTrace();
                compareResult = arg0.compareTo(arg1);
            }
            return compareResult;
        }
    });

    for (String s : list) {
        Log.e(TAG, "AvalDate:" + s);
    }
    return list;
}

From source file:com.android.unit_tests.CheckinProviderTest.java

@MediumTest
public void testEventReport() {
    long start = System.currentTimeMillis();
    ContentResolver r = getContext().getContentResolver();
    Checkin.logEvent(r, Checkin.Events.Tag.TEST, "Test Value");

    Cursor c = r.query(Checkin.Events.CONTENT_URI, null, Checkin.Events.TAG + "=?",
            new String[] { Checkin.Events.Tag.TEST.toString() }, null);

    long id = -1;
    while (c.moveToNext()) {
        String tag = c.getString(c.getColumnIndex(Checkin.Events.TAG));
        String value = c.getString(c.getColumnIndex(Checkin.Events.VALUE));
        long date = c.getLong(c.getColumnIndex(Checkin.Events.DATE));
        assertEquals(Checkin.Events.Tag.TEST.toString(), tag);
        if ("Test Value".equals(value) && date >= start) {
            assertTrue(id < 0);//from  w w w .j  a  v  a 2  s.  c o  m
            id = c.getInt(c.getColumnIndex(Checkin.Events._ID));
        }
    }
    assertTrue(id > 0);

    int rows = r.delete(ContentUris.withAppendedId(Checkin.Events.CONTENT_URI, id), null, null);
    assertEquals(1, rows);
    c.requery();
    while (c.moveToNext()) {
        long date = c.getLong(c.getColumnIndex(Checkin.Events.DATE));
        assertTrue(date < start); // Have deleted the only newer TEST.
    }

    c.close();
}

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

public static U1Node getNodeByResourcePath(String resourcePath) {
    String[] selectionArgs = new String[] { resourcePath };
    String selection = Nodes.NODE_RESOURCE_PATH + "=?";
    String[] projection = Nodes.getDefaultProjection();
    final Cursor c = sResolver.query(Nodes.CONTENT_URI, projection, selection, selectionArgs, null);
    if (c != null) {
        try {//  w  w  w.ja va  2s  . co  m
            if (c.moveToFirst()) {
                String key;
                U1NodeKind kind;
                Boolean isLive = true;
                String path;
                String parentPath;
                String volumePath;
                Date whenCreated;
                Date whenChanged;
                Long generation;
                Long generationCreated;
                String contentPath;

                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));

                return new U1Node(resourcePath, kind, isLive, path, parentPath, volumePath, key, whenCreated,
                        whenChanged, generation, generationCreated, contentPath);
            } else {
                return null;
            }
        } finally {
            c.close();
        }
    }
    return null;
}

From source file:com.tct.email.provider.EmailMessageCursor.java

public EmailMessageCursor(final Context c, final Cursor cursor, final String htmlColumn,
        final String textColumn) {
    super(cursor);
    mHtmlColumnIndex = cursor.getColumnIndex(htmlColumn);
    mTextColumnIndex = cursor.getColumnIndex(textColumn);
    final int cursorSize = cursor.getCount();
    mHtmlParts = new SparseArray<String>(cursorSize);
    mTextParts = new SparseArray<String>(cursorSize);
    //TS: jian.xu 2015-11-03 EMAIL BUGFIX-845079 ADD_S
    mHtmlLinkifyColumnIndex = cursor.getColumnIndex(UIProvider.MessageColumns.BODY_HTML_LINKIFY);
    mHtmlLinkifyParts = new SparseArray<String>(cursorSize);
    mTextLinkifyColumnIndex = cursor.getColumnIndex(UIProvider.MessageColumns.BODY_TEXT_LINKIFY);
    mTextLinkifyParts = new SparseArray<String>(cursorSize);
    //TS: jian.xu 2015-11-03 EMAIL BUGFIX-845079 ADD_E

    final ContentResolver cr = c.getContentResolver();

    while (cursor.moveToNext()) {
        final int position = cursor.getPosition();
        final long messageId = cursor.getLong(cursor.getColumnIndex(BaseColumns._ID));
        // TS: chao.zhang 2015-09-14 EMAIL BUGFIX-1039046  MOD_S
        InputStream htmlIn = null;
        InputStream textIn = null;
        try {// w  ww  . j  ava2 s  . c om
            if (mHtmlColumnIndex != -1) {
                final Uri htmlUri = Body.getBodyHtmlUriForMessageWithId(messageId);
                //WARNING: Actually openInput will used 2 PIPE(FD) to connect,but if some exception happen during connect,
                //such as fileNotFoundException,maybe the connection will not be closed. just a try!!!
                htmlIn = cr.openInputStream(htmlUri);
                final String underlyingHtmlString;
                try {
                    underlyingHtmlString = IOUtils.toString(htmlIn);
                } finally {
                    htmlIn.close();
                    htmlIn = null;
                }
                //TS: zhaotianyong 2015-04-05 EMAIL BUGFIX_964325 MOD_S
                final String sanitizedHtml = HtmlSanitizer.sanitizeHtml(underlyingHtmlString);
                mHtmlParts.put(position, sanitizedHtml);
                //TS: zhaotianyong 2015-04-05 EMAIL BUGFIX_964325 MOD_E
                //TS: jian.xu 2015-11-03 EMAIL BUGFIX-845079 ADD_S
                //NOTE: add links for sanitized html
                if (!TextUtils.isEmpty(sanitizedHtml)) {
                    final String linkifyHtml = com.tct.mail.utils.Linkify.addLinks(sanitizedHtml);
                    mHtmlLinkifyParts.put(position, linkifyHtml);
                } else {
                    mHtmlLinkifyParts.put(position, "");
                }
                //TS: jian.xu 2015-11-03 EMAIL BUGFIX-845079 ADD_E
            }
        } catch (final IOException e) {
            LogUtils.v(LogUtils.TAG, e, "Did not find html body for message %d", messageId);
        } catch (final OutOfMemoryError oom) {
            LogUtils.v(LogUtils.TAG, oom,
                    "Terrible,OOM happen durning query EmailMessageCursor in bodyHtml,current message %d",
                    messageId);
            mHtmlLinkifyParts.put(position, "");
        }
        try {
            if (mTextColumnIndex != -1) {
                final Uri textUri = Body.getBodyTextUriForMessageWithId(messageId);
                textIn = cr.openInputStream(textUri);
                final String underlyingTextString;
                try {
                    underlyingTextString = IOUtils.toString(textIn);
                } finally {
                    textIn.close();
                    textIn = null;
                }
                mTextParts.put(position, underlyingTextString);
                //TS: jian.xu 2015-11-03 EMAIL BUGFIX-845079 ADD_S
                //NOTE: add links for underlying text string
                if (!TextUtils.isEmpty(underlyingTextString)) {
                    final SpannableString spannable = new SpannableString(underlyingTextString);
                    Linkify.addLinks(spannable,
                            Linkify.EMAIL_ADDRESSES | Linkify.WEB_URLS | Linkify.PHONE_NUMBERS);
                    final String linkifyText = Html.toHtml(spannable);
                    mTextLinkifyParts.put(position, linkifyText);
                } else {
                    mTextLinkifyParts.put(position, "");
                }
                //TS: jian.xu 2015-11-03 EMAIL BUGFIX-845079 ADD_E
            }
        } catch (final IOException e) {
            LogUtils.v(LogUtils.TAG, e, "Did not find text body for message %d", messageId);
        } catch (final OutOfMemoryError oom) {
            LogUtils.v(LogUtils.TAG, oom,
                    "Terrible,OOM happen durning query EmailMessageCursor in bodyText,current message %d",
                    messageId);
            mTextLinkifyParts.put(position, "");
        }
        //NOTE:Remember that this just a protective code,for better release Not used Resources.
        if (htmlIn != null) {
            try {
                htmlIn.close();
            } catch (IOException e1) {
                LogUtils.v(LogUtils.TAG, e1, "IOException happen while close the htmlInput connection ");
            }
        }
        if (textIn != null) {
            try {
                textIn.close();
            } catch (IOException e2) {
                LogUtils.v(LogUtils.TAG, e2, "IOException happen while close the textInput connection ");
            }
        } // TS: chao.zhang 2015-09-14 EMAIL BUGFIX-1039046  MOD_E
    }
    cursor.moveToPosition(-1);
}

From source file:Main.java

@TargetApi(19)
public static File getFromMediaUri(Context context, ContentResolver resolver, Uri uri) {
    if (uri == null)
        return null;

    if (SCHEME_FILE.equals(uri.getScheme())) {
        return new File(uri.getPath());
    } else if (SCHEME_CONTENT.equals(uri.getScheme())) {
        String filePath = "";
        if (isMediaDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            Uri contentUri = null;//  w  w  w . j  av  a  2 s. com
            if ("image".equals(type)) {
                contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            }
            final String selection = "_id=?";
            final String[] selectionArgs = new String[] { split[1] };

            Cursor cursor = null;
            final String column = "_data";
            final String[] projection = { column };

            try {
                cursor = context.getContentResolver().query(contentUri, projection, selection, selectionArgs,
                        null);
                if (cursor != null && cursor.moveToFirst()) {
                    final int column_index = cursor.getColumnIndexOrThrow(column);
                    filePath = cursor.getString(column_index);
                }
            } finally {
                if (cursor != null)
                    cursor.close();
            }
        } else {
            final String[] filePathColumn = { MediaStore.MediaColumns.DATA,
                    MediaStore.MediaColumns.DISPLAY_NAME };
            Cursor cursor = null;
            try {
                cursor = resolver.query(uri, filePathColumn, null, null, null);
                if (cursor != null && cursor.moveToFirst()) {
                    final int columnIndex = (uri.toString()
                            .startsWith("content://com.google.android.gallery3d"))
                                    ? cursor.getColumnIndex(MediaStore.MediaColumns.DISPLAY_NAME)
                                    : cursor.getColumnIndex(MediaStore.MediaColumns.DATA);
                    // Picasa images on API 13+
                    if (columnIndex != -1) {
                        filePath = cursor.getString(columnIndex);
                    }
                }
            } catch (IllegalArgumentException e) {
                // Google Drive images
                return getFromMediaUriPfd(context, resolver, uri);
            } catch (SecurityException ignored) {
                // Nothing we can do
            } finally {
                if (cursor != null)
                    cursor.close();
            }
        }

        if (!TextUtils.isEmpty(filePath)) {
            return new File(filePath);
        }
    }
    return null;
}

From source file:com.taxicop.sync.SyncAdapter.java

public int queryLastId(ContentProviderClient provider) {
    Cursor c = null;
    int id = 0;// www.j a  v  a  2s  .  com
    try {
        c = provider.query(PlateContentProvider.URI_USERS, null, null, null, null);
        if (c.moveToFirst())
            id = c.getInt(c.getColumnIndex(Fields.ITH));

    } catch (Exception e) {
        Log.e(TAG, "lastId= " + e.getMessage());
    }
    c.close();
    return id;
}

From source file:com.notifry.android.database.NotifrySource.java

@Override
protected NotifrySource inflate(Context context, Cursor cursor) {
    NotifrySource source = new NotifrySource();
    source.setAccountName(cursor.getString(cursor.getColumnIndex(NotifryDatabaseAdapter.KEY_ACCOUNT_NAME)));
    source.setId(cursor.getLong(cursor.getColumnIndex(NotifryDatabaseAdapter.KEY_ID)));
    source.setServerEnabled(/*from  ww w . j a v a 2s  . c  om*/
            cursor.getLong(cursor.getColumnIndex(NotifryDatabaseAdapter.KEY_SERVER_ENABLED)) == 0 ? false
                    : true);
    source.setLocalEnabled(
            cursor.getLong(cursor.getColumnIndex(NotifryDatabaseAdapter.KEY_LOCAL_ENABLED)) == 0 ? false
                    : true);
    source.setServerId(cursor.getLong(cursor.getColumnIndex(NotifryDatabaseAdapter.KEY_SERVER_ID)));
    source.setTitle(cursor.getString(cursor.getColumnIndex(NotifryDatabaseAdapter.KEY_TITLE)));
    source.setChangeTimestamp(
            cursor.getString(cursor.getColumnIndex(NotifryDatabaseAdapter.KEY_CHANGE_TIMESTAMP)));
    source.setSourceKey(cursor.getString(cursor.getColumnIndex(NotifryDatabaseAdapter.KEY_SOURCE_KEY)));

    source.setUseGlobalNotification(
            cursor.getLong(cursor.getColumnIndex(NotifryDatabaseAdapter.KEY_USE_GLOBAL_NOTIFICATION)) == 0
                    ? false
                    : true);
    source.setVibrate(
            cursor.getLong(cursor.getColumnIndex(NotifryDatabaseAdapter.KEY_VIBRATE)) == 0 ? false : true);
    source.setRingtone(
            cursor.getLong(cursor.getColumnIndex(NotifryDatabaseAdapter.KEY_RINGTONE)) == 0 ? false : true);
    source.setLedFlash(
            cursor.getLong(cursor.getColumnIndex(NotifryDatabaseAdapter.KEY_LED_FLASH)) == 0 ? false : true);
    source.setCustomRingtone(
            cursor.getString(cursor.getColumnIndex(NotifryDatabaseAdapter.KEY_CUSTOM_RINGTONE)));
    source.setSpeakMessage(
            cursor.getLong(cursor.getColumnIndex(NotifryDatabaseAdapter.KEY_SPEAK_MESSAGE)) == 0 ? false
                    : true);

    return source;
}

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

public static U1Node getNodeByKey(String key) {
    String[] selectionArgs = new String[] { key };
    String selection = Nodes.NODE_KEY + "=?";
    String[] projection = Nodes.getDefaultProjection();
    final Cursor c = sResolver.query(Nodes.CONTENT_URI, projection, selection, selectionArgs, null);
    if (c != null) {
        try {//from  w  w  w . j a v a  2 s  .co  m
            if (c.moveToFirst()) {
                String resourcePath;
                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));
                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));

                return new U1Node(resourcePath, kind, isLive, path, parentPath, volumePath, key, whenCreated,
                        whenChanged, generation, generationCreated, contentPath);
            } else {
                return null;
            }
        } finally {
            c.close();
        }
    }
    return null;
}

From source file:de.tudarmstadt.dvs.myhealthassistant.myhealthhub.services.transformationmanager.database.LocalTransformationDBMS.java

private Transformation cursorToTransformation(Cursor cursor, int position) {

    if (cursor.moveToPosition(position)) {

        Transformation transformation = new Transformation(
                cursor.getLong(cursor.getColumnIndex(LocalTransformationDB.COLUMN_BUNDLE_ID)),
                cursor.getString(cursor.getColumnIndex(LocalTransformationDB.COLUMN_TRANSFORMATION_NAME)),
                cursor.getString(cursor.getColumnIndex(LocalTransformationDB.COLUMN_PRODUCED_EVENT_TYPE)),
                cursor.getInt(cursor.getColumnIndex(LocalTransformationDB.COLUMN_TRANSFORMATION_COSTS)));

        String requiredEventTypes = cursor
                .getString(cursor.getColumnIndex(LocalTransformationDB.COLUMN_REQUIRED_EVENT_TYPES));
        String[] types = requiredEventTypes.split(";");
        for (String type : types) {
            if (D)
                Log.d(TAG, "required event type: " + type);
            transformation.addRequiredEvent(type);
        }/*from  www  . j ava2 s .c  o  m*/

        return transformation;

    } else
        return null;
}