Example usage for android.database Cursor close

List of usage examples for android.database Cursor close

Introduction

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

Prototype

void close();

Source Link

Document

Closes the Cursor, releasing all of its resources and making it completely invalid.

Usage

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

static void notifyDependencies(DBHelper helper, ContentResolver resolver, String feedName) {
    Uri feedUri = Feed.uriForName(feedName);
    if (DBG)//from   w ww  . jav  a  2  s . c  om
        Log.d(TAG, "notifying dependencies of  " + feedUri);
    resolver.notifyChange(feedUri, null);
    resolver.notifyChange(Feed.uriForName(Feed.FEED_NAME_GLOBAL), null);
    if (feedName.contains(":")) {
        feedName = feedName.split(":")[0];
        resolver.notifyChange(Feed.uriForName(feedName), null);
    }
    Cursor c = helper.getFeedDependencies(feedName);
    try {
        while (c.moveToNext()) {
            Uri uri = Feed.uriForName(c.getString(0));
            resolver.notifyChange(uri, null);
        }
    } finally {
        c.close();
    }
}

From source file:org.jsharkey.sky.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 2s  .  com*/
public static void updateForecasts(Context context, Uri appWidgetUri, int days) throws ForecastParseException {

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

    ContentResolver resolver = context.getContentResolver();

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

    // 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);
        }
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }

    // Query webservice for this location
    List<Forecast> forecasts = queryLocation(lat, lon, days);

    if (forecasts == null || forecasts.size() == 0) {
        throw new ForecastParseException("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:edu.mit.mobile.android.locast.data.TaggableItem.java

/**
 * TODO make this pick the set of tags for a set of content.
 *
 * @param cr a content resolver/*w  w  w.  ja  v  a2  s. c  om*/
 * @return the top MAX_POPULAR_TAGS most popular tags in the set, with the most popular first.
 */
public static List<String> getPopularTags(ContentResolver cr) {

    final Map<String, Integer> tagPop = new HashMap<String, Integer>();
    final List<String> popTags;

    final Cursor c = cr.query(Tag.CONTENT_URI, Tag.DEFAULT_PROJECTION, null, null, null);
    final int tagColumn = c.getColumnIndex(Tag._NAME);

    for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
        final String tag = c.getString(tagColumn);

        final Integer count = tagPop.get(tag);
        if (count == null) {
            tagPop.put(tag, 1);
        } else {
            tagPop.put(tag, count + 1);
        }
    }
    c.close();

    popTags = new ArrayList<String>(tagPop.keySet());

    Collections.sort(popTags, new Comparator<String>() {
        public int compare(String object1, String object2) {
            return tagPop.get(object2).compareTo(tagPop.get(object1));
        }

    });
    int limit;
    if (popTags.size() < MAX_POPULAR_TAGS) {
        limit = popTags.size();
    } else {
        limit = MAX_POPULAR_TAGS;
    }
    return popTags.subList(0, limit);
}

From source file:nz.co.wholemeal.christchurchmetro.Stop.java

private static ArrayList<Stop> doArrayListQuery(Context context, String query) {
    ArrayList<Stop> stops = new ArrayList<Stop>();

    Log.d(TAG, "query: " + query);

    DatabaseHelper databaseHelper = new DatabaseHelper(context);
    SQLiteDatabase database = databaseHelper.getWritableDatabase();
    Cursor cursor = database.rawQuery(query, null);

    try {/* w w w.ja  v a  2s .  c  o m*/
        if (cursor.moveToFirst()) {
            do {
                Stop stop = new Stop();
                stop.platformTag = cursor.getString(0);
                stop.platformNumber = cursor.getString(1);
                stop.name = cursor.getString(2);
                stop.roadName = cursor.getString(3);
                stop.latitude = cursor.getDouble(4);
                stop.longitude = cursor.getDouble(5);
                stops.add(stop);
            } while (cursor.moveToNext());
        }
    } finally {
        cursor.close();
    }
    Log.d(TAG, "stops.size() = " + stops.size());
    database.close();
    return stops;
}

From source file:Main.java

public static File getFromMediaUri(ContentResolver resolver, Uri uri) {
    if (uri == null)
        return null;
    if ("file".equals(uri.getScheme())) {
        return new File(uri.getPath());
    } else if ("content".equals(uri.getScheme())) {
        final String[] filePathColumn = { MediaStore.MediaColumns.DATA, MediaStore.MediaColumns.DISPLAY_NAME };
        Cursor cursor = null;
        try {//w  w  w.  j  av  a2  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);
                if (columnIndex != -1) {
                    String filePath = cursor.getString(columnIndex);
                    if (!TextUtils.isEmpty(filePath)) {
                        return new File(filePath);
                    }
                }
            }
        } catch (SecurityException ignored) {
        } finally {
            if (cursor != null)
                cursor.close();
        }
    }
    return null;
}

From source file:Main.java

public static String queryAudioName(Context context, Uri name) {
    String audioId;/* w ww  .j a  v a  2  s .c  o m*/
    String uriName = name.toString();
    uriName = uriName.substring(uriName.lastIndexOf("/") + 1);
    Cursor cursor = context.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null,
            null, MediaStore.Audio.Media.DEFAULT_SORT_ORDER);
    if (cursor != null && cursor.getCount() > 0) {
        cursor.moveToFirst();
        int counter = cursor.getCount();
        for (int j = 0; j < counter; j++) {
            audioId = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media._ID));

            if (uriName.equals(audioId)) {
                uriName = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE));
            } else {
                Ringtone ringtone = RingtoneManager.getRingtone(context, name);
                uriName = ringtone.getTitle(context);
                break;
            }
            cursor.moveToNext();

        }
        cursor.close();
    } else {
        try {
            Ringtone ringtone = RingtoneManager.getRingtone(context, name);
            uriName = ringtone.getTitle(context);
        } catch (Exception e) {
            return uriName;
        }
    }
    return uriName;
}

From source file:ro.weednet.contactssync.platform.ContactManager.java

public static int getLocalContactsCount(Context context, Account account) {
    Log.i(TAG, "*** Counting local contacts");

    final Uri uri = RawContacts.CONTENT_URI.buildUpon()
            .appendQueryParameter(RawContacts.ACCOUNT_NAME, account.name)
            .appendQueryParameter(RawContacts.ACCOUNT_TYPE, account.type).build();

    final ContentResolver resolver = context.getContentResolver();
    final Cursor c = resolver.query(uri, new String[] { Contacts._ID, RawContacts.SOURCE_ID }, null, null,
            null);/* ww w .  j  a va2s.c  om*/

    int count = 0;
    try {
        count = c.getCount();
    } catch (Exception e) {
    } finally {
        if (c != null) {
            c.close();
        }
    }

    Log.i(TAG, "*** ... found " + count);
    return count;
}

From source file:cc.softwarefactory.lokki.android.utilities.Utils.java

public static Bitmap getPhotoFromEmail(Context context, String email) {

    if (context == null || email == null) {
        return null;
    }// w  ww  . j a va  2 s.  co m

    Bitmap result = MainApplication.avatarCache.get(email);
    if (result != null) {
        Log.e(TAG, "getPhotoFromEmail IN cache, Email: " + email);
        return result;
    }

    if (loadContacts(context)) {
        try {
            Log.e(TAG, "getPhotoFromEmail - Email: " + email + ", id: "
                    + MainApplication.contacts.getJSONObject(email).getLong("id"));
            result = openPhoto(context, MainApplication.contacts.getJSONObject(email).getLong("id"));
        } catch (JSONException e) {
            Log.e(TAG, "getPhotoFromEmail - failed: " + email);
        }
    } else {
        Log.e(TAG, "getPhotoFromEmail - id queried: " + email);
        Cursor emailCursor = context.getContentResolver().query(
                ContactsContract.CommonDataKinds.Email.CONTENT_URI, null,
                ContactsContract.CommonDataKinds.Email.DATA + "='" + email + "'", null, null);
        while (emailCursor != null && emailCursor.moveToNext()) {
            Long contactId = Long.valueOf(emailCursor
                    .getString(emailCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.CONTACT_ID)));
            result = openPhoto(context, contactId);
        }
        if (emailCursor != null) {
            emailCursor.close();
        }
    }

    if (result == null) {
        String name = getNameFromEmail(context, email);
        result = Utils.getDefaultAvatarInitials(context, name);
    }

    MainApplication.avatarCache.put(email, result);
    return result;
}

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

public static int getCount(String resourcePath) {
    final String[] projection = new String[] { Nodes._ID };
    final String[] selectionArgs = new String[] { resourcePath };
    final Cursor c = sResolver.query(Nodes.CONTENT_URI, projection, sSelection, selectionArgs, null);
    int count = 0;
    try {/*  w  w  w. j av a 2 s. com*/
        count = c.getCount();
    } finally {
        c.close();
    }
    return count;
}

From source file:ro.weednet.contactssync.platform.ContactManager.java

public static int getStreamItemLimit(Context context) {
    Cursor c = context.getContentResolver().query(StreamItems.CONTENT_LIMIT_URI,
            new String[] { StreamItems.MAX_ITEMS }, null, null, null);

    try {//from w  w  w.  ja  v  a 2 s. c  om
        c.moveToFirst();
        return c.getInt(0);
    } catch (Exception e) {
    } finally {
        if (c != null) {
            c.close();
        }
    }

    return 1;
}