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:com.xorcode.andtweet.TweetListActivity.java

@Override
public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, view, menuInfo);

    // Get the adapter context menu information
    AdapterView.AdapterContextMenuInfo info;
    try {/* w w  w.  ja  v  a2  s.  c  om*/
        info = (AdapterView.AdapterContextMenuInfo) menuInfo;
    } catch (ClassCastException e) {
        Log.e(TAG, "bad menuInfo", e);
        return;
    }

    int m = 0;

    // Add menu items
    menu.add(0, CONTEXT_MENU_ITEM_REPLY, m++, R.string.menu_item_reply);
    menu.add(0, CONTEXT_MENU_ITEM_RETWEET, m++, R.string.menu_item_retweet);
    menu.add(0, CONTEXT_MENU_ITEM_SHARE, m++, R.string.menu_item_share);
    // menu.add(0, CONTEXT_MENU_ITEM_DIRECT_MESSAGE, m++,
    // R.string.menu_item_direct_message);
    // menu.add(0, CONTEXT_MENU_ITEM_UNFOLLOW, m++,
    // R.string.menu_item_unfollow);
    // menu.add(0, CONTEXT_MENU_ITEM_BLOCK, m++, R.string.menu_item_block);
    // menu.add(0, CONTEXT_MENU_ITEM_PROFILE, m++,
    // R.string.menu_item_view_profile);

    // Get the record for the currently selected item
    Uri uri = ContentUris.withAppendedId(Tweets.CONTENT_URI, info.id);
    Cursor c = getContentResolver().query(uri,
            new String[] { Tweets._ID, Tweets.MESSAGE, Tweets.AUTHOR_ID, Tweets.FAVORITED }, null, null, null);
    try {
        c.moveToFirst();
        menu.setHeaderTitle(c.getString(c.getColumnIndex(Tweets.MESSAGE)));
        if (c.getInt(c.getColumnIndex(Tweets.FAVORITED)) == 1) {
            menu.add(0, CONTEXT_MENU_ITEM_DESTROY_FAVORITE, m++, R.string.menu_item_destroy_favorite);
        } else {
            menu.add(0, CONTEXT_MENU_ITEM_FAVORITE, m++, R.string.menu_item_favorite);
        }
        if (MyPreferences.getDefaultSharedPreferences().getString(MyPreferences.KEY_TWITTER_USERNAME, null)
                .equals(c.getString(c.getColumnIndex(Tweets.AUTHOR_ID)))) {
            menu.add(0, CONTEXT_MENU_ITEM_DESTROY_STATUS, m++, R.string.menu_item_destroy_status);
        }
    } catch (Exception e) {
        Log.e(TAG, "onCreateContextMenu: " + e.toString());
    } finally {
        if (c != null && !c.isClosed())
            c.close();
    }
}

From source file:org.opendatakit.tables.utils.CollectUtil.java

/**
 * Returns true if the instance has been marked as complete/finalized. If the
 * instance cannot be found or is not marked as complete, returns false.
 *
 * @param context//w  w w  . j a v  a2 s  .c o m
 * @param instanceId
 * @return
 */
private static boolean instanceIsFinalized(Context context, int instanceId) {
    String[] projection = { COLLECT_KEY_STATUS };
    String selection = "_id = ?";
    String[] selectionArgs = { instanceId + "" };
    Cursor c = null;
    try {
        c = context.getContentResolver().query(COLLECT_INSTANCES_CONTENT_URI, projection, selection,
                selectionArgs, COLLECT_INSTANCE_ORDER_BY);

        if (c.getCount() == 0) {
            return false;
        }
        c.moveToFirst();
        String status = ODKDatabaseUtils.get().getIndexAsString(c, c.getColumnIndexOrThrow(COLLECT_KEY_STATUS));
        // potential status values are incomplete, complete, submitted,
        // submission_failed
        // all but the incomplete status indicate a marked-as-complete record.
        if (status != null && !status.equals(COLLECT_KEY_STATUS_INCOMPLETE)) {
            return true;
        } else {
            return false;
        }
    } finally {
        if (c != null && !c.isClosed()) {
            c.close();
        }
    }
}

From source file:com.hichinaschool.flashcards.libanki.Collection.java

/**
 * Field checksums and sorting fields ***************************************
 * ********************************************************
 *///from  w w w .  j a  va 2s  .  c  o m

private ArrayList<Object[]> _fieldData(String snids) {
    ArrayList<Object[]> result = new ArrayList<Object[]>();
    Cursor cur = null;
    try {
        cur = mDb.getDatabase().rawQuery("SELECT id, mid, flds FROM notes WHERE id IN " + snids, null);
        while (cur.moveToNext()) {
            result.add(new Object[] { cur.getLong(0), cur.getLong(1), cur.getString(2) });
        }
    } finally {
        if (cur != null && !cur.isClosed()) {
            cur.close();
        }
    }
    return result;
}

From source file:com.aware.Aware.java

/**
 * Stops a plugin. Expects the package name of the plugin.
 * @param context//from w w  w.  ja v  a2 s  . c  o m
 * @param package_name
 */
public static void stopPlugin(Context context, String package_name) {
    Cursor is_installed = context.getContentResolver().query(Aware_Plugins.CONTENT_URI, null,
            Aware_Plugins.PLUGIN_PACKAGE_NAME + " LIKE '" + package_name + "'", null, null);
    if (is_installed != null && is_installed.moveToFirst()) {
        //it's installed, stop it!
        Intent plugin = new Intent();
        plugin.setClassName(package_name, package_name + ".Plugin");
        context.stopService(plugin);
        if (Aware.DEBUG)
            Log.d(TAG, package_name + " stopped...");

        ContentValues rowData = new ContentValues();
        rowData.put(Aware_Plugins.PLUGIN_STATUS, Aware_Plugin.STATUS_PLUGIN_OFF);
        context.getContentResolver().update(Aware_Plugins.CONTENT_URI, rowData,
                Aware_Plugins.PLUGIN_PACKAGE_NAME + " LIKE '" + package_name + "'", null);
    }
    if (is_installed != null && !is_installed.isClosed())
        is_installed.close();
}

From source file:org.rapidandroid.activity.chart.ChartBroker.java

protected JSONGraphData getDateQuery(DateDisplayTypes displayType, Cursor cr, SQLiteDatabase db) {
    // TODO Auto-generated method stub
    int barCount = cr.getCount();

    if (barCount == 0) {
        db.close();//from w w  w .ja  va 2  s . c om
        cr.close();
    } else {
        Date[] xVals = new Date[barCount];
        int[] yVals = new int[barCount];
        cr.moveToFirst();
        int i = 0;
        do {
            xVals[i] = getDate(displayType, cr.getString(0));
            yVals[i] = cr.getInt(1);
            i++;
        } while (cr.moveToNext());

        try {
            // result.put("label", fieldToPlot.getName());
            // result.put("data", prepareData(xVals, yVals));
            // result.put("bars", getShowTrue());
            // result.put("xaxis", getXaxisOptions(xVals));
            // todo
            String legend = this.getLegendString(displayType);
            return new JSONGraphData(prepareDateHistogramData(displayType, xVals, yVals, legend),
                    loadOptionsForDateGraph(xVals, true, displayType));

        } catch (Exception ex) {

        } finally {
            if (!cr.isClosed()) {

                cr.close();
            }
            if (db.isOpen()) {
                db.close();
            }
        }
    }
    // either there was no data or something bad happened
    return new JSONGraphData(getEmptyData(), new JSONObject());
}

From source file:org.opendatakit.tables.utils.CollectUtil.java

/**
 * Return the URI of the form for adding a row to a table. If the formId is
 * custom defined it must exist to Collect (most likely by putting the form in
 * Collect's form folder and starting Collect once). If the form does not
 * exist, it inserts the static addRowForm information into Collect.
 * <p>//  w ww.  j  a  v  a2  s .com
 * Display name only matters if it is a programmatically generated form.
 * <p>
 * Precondition: If formId refers to a custom form, it must have already been
 * scanned in and known to exist to Collect. If the formId is not custom, but
 * refers to a form built on the fly, it should be the id of
 * {@link COLLECT_ADDROW_FORM_ID}, and the form should already have been
 * written.
 *
 * @param resolver
 *          ContentResolver of the calling activity
 * @param appName
 *          application name.
 * @param formId
 *          id of the form whose uri will be returned
 * @param formDisplayName
 *          display name of the table. Only pertinent if the form has been
 *          programmatically generated.
 * @return the uri of the form.
 */
private static Uri getUriOfForm(ContentResolver resolver, String appName, String formId) {
    Uri resultUri = null;
    Cursor c = null;
    try {
        c = resolver.query(CollectUtil.CONTENT_FORM_URI, null, CollectUtil.COLLECT_KEY_JR_FORM_ID + "=?",
                new String[] { formId }, null);
        if (!c.moveToFirst()) {
            WebLogger.getLogger(appName).e(TAG, "query of Collect for form returned no results");
        } else {
            // we got a result, meaning that the form exists in collect.
            // so we just need to set the URI.
            int collectFormKey; // this is the primary key of the form in
            // Collect's
            // database.
            collectFormKey = ODKDatabaseUtils.get().getIndexAsType(c, Integer.class,
                    c.getColumnIndexOrThrow(BaseColumns._ID));
            resultUri = (Uri.parse(CollectUtil.CONTENT_FORM_URI + "/" + collectFormKey));
        }
    } finally {
        if (c != null && !c.isClosed()) {
            c.close();
        }
    }
    return resultUri;
}

From source file:com.money.manager.ex.MmxContentProvider.java

private Cursor query_internal(Uri uri, String[] projection, String selection, String[] selectionArgs,
        String sortOrder) {/* w w  w. j  a  va  2s  . c o m*/
    Timber.d("Querying URI: %s", uri);

    // find object from uri
    Object sourceObject = getObjectFromUri(uri);

    initializeDependencies();

    SQLiteDatabase database = openHelper.get().getReadableDatabase();
    if (database == null) {
        Timber.e("Database could not be opened");
        return null;
    }

    Cursor cursor;

    // check type of instance data set
    if (Dataset.class.isInstance(sourceObject)) {
        Dataset dataset = ((Dataset) sourceObject);

        //            logQuery(dataset, projection, selection, selectionArgs, sortOrder);

        switch (dataset.getType()) {
        case QUERY:
            String query = prepareQuery(dataset.getSource(), projection, selection, sortOrder);
            cursor = database.rawQuery(query, selectionArgs);
            break;
        case SQL:
            cursor = database.rawQuery(selection, selectionArgs);
            break;
        case TABLE:
        case VIEW:
            SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
            queryBuilder.setTables(dataset.getSource());
            cursor = queryBuilder.query(database, projection, selection, selectionArgs, null, null, sortOrder);
            break;
        default:
            throw new IllegalArgumentException("Type of dataset not defined");
        }
    } else {
        throw new IllegalArgumentException("Object sourceObject of mapContent is not instance of dataset");
    }

    // notify listeners waiting for the data is ready
    cursor.setNotificationUri(getContext().getContentResolver(), uri);

    if (!cursor.isClosed()) {
        Timber.d("Rows returned: %d", cursor.getCount());
    }

    return cursor;
}

From source file:com.ichi2.libanki.Stats.java

/**
 * Cards Types//w  ww . j a va 2 s . c  o m
 */
public boolean calculateCardsTypes(int type) {
    mTitle = R.string.stats_cards_types;
    mIsPieChart = true;
    mAxisTitles = new int[] { R.string.stats_answer_type, R.string.stats_answers,
            R.string.stats_cumulative_correct_percentage };

    mValueLabels = new int[] { R.string.statistics_mature, R.string.statistics_young_and_learn,
            R.string.statistics_unlearned, R.string.statistics_suspended };
    mColors = new int[] { R.color.stats_mature, R.color.stats_young, R.color.stats_unseen,
            R.color.stats_suspended };

    mType = type;

    ArrayList<double[]> list = new ArrayList<double[]>();
    double[] pieData;
    Cursor cur = null;
    String query = "select " + "sum(case when queue=2 and ivl >= 21 then 1 else 0 end), -- mtr\n"
            + "sum(case when queue in (1,3) or (queue=2 and ivl < 21) then 1 else 0 end), -- yng/lrn\n"
            + "sum(case when queue=0 then 1 else 0 end), -- new\n"
            + "sum(case when queue<0 then 1 else 0 end) -- susp\n" + "from cards where did in " + _limit();
    Timber.d("CardsTypes query: %s", query);

    try {
        cur = mCol.getDb().getDatabase().rawQuery(query, null);

        cur.moveToFirst();
        pieData = new double[] { cur.getDouble(0), cur.getDouble(1), cur.getDouble(2), cur.getDouble(3) };

    } finally {
        if (cur != null && !cur.isClosed()) {
            cur.close();
        }
    }

    //TODO adjust for CardsTypes, for now only copied from intervals
    // small adjustment for a proper chartbuilding with achartengine
    //        if (list.size() == 0 || list.get(0)[0] > 0) {
    //            list.add(0, new double[] { 0, 0, 0 });
    //        }
    //        if (num == -1 && list.size() < 2) {
    //            num = 31;
    //        }
    //        if (type != Utils.TYPE_LIFE && list.get(list.size() - 1)[0] < num) {
    //            list.add(new double[] { num, 0, 0 });
    //        } else if (type == Utils.TYPE_LIFE && list.size() < 2) {
    //            list.add(new double[] { Math.max(12, list.get(list.size() - 1)[0] + 1), 0, 0 });
    //        }

    mSeriesList = new double[1][4];
    mSeriesList[0] = pieData;

    mFirstElement = 0.5;
    mLastElement = 9.5;
    mMcount = 100;
    mMaxElements = 10; //bars are positioned from 1 to 14
    if (mMaxCards == 0)
        mMaxCards = 10;
    return list.size() > 0;
}

From source file:com.ichi2.libanki.Stats.java

/**
 * Due and cumulative due/*  w w  w .  j a  va2s .c  o  m*/
 * ***********************************************************************************************
 */
public boolean calculateDue(int type) {
    mHasColoredCumulative = false;
    mType = type;
    mDynamicAxis = true;
    mBackwards = false;
    mTitle = R.string.stats_forecast;
    mValueLabels = new int[] { R.string.statistics_young, R.string.statistics_mature };
    mColors = new int[] { R.color.stats_young, R.color.stats_mature };
    mAxisTitles = new int[] { type, R.string.stats_cards, R.string.stats_cumulative_cards };
    int end = 0;
    int chunk = 0;
    switch (type) {
    case TYPE_MONTH:
        end = 31;
        chunk = 1;
        break;
    case TYPE_YEAR:
        end = 52;
        chunk = 7;
        break;
    case TYPE_LIFE:
        end = -1;
        chunk = 30;
        break;
    }

    String lim = "";// AND due - " + mCol.getSched().getToday() + " >= " + start; // leave this out in order to show
    // card too which were due the days before
    if (end != -1) {
        lim += " AND day <= " + end;
    }

    ArrayList<int[]> dues = new ArrayList<int[]>();
    Cursor cur = null;
    try {
        String query;
        query = "SELECT (due - " + mCol.getSched().getToday() + ")/" + chunk + " AS day, " // day
                + "count(), " // all cards
                + "sum(CASE WHEN ivl >= 21 THEN 1 ELSE 0 END) " // mature cards
                + "FROM cards WHERE did IN " + _limit() + " AND queue IN (2,3)" + lim
                + " GROUP BY day ORDER BY day";
        Timber.d("Forecast query: %s", query);
        cur = mCol.getDb().getDatabase().rawQuery(query, null);
        while (cur.moveToNext()) {
            dues.add(new int[] { cur.getInt(0), cur.getInt(1), cur.getInt(2) });
        }
    } finally {
        if (cur != null && !cur.isClosed()) {
            cur.close();
        }
    }
    // small adjustment for a proper chartbuilding with achartengine
    if (dues.size() == 0 || dues.get(0)[0] > 0) {
        dues.add(0, new int[] { 0, 0, 0 });
    }
    if (end == -1 && dues.size() < 2) {
        end = 31;
    }
    if (type != TYPE_LIFE && dues.get(dues.size() - 1)[0] < end) {
        dues.add(new int[] { end, 0, 0 });
    } else if (type == TYPE_LIFE && dues.size() < 2) {
        dues.add(new int[] { Math.max(12, dues.get(dues.size() - 1)[0] + 1), 0, 0 });
    }

    mSeriesList = new double[3][dues.size()];
    for (int i = 0; i < dues.size(); i++) {
        int[] data = dues.get(i);

        if (data[1] > mMaxCards)
            mMaxCards = data[1];

        mSeriesList[0][i] = data[0];
        mSeriesList[1][i] = data[1];
        mSeriesList[2][i] = data[2];
        if (data[0] > mLastElement)
            mLastElement = data[0];
        if (data[0] == 0) {
            mZeroIndex = i;
        }
    }
    mMaxElements = dues.size() - 1;
    switch (mType) {
    case TYPE_MONTH:
        mLastElement = 31;
        break;
    case TYPE_YEAR:
        mLastElement = 52;
        break;
    default:
    }
    mFirstElement = 0;

    mHasColoredCumulative = false;
    mCumulative = Stats.createCumulative(new double[][] { mSeriesList[0], mSeriesList[1] }, mZeroIndex);
    mMcount = mCumulative[1][mCumulative[1].length - 1];
    //some adjustments to not crash the chartbuilding with emtpy data
    if (mMaxElements == 0) {
        mMaxElements = 10;
    }
    if (mMcount == 0) {
        mMcount = 10;
    }
    if (mFirstElement == mLastElement) {
        mFirstElement = 0;
        mLastElement = 6;
    }
    if (mMaxCards == 0)
        mMaxCards = 10;
    return dues.size() > 0;
}

From source file:com.ichi2.libanki.Stats.java

/**
 * Answer Buttons/*from  w  w  w.j a  v  a 2 s  . c om*/
 */

public boolean calculateAnswerButtons(int type) {
    mHasColoredCumulative = true;
    mTitle = R.string.stats_answer_buttons;
    mAxisTitles = new int[] { R.string.stats_answer_type, R.string.stats_answers,
            R.string.stats_cumulative_correct_percentage };

    mValueLabels = new int[] { R.string.statistics_learn, R.string.statistics_young,
            R.string.statistics_mature };
    mColors = new int[] { R.color.stats_learn, R.color.stats_young, R.color.stats_mature };

    mType = type;
    String lim = _revlogLimit().replaceAll("[\\[\\]]", "");

    Vector<String> lims = new Vector<String>();
    int days = 0;

    if (lim.length() > 0)
        lims.add(lim);

    if (type == TYPE_MONTH)
        days = 30;
    else if (type == TYPE_YEAR)
        days = 365;
    else
        days = -1;

    if (days > 0)
        lims.add("id > " + ((mCol.getSched().getDayCutoff() - (days * 86400)) * 1000));
    if (lims.size() > 0) {
        lim = "where " + lims.get(0);
        for (int i = 1; i < lims.size(); i++)
            lim += " and " + lims.get(i);
    } else
        lim = "";

    ArrayList<double[]> list = new ArrayList<double[]>();
    Cursor cur = null;
    String query = "select (case " + "                when type in (0,2) then 0 "
            + "        when lastIvl < 21 then 1 " + "        else 2 end) as thetype, "
            + "        (case when type in (0,2) and ease = 4 then 3 else ease end), count() from revlog " + lim
            + " " + "        group by thetype, ease " + "        order by thetype, ease";
    Timber.d("AnswerButtons query: %s", query);

    try {
        cur = mCol.getDb().getDatabase().rawQuery(query, null);
        while (cur.moveToNext()) {
            list.add(new double[] { cur.getDouble(0), cur.getDouble(1), cur.getDouble(2) });
        }

    } finally {
        if (cur != null && !cur.isClosed()) {
            cur.close();
        }
    }

    //TODO adjust for AnswerButton, for now only copied from intervals
    // small adjustment for a proper chartbuilding with achartengine
    if (list.size() == 0) {
        list.add(0, new double[] { 0, 1, 0 });
    }

    double[] totals = new double[3];
    for (int i = 0; i < list.size(); i++) {
        double[] data = list.get(i);
        int currentType = (int) data[0];
        double ease = data[1];
        double cnt = data[2];

        totals[currentType] += cnt;
    }
    int badNew = 0;
    int badYoung = 0;
    int badMature = 0;

    mSeriesList = new double[4][list.size() + 1];

    for (int i = 0; i < list.size(); i++) {
        double[] data = list.get(i);
        int currentType = (int) data[0];
        double ease = data[1];
        double cnt = data[2];

        if (currentType == 1)
            ease += 5;
        else if (currentType == 2)
            ease += 10;

        if ((int) ease == 1) {
            badNew = i;
        }

        if ((int) ease == 6) {
            badYoung = i;
        }
        if ((int) ease == 11) {
            badMature = i;
        }
        mSeriesList[0][i] = ease;
        mSeriesList[1 + currentType][i] = cnt;
        if (cnt > mMaxCards)
            mMaxCards = (int) cnt;
    }
    mSeriesList[0][list.size()] = 15;

    mCumulative = new double[4][];
    mCumulative[0] = mSeriesList[0];
    mCumulative[1] = createCumulativeInPercent(mSeriesList[1], totals[0], badNew);
    mCumulative[2] = createCumulativeInPercent(mSeriesList[2], totals[1], badYoung);
    mCumulative[3] = createCumulativeInPercent(mSeriesList[3], totals[2], badMature);

    mFirstElement = 0.5;
    mLastElement = 14.5;
    mMcount = 100;
    mMaxElements = 15; //bars are positioned from 1 to 14
    if (mMaxCards == 0)
        mMaxCards = 10;

    return list.size() > 0;
}