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:org.zoumbox.mh_dla_notifier.sp.PublicScriptsProxy.java

public static Date geLastUpdate(Context context, PublicScript script, String trollId) {

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

    Cursor cursor = database.rawQuery(SQL_LAST_UPDATE,
            new String[] { trollId, script.name(), MhDlaSQLHelper.STATUS_SUCCESS });
    Date result = null;/*from ww w  . j ava  2  s . c o m*/
    if (cursor.getCount() > 0) {
        cursor.moveToFirst();
        long resultTimestamp = cursor.getLong(0);
        result = new Date(resultTimestamp);
    }

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

    String format = "Last update for category %s (script=%s) and troll=%s is: '%s'";
    String message = String.format(format, script.category, script, trollId, result);
    Log.d(TAG, message);

    return result;
}

From source file:com.android.emailcommon.utility.AttachmentUtilities.java

/**
 * In support of deleting a mailbox, find all messages and delete their attachments.
 *
 * @param context//  w ww.  j  a  v  a  2 s . c o m
 * @param accountId the account for the mailbox
 * @param mailboxId the mailbox for the messages
 */
public static void deleteAllMailboxAttachmentFiles(Context context, long accountId, long mailboxId) {
    Cursor c = context.getContentResolver().query(Message.CONTENT_URI, Message.ID_COLUMN_PROJECTION,
            MessageColumns.MAILBOX_KEY + "=?", new String[] { Long.toString(mailboxId) }, null);
    try {
        while (c.moveToNext()) {
            long messageId = c.getLong(Message.ID_PROJECTION_COLUMN);
            deleteAllAttachmentFiles(context, accountId, messageId);
        }
    } finally {
        c.close();
    }
}

From source file:com.chess.genesis.data.GameDataDB.java

public static Bundle rowToBundle(final Cursor cursor, final int index, final boolean closeCursor) {
    final Bundle bundle = new Bundle();
    final String[] column = cursor.getColumnNames();

    cursor.moveToPosition(index);//from ww w.  j a v a2  s .c o  m
    for (int i = 0, len = cursor.getColumnCount(); i < len; i++)
        bundle.putString(column[i], cursor.getString(i));
    if (closeCursor)
        cursor.close();
    return bundle;
}

From source file:com.deliciousdroid.platform.ContactManager.java

/**
 * Returns the Data id for a sample SyncAdapter contact's profile row, or 0
 * if the sample SyncAdapter user isn't found.
 * //  w  ww. j  av  a 2 s  .  c o  m
 * @param resolver a content resolver
 * @param userId the sample SyncAdapter user ID to lookup
 * @return the profile Data row id, or 0 if not found
 */
private static long lookupProfile(ContentResolver resolver, String userName) {
    long profileId = 0;
    final Cursor c = resolver.query(Data.CONTENT_URI, ProfileQuery.PROJECTION, ProfileQuery.SELECTION,
            new String[] { userName }, null);
    try {
        if (c != null && c.moveToFirst()) {
            profileId = c.getLong(ProfileQuery.COLUMN_ID);
            Log.d("ProfileLookup", Long.toString(c.getLong(ProfileQuery.COLUMN_ID)));
        }
    } finally {
        if (c != null) {
            c.close();
        }
    }
    return profileId;
}

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;/*from ww  w  .  j  a va2  s  . c o  m*/
            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.hivewallet.androidclient.wallet.AddressBookProvider.java

public static AddressBookEntry lookupEntry(final Context context, @Nonnull final String address) {
    String label = null;//from  ww  w .j  a v  a  2 s .  c o  m
    String photo = null;

    final Uri uri = contentUri(context.getPackageName()).buildUpon().appendPath(address).build();
    final Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);

    if (cursor != null) {
        if (cursor.moveToFirst()) {
            label = cursor.getString(cursor.getColumnIndexOrThrow(KEY_LABEL));
            photo = cursor.getString(cursor.getColumnIndexOrThrow(KEY_PHOTO));
        }

        cursor.close();
    }

    if (label != null) {
        return new AddressBookEntry(address, label, photo);
    } else {
        return null;
    }
}

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.
 *///from  w ww  .  j ava  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:cc.softwarefactory.lokki.android.utilities.Utils.java

public static Bitmap openPhoto(Context context, long contactId) {

    Log.e(TAG, "openPhoto");
    if (context == null) {
        return null;
    }//www  . j ava  2  s . c  om

    Uri contactUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, contactId);
    Uri photoUri = Uri.withAppendedPath(contactUri, ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
    Cursor cursor = context.getContentResolver().query(photoUri,
            new String[] { ContactsContract.Contacts.Photo.PHOTO }, null, null, null);
    if (cursor == null) {
        return null;
    }

    try {
        if (cursor.moveToFirst()) {
            byte[] data = cursor.getBlob(0);
            if (data != null) {
                return BitmapFactory.decodeStream(new ByteArrayInputStream(data));
            }
        }
    } finally {
        cursor.close();
    }
    return null;
}

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

private static String getDeviceId(Context context) {
    String id = null;/*from  w  ww. ja v  a 2s  . 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:Main.java

public static Map<Integer, List> getCityByPid(int id, File file) {

    String sql = "select cityid,city  from city where provinceid= " + id;
    SQLiteDatabase db = null;//from  ww w.j  ava2 s.c o m
    Cursor c = null;
    Map<Integer, List> cityData = new HashMap<Integer, List>();
    //List cityList = null;
    try {
        db = SQLiteDatabase.openOrCreateDatabase(file, null);
        c = db.rawQuery(sql, null);
        List cityList1 = new ArrayList();
        List cityList2 = new ArrayList();
        while (c.moveToNext()) {
            Map cityMap = new HashMap();
            cityMap.put(c.getString(1), c.getInt(0));
            cityList1.add(cityMap);
            cityList2.add(c.getString(1));
        }
        cityData.put(0, cityList1);
        cityData.put(1, cityList2);

    } catch (Exception e) {
        Log.d("WineStock", "getCityByPid:" + e.getMessage());
    } finally {
        if (c != null) {
            c.close();
        }
        if (db != null) {
            db.close();
        }
    }
    return cityData;
}