Example usage for android.database Cursor isClosed

List of usage examples for android.database Cursor isClosed

Introduction

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

Prototype

boolean isClosed();

Source Link

Document

return true if the cursor is closed

Usage

From source file:org.ttrssreader.controllers.DBHelper.java

/**
 * get the DB object representing remote file by its URL
 *
 * @param url remote file URL//from   w w w. j a v  a 2  s .  co m
 * @return remote file object from DB
 */
private RemoteFile getRemoteFile(String url) {
    if (!isDBAvailable())
        return null;

    RemoteFile rf = null;
    SQLiteDatabase db = getOpenHelper().getReadableDatabase();
    readLock(true);
    Cursor c = null;
    try {
        c = db.query(TABLE_REMOTEFILES, null, "url=?", new String[] { url }, null, null, null, null);
        if (c.moveToFirst())
            rf = handleRemoteFileCursor(c);

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (c != null && !c.isClosed())
            c.close();
        readLock(false);
    }
    return rf;
}

From source file:org.ttrssreader.controllers.DBHelper.java

public int getUnreadCount(int id, boolean isCat) {
    if (!isDBAvailable())
        return 0;

    StringBuilder selection = new StringBuilder("isUnread>0");
    String[] selectionArgs = new String[] { String.valueOf(id) };

    if (isCat && id >= 0) {
        // real categories
        selection.append(" and feedId in (select _id from feeds where categoryId=?)");
    } else {// w w w  .  ja  v  a 2 s  .co m
        if (id < 0) {
            // virtual categories
            switch (id) {
            // All Articles
            case Data.VCAT_ALL:
                selectionArgs = null;
                break;

            // Fresh Articles
            case Data.VCAT_FRESH:
                selection.append(" and updateDate>?");
                selectionArgs = new String[] { String
                        .valueOf(new Date().getTime() - Controller.getInstance().getFreshArticleMaxAge()) };
                break;

            // Published Articles
            case Data.VCAT_PUB:
                selection.append(" and isPublished>0");
                selectionArgs = null;
                break;

            // Starred Articles
            case Data.VCAT_STAR:
                selection.append(" and isStarred>0");
                selectionArgs = null;
                break;

            default:
                // Probably a label...
                selection.append(" and feedId=?");
            }
        } else {
            // feeds
            selection.append(" and feedId=?");
        }
    }

    // Read count for given feed
    int ret = 0;
    SQLiteDatabase db = getOpenHelper().getReadableDatabase();
    readLock(true);
    Cursor c = null;
    try {
        c = db.query(TABLE_ARTICLES, new String[] { "count(*)" }, selection.toString(), selectionArgs, null,
                null, null, null);

        if (c.moveToFirst())
            ret = c.getInt(0);
    } finally {
        if (c != null && !c.isClosed())
            c.close();
        readLock(false);
    }

    return ret;
}

From source file:org.ttrssreader.controllers.DBHelper.java

public Set<Category> getAllCategories() {
    if (!isDBAvailable())
        return new LinkedHashSet<>();

    SQLiteDatabase db = getOpenHelper().getReadableDatabase();
    readLock(true);//  w w  w.j  a v  a2s . co m
    Cursor c = null;
    try {
        c = db.query(TABLE_CATEGORIES, null, "_id>=0", null, null, null, "title ASC");
        Set<Category> ret = new LinkedHashSet<>(c.getCount());
        while (c.moveToNext()) {
            ret.add(handleCategoryCursor(c));
        }
        return ret;
    } finally {
        if (c != null && !c.isClosed())
            c.close();
        readLock(false);
    }
}

From source file:de.ub0r.android.smsdroid.SmsReceiver.java

/**
 * Update failed message notification./*  w w  w  . j  a  v a2  s .c  o m*/
 *
 * @param context {@link Context}
 * @param uri     {@link Uri} to message
 */
private static void updateFailedNotification(final Context context, final Uri uri) {
    Log.d(TAG, "updateFailedNotification: ", uri);
    final Cursor c = context.getContentResolver().query(uri, Message.PROJECTION_SMS, null, null, null);
    if (c != null && c.moveToFirst()) {
        final int id = c.getInt(Message.INDEX_ID);
        final int tid = c.getInt(Message.INDEX_THREADID);
        final String body = c.getString(Message.INDEX_BODY);
        final long date = c.getLong(Message.INDEX_DATE);

        Conversation conv = Conversation.getConversation(context, tid, true);

        final NotificationManager mNotificationMgr = (NotificationManager) context
                .getSystemService(Context.NOTIFICATION_SERVICE);
        final SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(context);
        final boolean privateNotification = p.getBoolean(PreferencesActivity.PREFS_NOTIFICATION_PRIVACY, false);
        Intent intent;
        if (conv == null) {
            intent = new Intent(Intent.ACTION_VIEW, null, context, SenderActivity.class);
        } else {
            intent = new Intent(Intent.ACTION_VIEW, conv.getUri(), context, MessageListActivity.class);
        }
        intent.putExtra(Intent.EXTRA_TEXT, body);

        String title = context.getString(R.string.error_sending_failed);

        final int[] ledFlash = PreferencesActivity.getLEDflash(context);
        final NotificationCompat.Builder b = new NotificationCompat.Builder(context)
                .setSmallIcon(android.R.drawable.stat_sys_warning).setTicker(title).setWhen(date)
                .setAutoCancel(true).setLights(RED, ledFlash[0], ledFlash[1]).setContentIntent(
                        PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT));
        String text;
        if (privateNotification) {
            title += "!";
            text = "";
        } else if (conv == null) {
            title += "!";
            text = body;
        } else {
            title += ": " + conv.getContact().getDisplayName();
            text = body;
        }
        b.setContentTitle(title);
        b.setContentText(text);
        final String s = p.getString(PreferencesActivity.PREFS_SOUND, null);
        if (!TextUtils.isEmpty(s)) {
            b.setSound(Uri.parse(s));
        }
        final boolean vibrate = p.getBoolean(PreferencesActivity.PREFS_VIBRATE, false);
        if (vibrate) {
            final long[] pattern = PreferencesActivity.getVibratorPattern(context);
            if (pattern.length > 1) {
                b.setVibrate(pattern);
            }
        }

        mNotificationMgr.notify(id, b.build());
    }
    if (c != null && !c.isClosed()) {
        c.close();
    }
}

From source file:org.ttrssreader.controllers.DBHelper.java

/**
 * 0 - Uncategorized//from ww w.java 2 s .  c o  m
 * -1 - Special (e.g. Starred, Published, Archived, etc.) <- these are categories here o.O
 * -2 - Labels
 * -3 - All feeds, excluding virtual feeds (e.g. Labels and such)
 * -4 - All feeds, including virtual feeds
 */
public Set<Feed> getFeeds(int categoryId) {
    if (!isDBAvailable())
        return new LinkedHashSet<>();

    String where = null; // categoryId = 0
    if (categoryId >= 0)
        where = "categoryId=" + categoryId;
    switch (categoryId) {
    case -1:
        where = "_id IN (0, -2, -3)";
        break;
    case -2:
        where = "_id < -10";
        break;
    case -3:
        where = "categoryId >= 0";
        break;
    case -4:
        where = null;
        break;
    }

    SQLiteDatabase db = getOpenHelper().getReadableDatabase();
    readLock(true);
    Cursor c = null;
    try {
        c = db.query(TABLE_FEEDS, null, where, null, null, null, "UPPER(title) ASC");
        Set<Feed> ret = new LinkedHashSet<>(c.getCount());
        while (c.moveToNext()) {
            ret.add(handleFeedCursor(c));
        }
        return ret;
    } finally {
        if (c != null && !c.isClosed())
            c.close();
        readLock(false);
    }
}

From source file:com.ezac.gliderlogs.FlightOverviewActivity.java

public int getTableMemberCnt(boolean Notify) {
    int res = 0;/*  www  .jav a 2 s  .c o  m*/
    Uri uri = FlightsContentProvider.CONTENT_URI_MEMBER;
    String[] projection = { GliderLogTables.M_ID };
    Cursor cur_mc = getContentResolver().query(uri, projection, null, null, null);
    if (cur_mc != null) {
        try {
            res = cur_mc.getCount();
        } finally {
            if (!cur_mc.isClosed()) {
                cur_mc.close();
            }
        }
    }
    if ((Notify) && (res == 0)) {
        makeToast("Leden tabel is nog niet geladen", 1);
    }
    return res;
}

From source file:com.ezac.gliderlogs.FlightOverviewActivity.java

public int getTableGliderCnt(boolean Notify) {
    int res = 0;/*from   ww  w .j a va2 s.co  m*/
    Uri uri = FlightsContentProvider.CONTENT_URI_GLIDER;
    String[] projection = { GliderLogTables.G_REGISTRATION };
    Cursor cur_gc = getContentResolver().query(uri, projection, null, null, null);
    if (cur_gc != null) {
        try {
            res = cur_gc.getCount();
        } finally {
            if (!cur_gc.isClosed()) {
                cur_gc.close();
            }
        }
    }

    if ((Notify) && (res == 0)) {
        makeToast("Kisten tabel is nog niet geladen", 1);
    }
    return res;
}

From source file:org.ttrssreader.controllers.DBHelper.java

@SuppressLint("UseSparseArrays")
Map<Integer, String> getMarked(String mark, int status) {
    if (!isDBAvailable())
        return new HashMap<>();

    SQLiteDatabase db = getOpenHelper().getReadableDatabase();
    readLock(true);//  w w w .  jav  a 2 s. com
    Cursor c = null;
    try {
        c = db.query(TABLE_MARK, new String[] { "id", MARK_NOTE }, mark + "=" + status, null, null, null, null,
                null);

        Map<Integer, String> ret = new HashMap<>(c.getCount());
        while (c.moveToNext()) {
            ret.put(c.getInt(0), c.getString(1));
        }
        return ret;

    } finally {
        if (c != null && !c.isClosed())
            c.close();
        readLock(false);
    }
}

From source file:org.ttrssreader.controllers.DBHelper.java

/**
 * get remote files which should be deleted to free given amount of space
 *
 * @param spaceToBeFreed amount of space (summary file size) to be freed
 * @return collection of remote files, which can be deleted
 * to free given amount of space/*from w  ww .  j  a  va2  s.  c  o  m*/
 */
public Collection<RemoteFile> getUncacheFiles(long spaceToBeFreed) {
    if (!isDBAvailable())
        return null;

    ArrayList<RemoteFile> rfs = new ArrayList<>();
    SQLiteDatabase db = getOpenHelper().getReadableDatabase();
    readLock(true);
    Cursor c = null;
    try {
        c = db.query("remotefile_sequence", null, "cached = 1", null, null, null, "ord");

        long spaceToFree = spaceToBeFreed;
        while (spaceToFree > 0 && c.moveToNext()) {
            RemoteFile rf = handleRemoteFileCursor(c);
            spaceToFree -= rf.length;
            rfs.add(rf);
        }
    } finally {
        if (c != null && !c.isClosed())
            c.close();
        readLock(false);
    }
    return rfs;
}

From source file:org.opendatakit.common.android.provider.impl.FormsProviderImpl.java

/**
 * This method removes the entry from the content provider, and also removes
 * any associated files. files: form.xml, [formmd5].formdef, formname
 * {directory}/*from  w  w  w  .  j  a  v a2 s.  c  o  m*/
 */
@Override
public int delete(Uri uri, String where, String[] whereArgs) {
    List<String> segments = uri.getPathSegments();

    if (segments.size() < 1 || segments.size() > 2) {
        throw new IllegalArgumentException("Unknown URI (incorrect number of segments!) " + uri);
    }

    String appName = segments.get(0);
    ODKFileUtils.verifyExternalStorageAvailability();
    ODKFileUtils.assertDirectoryStructure(appName);
    WebLogger log = WebLogger.getLogger(appName);

    String uriFormId = ((segments.size() == 2) ? segments.get(1) : null);
    boolean isNumericId = StringUtils.isNumeric(uriFormId);

    // Modify the where clause to account for the presence of
    // a form id. Accept either:
    // (1) numeric _ID value
    // (2) string FORM_ID value.
    String whereId;
    String[] whereIdArgs;

    if (uriFormId == null) {
        whereId = where;
        whereIdArgs = whereArgs;
    } else {
        if (TextUtils.isEmpty(where)) {
            whereId = (isNumericId ? FormsColumns._ID : FormsColumns.FORM_ID) + "=?";
            whereIdArgs = new String[1];
            whereIdArgs[0] = uriFormId;
        } else {
            whereId = (isNumericId ? FormsColumns._ID : FormsColumns.FORM_ID) + "=? AND (" + where + ")";
            whereIdArgs = new String[whereArgs.length + 1];
            whereIdArgs[0] = uriFormId;
            for (int i = 0; i < whereArgs.length; ++i) {
                whereIdArgs[i + 1] = whereArgs[i];
            }
        }
    }

    Cursor del = null;
    Integer idValue = null;
    String tableIdValue = null;
    String formIdValue = null;
    HashMap<File, DirType> mediaDirs = new HashMap<File, DirType>();
    try {
        del = this.query(uri, null, whereId, whereIdArgs, null);
        if (del == null) {
            throw new SQLException("FAILED Delete into " + uri + " -- unable to query for existing records");
        }
        del.moveToPosition(-1);
        while (del.moveToNext()) {
            idValue = ODKDatabaseUtils.get().getIndexAsType(del, Integer.class,
                    del.getColumnIndex(FormsColumns._ID));
            tableIdValue = ODKDatabaseUtils.get().getIndexAsString(del,
                    del.getColumnIndex(FormsColumns.TABLE_ID));
            formIdValue = ODKDatabaseUtils.get().getIndexAsString(del,
                    del.getColumnIndex(FormsColumns.FORM_ID));
            File mediaDir = ODKFileUtils.asAppFile(appName, ODKDatabaseUtils.get().getIndexAsString(del,
                    del.getColumnIndex(FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH)));
            mediaDirs.put(mediaDir, (tableIdValue == null) ? DirType.FRAMEWORK : DirType.FORMS);
        }
    } catch (Exception e) {
        log.w(t, "FAILED Delete from " + uri + " -- query for existing row failed: " + e.toString());

        if (e instanceof SQLException) {
            throw (SQLException) e;
        } else {
            throw new SQLException(
                    "FAILED Delete from " + uri + " -- query for existing row failed: " + e.toString());
        }
    } finally {
        if (del != null && !del.isClosed()) {
            del.close();
        }
    }

    SQLiteDatabase db = null;
    int count;
    try {
        db = DatabaseFactory.get().getDatabase(getContext(), appName);
        db.beginTransaction();
        count = db.delete(DatabaseConstants.FORMS_TABLE_NAME, whereId, whereIdArgs);
        db.setTransactionSuccessful();
    } catch (Exception e) {
        e.printStackTrace();
        log.w(t, "Unable to perform deletion " + e.toString());
        return 0;
    } finally {
        if (db != null) {
            db.endTransaction();
            db.close();
        }
    }

    // and attempt to move these directories to the stale forms location
    // so that they do not immediately get rescanned...

    for (HashMap.Entry<File, DirType> entry : mediaDirs.entrySet()) {
        try {
            moveDirectory(appName, entry.getValue(), entry.getKey());
        } catch (IOException e) {
            e.printStackTrace();
            log.e(t, "Unable to move directory " + e.toString());
        }
    }

    if (count == 1) {
        Uri formUri = Uri.withAppendedPath(
                Uri.withAppendedPath(Uri.parse("content://" + getFormsAuthority()), appName), formIdValue);
        getContext().getContentResolver().notifyChange(formUri, null);
        Uri idUri = Uri.withAppendedPath(
                Uri.withAppendedPath(Uri.parse("content://" + getFormsAuthority()), appName),
                Long.toString(idValue));
        getContext().getContentResolver().notifyChange(idUri, null);
    } else {
        getContext().getContentResolver().notifyChange(uri, null);
    }
    return count;
}