Example usage for android.database Cursor getString

List of usage examples for android.database Cursor getString

Introduction

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

Prototype

String getString(int columnIndex);

Source Link

Document

Returns the value of the requested column as a String.

Usage

From source file:eu.e43.impeller.Utils.java

public static JSONObject findPost(Context ctx, Content.Uris uris, JSONObject object) throws JSONException {
    Cursor res = ctx.getContentResolver().query(uris.activitiesUri, new String[] { "_json" },
            "actor=? AND verb='post' AND object.id=?",
            new String[] { object.getJSONObject("author").getString("id"), object.getString("id") }, null);

    try {/*  www. java 2  s  .  co m*/
        if (res.getCount() > 0) {
            res.moveToFirst();
            return new JSONObject(res.getString(0));
        } else {
            return null;
        }
    } finally {
        res.close();
    }
}

From source file:com.gmail.nagamatu.radiko.installer.RadikoInstallerActivity.java

private static String getDeviceId(Context context) {
    String id = null;/*from  w  w w .  ja va2 s .  c o  m*/
    Cursor c = context.getContentResolver().query(URI_GFS_SERVICE, null, null, new String[] { "android_id" },
            null);
    try {
        c.moveToFirst();
        id = Long.toHexString(Long.parseLong(c.getString(1)));
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (c != null) {
            c.close();
        }
    }
    return id;
}

From source file:org.c99.SyncProviderDemo.ContactsSyncAdapterService.java

private static void updateContactStatus(ArrayList<ContentProviderOperation> operationList, long rawContactId,
        String status) {//from w w w.j  ava2  s . c o  m
    Uri rawContactUri = ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId);
    Uri entityUri = Uri.withAppendedPath(rawContactUri, Entity.CONTENT_DIRECTORY);
    Cursor c = mContentResolver.query(entityUri,
            new String[] { RawContacts.SOURCE_ID, Entity.DATA_ID, Entity.MIMETYPE, Entity.DATA1 }, null, null,
            null);
    try {
        while (c.moveToNext()) {
            if (!c.isNull(1)) {
                String mimeType = c.getString(2);

                if (mimeType.equals("vnd.android.cursor.item/vnd.org.c99.SyncProviderDemo.profile")) {
                    ContentProviderOperation.Builder builder = ContentProviderOperation
                            .newInsert(ContactsContract.StatusUpdates.CONTENT_URI);
                    builder.withValue(ContactsContract.StatusUpdates.DATA_ID, c.getLong(1));
                    builder.withValue(ContactsContract.StatusUpdates.STATUS, status);
                    builder.withValue(ContactsContract.StatusUpdates.STATUS_RES_PACKAGE,
                            "org.c99.SyncProviderDemo");
                    builder.withValue(ContactsContract.StatusUpdates.STATUS_LABEL, R.string.app_name);
                    builder.withValue(ContactsContract.StatusUpdates.STATUS_ICON, R.drawable.logo);
                    builder.withValue(ContactsContract.StatusUpdates.STATUS_TIMESTAMP,
                            System.currentTimeMillis());
                    operationList.add(builder.build());

                    //Only change the text of our custom entry to the status message pre-Honeycomb, as the newer contacts app shows
                    //statuses elsewhere
                    if (Integer.decode(Build.VERSION.SDK) < 11) {
                        builder = ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI);
                        builder.withSelection(BaseColumns._ID + " = '" + c.getLong(1) + "'", null);
                        builder.withValue(ContactsContract.Data.DATA3, status);
                        operationList.add(builder.build());
                    }
                }
            }
        }
    } finally {
        c.close();
    }
}

From source file:im.delight.android.commons.Social.java

/**
 * Returns a list of phone numbers for the contact with the given lookup ID
 *
 * @param contactLookupId a contact's lookup ID to get the phone numbers for
 * @param context a context reference//from   ww w  .j a  v a2  s.  c  o  m
 * @return CharSequence[] a list of all phone numbers for the given contact or `null`
 */
public static CharSequence[] getContactPhone(final String contactLookupId, final Context context) {
    final Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
    final String[] projection = new String[] { ContactsContract.CommonDataKinds.Phone.NUMBER };
    final String where = ContactsContract.Contacts.LOOKUP_KEY + " = ?";
    final String[] selectionArgs = new String[] { contactLookupId };
    final String sortOrder = null;

    Cursor result = context.getContentResolver().query(uri, projection, where, selectionArgs, sortOrder);

    String phone;
    if (result != null) {
        if (result.getCount() > 0) {
            final CharSequence[] res = new CharSequence[result.getCount()];

            int i = 0;
            while (result.moveToNext()) {
                phone = result.getString(result.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

                if (phone != null) {
                    res[i] = phone;
                    i++;
                }
            }

            result.close();

            return res;
        } else {
            result.close();

            return null;
        }
    } else {
        return null;
    }
}

From source file:im.delight.android.commons.Social.java

/**
 * Returns a list of email addresses for the contact with the given lookup ID
 *
 * @param contactLookupId a contact's lookup ID to get the email addresses for
 * @param context a context reference/*from www . java 2 s .c  om*/
 * @return CharSequence[] a list of all email addresses for the given contact or `null`
 */
public static CharSequence[] getContactEmail(final String contactLookupId, final Context context) {
    final Uri uri = ContactsContract.CommonDataKinds.Email.CONTENT_URI;
    final String[] projection = new String[] { ContactsContract.CommonDataKinds.Email.DATA };
    final String where = ContactsContract.Contacts.LOOKUP_KEY + " = ?";
    final String[] selectionArgs = new String[] { contactLookupId };
    final String sortOrder = null;

    Cursor result = context.getContentResolver().query(uri, projection, where, selectionArgs, sortOrder);

    String email;
    if (result != null) {
        if (result.getCount() > 0) {
            final CharSequence[] res = new CharSequence[result.getCount()];

            int i = 0;
            while (result.moveToNext()) {
                email = result.getString(result.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));

                if (email != null) {
                    res[i] = email;
                    i++;
                }
            }

            result.close();

            return res;
        } else {
            result.close();

            return null;
        }
    } else {
        return null;
    }
}

From source file:org.zoumbox.mh_dla_notifier.sp.PublicScriptsProxy.java

public static List<MhSpRequest> listLatestRequests(Context context, String trollId, int count) {
    List<MhSpRequest> result = new ArrayList<MhSpRequest>();

    String query = String.format(SQL_LIST_REQUESTS, count);

    MhDlaSQLHelper helper = new MhDlaSQLHelper(context);
    SQLiteDatabase database = helper.getReadableDatabase();

    Calendar calendar = Calendar.getInstance();

    Cursor cursor = database.rawQuery(query, new String[] { trollId });
    while (cursor.moveToNext()) {
        long startTimeMillis = cursor.getLong(0);
        long endTimeMillis = cursor.getLong(1);
        String scriptName = cursor.getString(2);
        String status = cursor.getString(3);

        calendar.setTimeInMillis(startTimeMillis);
        Date date = calendar.getTime();
        PublicScript script = PublicScript.valueOf(scriptName);

        long duration = 0;
        if (endTimeMillis > 0) {
            duration = endTimeMillis - startTimeMillis;
        }/*from   ww w. j  a  v  a 2s.c om*/
        MhSpRequest request = new MhSpRequest(date, duration, script, status);
        result.add(request);
    }

    cursor.close();
    database.close();

    return result;
}

From source file:org.jsharkey.sky.webservice.WebserviceHelper.java

/**
 * Perform a webservice query to retrieve and store the forecast for the
 * given widget. This call blocks until request is finished and
 * {@link Forecasts#CONTENT_URI} has been updated.
 */// w  w  w . j a va  2 s  . c  o  m
public static void updateForecasts(Context context, Uri appWidgetUri, int days) throws ParseException {

    if (sUserAgent == null) {
        prepareUserAgent(context);
    }

    Uri appWidgetForecasts = Uri.withAppendedPath(appWidgetUri, AppWidgets.TWIG_FORECASTS);

    ContentResolver resolver = context.getContentResolver();

    Cursor cursor = null;
    double lat = Double.NaN;
    double lon = Double.NaN;
    String countryCode = null;

    // Pull exact forecast location from database
    try {
        cursor = resolver.query(appWidgetUri, PROJECTION_APPWIDGET, null, null, null);
        if (cursor != null && cursor.moveToFirst()) {
            lat = cursor.getDouble(COL_LAT);
            lon = cursor.getDouble(COL_LON);
            countryCode = cursor.getString(COL_COUNTRY_CODE);
        }
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }

    Log.d(TAG, "using country code=" + countryCode);

    // Query webservice for this location
    List<Forecast> forecasts = null;
    if (COUNTRY_US.equals(countryCode)) {
        forecasts = new NoaaSource().getForecasts(lat, lon, days);
    } else {
        forecasts = new MetarSource().getForecasts(lat, lon, days);
    }

    if (forecasts == null || forecasts.size() == 0) {
        throw new ParseException("No forecasts found from webservice query");
    }

    // Purge existing forecasts covered by incoming data, and anything
    // before today
    long lastMidnight = ForecastUtils.getLastMidnight();
    long earliest = Long.MAX_VALUE;
    for (Forecast forecast : forecasts) {
        earliest = Math.min(earliest, forecast.validStart);
    }

    resolver.delete(appWidgetForecasts, ForecastsColumns.VALID_START + " >= " + earliest + " OR "
            + ForecastsColumns.VALID_START + " <= " + lastMidnight, null);

    // Insert any new forecasts found
    ContentValues values = new ContentValues();
    for (Forecast forecast : forecasts) {
        Log.d(TAG, "inserting forecast with validStart=" + forecast.validStart);
        values.clear();
        values.put(ForecastsColumns.VALID_START, forecast.validStart);
        values.put(ForecastsColumns.TEMP_HIGH, forecast.tempHigh);
        values.put(ForecastsColumns.TEMP_LOW, forecast.tempLow);
        values.put(ForecastsColumns.CONDITIONS, forecast.conditions);
        values.put(ForecastsColumns.URL, forecast.url);
        if (forecast.alert) {
            values.put(ForecastsColumns.ALERT, ForecastsColumns.ALERT_TRUE);
        }
        resolver.insert(appWidgetForecasts, values);
    }

    // Mark widget cache as being updated
    values.clear();
    values.put(AppWidgetsColumns.LAST_UPDATED, System.currentTimeMillis());
    resolver.update(appWidgetUri, values, null, null);
}

From source file:com.nnm.smsviet.Message.java

/**
 * Get a {@link Message} from cache or {@link Cursor}.
 * /*from w  w  w  .j  av  a 2  s.co  m*/
 * @param context
 *            {@link Context}
 * @param cursor
 *            {@link Cursor}
 * @return {@link Message}
 */
public static Message getMessage(final Context context, final Cursor cursor) {
    synchronized (CACHE) {
        String body = cursor.getString(INDEX_BODY);
        int id = cursor.getInt(INDEX_ID);
        if (body == null) { // MMS
            id *= -1;
        }
        Message ret = CACHE.get(id);
        if (ret == null) {
            ret = new Message(context, cursor);
            CACHE.put(id, ret);
            Log.d(TAG, "cachesize: " + CACHE.size());
            while (CACHE.size() > CAHCESIZE) {
                Integer i = CACHE.keySet().iterator().next();
                Log.d(TAG, "rm msg. from cache: " + i);
                Message cc = CACHE.remove(i);
                if (cc == null) {
                    Log.w(TAG, "CACHE might be inconsistent!");
                    break;
                }
            }
        } else {
            ret.update(cursor);
        }
        return ret;
    }
}

From source file:Main.java

@Nullable
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())) {
        final String[] filePathColumn = { MediaStore.MediaColumns.DATA, MediaStore.MediaColumns.DISPLAY_NAME };
        Cursor cursor = null;
        try {// w w  w.  j a va2  s.  c o  m
            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) {
                    String filePath = cursor.getString(columnIndex);
                    if (!TextUtils.isEmpty(filePath)) {
                        return new File(filePath);
                    }
                }
            }
        } catch (IllegalArgumentException e) {
            // Google Drive images
            return getFromMediaUriPfd(context, resolver, uri);
        } catch (SecurityException ignored) {
            // Nothing we can do
        } finally {
            if (cursor != null)
                cursor.close();
        }
    }
    return null;
}

From source file:com.onesignal.NotificationOpenedProcessor.java

private static void addChildNotifications(JSONArray dataArray, String summaryGroup, SQLiteDatabase writableDb) {
    String[] retColumn = { NotificationTable.COLUMN_NAME_FULL_DATA };
    String[] whereArgs = { summaryGroup };

    Cursor cursor = writableDb.query(NotificationTable.TABLE_NAME, retColumn,
            NotificationTable.COLUMN_NAME_GROUP_ID + " = ? AND " + // Where String
                    NotificationTable.COLUMN_NAME_DISMISSED + " = 0 AND " + NotificationTable.COLUMN_NAME_OPENED
                    + " = 0 AND " + NotificationTable.COLUMN_NAME_IS_SUMMARY + " = 0",
            whereArgs, null, null, null);

    if (cursor.getCount() > 1) {
        cursor.moveToFirst();//  w ww  .j av  a 2 s.  co  m
        do {
            try {
                String jsonStr = cursor
                        .getString(cursor.getColumnIndex(NotificationTable.COLUMN_NAME_FULL_DATA));
                dataArray.put(new JSONObject(jsonStr));
            } catch (Throwable t) {
                OneSignal.Log(OneSignal.LOG_LEVEL.ERROR,
                        "Could not parse JSON of sub notification in group: " + summaryGroup);
            }
        } while (cursor.moveToNext());
    }

    cursor.close();
}