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.argenes.android.sanicen.activities.MapActivity.java

private void addCenters() {
    Cursor cursor;

    HashMap<String, Integer> iconTypes = new HashMap<>();
    iconTypes.put(db.apCode, R.drawable.ap_marker);
    iconTypes.put(db.hoCode, R.drawable.ho_marker);
    iconTypes.put(db.auCode, R.drawable.au_marker);

    provinceCode = NavigationManager.getData(this, "provinceCode");
    provinceName = NavigationManager.getData(this, "provinceName");
    munCode = NavigationManager.getData(this, "munCode");
    munName = NavigationManager.getData(this, "munName");
    centerTypeName = NavigationManager.getData(this, "centerTypeName");
    centerTypeCode = NavigationManager.getData(this, "centerTypeCode");
    specialities = NavigationManager.getDataArray(this, "specialities");

    LatLngBounds.Builder builder = new LatLngBounds.Builder();
    cursor = db.getCenterTypeCursor(centerTypeCode, munCode, specialities);

    if (cursor.moveToFirst()) {
        do {//  w ww. j a v a  2 s.  com
            String name = centerTypeCode + ":  " + cursor.getString(cursor.getColumnIndex("name"));
            String snippet = db.getCenterInfo(cursor, provinceName, munName, centerTypeCode, centerTypeName);
            String latitude = cursor.getString(cursor.getColumnIndex("latitude"));
            String longitude = cursor.getString(cursor.getColumnIndex("longitude"));
            LatLng position = new LatLng(Float.parseFloat(latitude), Float.parseFloat(longitude));
            builder.include(position);
            mMap.addMarker(new MarkerOptions().position(position).title(name).snippet(snippet)
                    .icon(BitmapDescriptorFactory.fromResource(iconTypes.get(centerTypeCode))));

        } while (cursor.moveToNext());

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

        mMap.animateCamera(CameraUpdateFactory.newLatLngBounds(builder.build(), 50));
    } else {
        Toast toast = Toast.makeText(this, R.string.no_results, Toast.LENGTH_SHORT);
        toast.show();
    }
}

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

public ArrayList<Object[]> _qaData(String where) {
    ArrayList<Object[]> data = new ArrayList<Object[]>();
    Cursor cur = null;
    try {//from   ww w.ja  v  a  2  s .c  o m
        cur = mDb.getDatabase().rawQuery("SELECT c.id, n.id, n.mid, c.did, c.ord, "
                + "n.tags, n.flds FROM cards c, notes n WHERE c.nid == n.id " + where, null);
        while (cur.moveToNext()) {
            data.add(new Object[] { cur.getLong(0), cur.getLong(1), cur.getLong(2), cur.getLong(3),
                    cur.getInt(4), cur.getString(5), cur.getString(6) });
        }
    } finally {
        if (cur != null && !cur.isClosed()) {
            cur.close();
        }
    }
    return data;
}

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

/**
 * Hourly Breakdown//w  w w  .  j a v a2  s . c o  m
 */
public boolean calculateBreakdown(int type) {
    mTitle = R.string.stats_breakdown;
    mAxisTitles = new int[] { R.string.stats_time_of_day, R.string.stats_percentage_correct,
            R.string.stats_reviews };

    mValueLabels = new int[] { R.string.stats_percentage_correct, R.string.stats_answers };
    mColors = new int[] { R.color.stats_counts, R.color.stats_hours };

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

    if (lim.length() > 0) {
        lim = " and " + lim;
    }

    Calendar sd = GregorianCalendar.getInstance();
    sd.setTimeInMillis(mCol.getCrt() * 1000);

    int pd = _periodDays();
    if (pd > 0) {
        lim += " and id > " + ((mCol.getSched().getDayCutoff() - (86400 * pd)) * 1000);
    }
    long cutoff = mCol.getSched().getDayCutoff();
    long cut = cutoff - sd.get(Calendar.HOUR_OF_DAY) * 3600;

    ArrayList<double[]> list = new ArrayList<double[]>();
    Cursor cur = null;
    String query = "select " + "23 - ((cast((" + cut + " - id/1000) / 3600.0 as int)) % 24) as hour, "
            + "sum(case when ease = 1 then 0 else 1 end) / " + "cast(count() as float) * 100, " + "count() "
            + "from revlog where type in (0,1,2) " + lim + " "
            + "group by hour having count() > 30 order by hour";
    Timber.d(sd.get(Calendar.HOUR_OF_DAY) + " : " + cutoff + " breakdown 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 breakdown, for now only copied from intervals
    //small adjustment for a proper chartbuilding with achartengine
    if (list.size() == 0) {
        list.add(0, new double[] { 0, 0, 0 });
    }

    for (int i = 0; i < list.size(); i++) {
        double[] data = list.get(i);
        int intHour = (int) data[0];
        int hour = (intHour - 4) % 24;
        if (hour < 0)
            hour += 24;
        data[0] = hour;
        list.set(i, data);
    }
    Collections.sort(list, new Comparator<double[]>() {
        @Override
        public int compare(double[] s1, double[] s2) {
            if (s1[0] < s2[0])
                return -1;
            if (s1[0] > s2[0])
                return 1;
            return 0;
        }
    });

    mSeriesList = new double[4][list.size()];
    mPeak = 0.0;
    mMcount = 0.0;
    double minHour = Double.MAX_VALUE;
    double maxHour = 0;
    for (int i = 0; i < list.size(); i++) {
        double[] data = list.get(i);
        int hour = (int) data[0];

        //double hour = data[0];
        if (hour < minHour)
            minHour = hour;

        if (hour > maxHour)
            maxHour = hour;

        double pct = data[1];
        if (pct > mPeak)
            mPeak = pct;

        mSeriesList[0][i] = hour;
        mSeriesList[1][i] = pct;
        mSeriesList[2][i] = data[2];
        if (i == 0) {
            mSeriesList[3][i] = pct;
        } else {
            double prev = mSeriesList[3][i - 1];
            double diff = pct - prev;
            diff /= 3.0;
            diff = Math.round(diff * 10.0) / 10.0;

            mSeriesList[3][i] = prev + diff;
        }

        if (data[2] > mMcount)
            mMcount = data[2];
        if (mSeriesList[1][i] > mMaxCards)
            mMaxCards = (int) mSeriesList[1][i];
    }

    mFirstElement = mSeriesList[0][0];
    mLastElement = mSeriesList[0][mSeriesList[0].length - 1];
    mMaxElements = (int) (maxHour - minHour);

    //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 = 23;
    }
    if (mMaxCards == 0)
        mMaxCards = 10;
    return list.size() > 0;
}

From source file:org.opendatakit.common.android.database.DataModelDatabaseHelper.java

/**
 * Return a map of (elementKey -> ColumnDefinition)
 *
 * @param db//from   w ww.  ja  v  a  2s .  co m
 * @param tableId
 * @return
 * @throws JsonParseException
 * @throws JsonMappingException
 * @throws IOException
 */
public static Map<String, ColumnDefinition> getColumnDefinitions(SQLiteDatabase db, String tableId)
        throws JsonParseException, JsonMappingException, IOException {
    Map<String, ColumnDefinition> defn = new HashMap<String, ColumnDefinition>();

    Cursor c = null;
    try {
        c = db.query(COLUMN_DEFINITIONS_TABLE_NAME, null, ColumnDefinitionsColumns.TABLE_ID + "=?",
                new String[] { tableId }, null, null, null);

        if (c.moveToFirst()) {
            int idxEK = c.getColumnIndex(ColumnDefinitionsColumns.ELEMENT_KEY);
            int idxEN = c.getColumnIndex(ColumnDefinitionsColumns.ELEMENT_NAME);
            int idxET = c.getColumnIndex(ColumnDefinitionsColumns.ELEMENT_TYPE);
            int idxIP = c.getColumnIndex(ColumnDefinitionsColumns.IS_UNIT_OF_RETENTION);
            int idxLIST = c.getColumnIndex(ColumnDefinitionsColumns.LIST_CHILD_ELEMENT_KEYS);
            HashMap<String, ColumnContainer> ref = new HashMap<String, ColumnContainer>();

            do {
                String elementKey = c.getString(idxEK);
                String elementName = c.getString(idxEN);
                String elementType = c.getString(idxET);
                boolean isUnitOfRetention = (c.getInt(idxIP) != 0);
                String childrenString = c.isNull(idxLIST) ? null : c.getString(idxLIST);
                ColumnContainer ctn = new ColumnContainer();
                ctn.defn = new ColumnDefinition(elementKey, elementName, elementType, isUnitOfRetention);

                if (childrenString != null) {
                    @SuppressWarnings("unchecked")
                    ArrayList<String> l = ODKFileUtils.mapper.readValue(childrenString, ArrayList.class);
                    ctn.children = l;
                }

                ref.put(elementKey, ctn);
            } while (c.moveToNext());

            // OK now connect all the children...

            for (ColumnContainer ctn : ref.values()) {
                if (ctn.children != null) {
                    for (String ek : ctn.children) {
                        ColumnContainer child = ref.get(ek);
                        if (child == null) {
                            throw new IllegalArgumentException("Unexpected missing child element: " + ek);
                        }
                        ctn.defn.addChild(child.defn);
                    }
                }
            }

            // and construct the list of entries...
            for (ColumnContainer ctn : ref.values()) {
                defn.put(ctn.defn.elementKey, ctn.defn);
            }
            return defn;
        }
    } finally {
        if (c != null && !c.isClosed()) {
            c.close();
        }
    }
    return null;
}

From source file:holidayiq.com.geofenced.geofence.GeofenceTransitionsIntentService.java

public static void SendNotificationForEntry(Context mContext, String geoId, String geoName,
        String notificationStringTitle, String notificationStringContent, String notificationStringDeeplink,
        String objType, Context context, String eventType, boolean isBanner) {
    String currentTime = String.valueOf(System.currentTimeMillis());
    if (notificationStringTitle != null) {
        notificationStringTitle = notificationStringTitle.replace("$name$", geoName);
        notificationStringContent = notificationStringContent.replace("$name$", geoName);
        notificationStringDeeplink = notificationStringDeeplink.replace("$name$", Underscored(geoName));
        notificationStringDeeplink = notificationStringDeeplink.replace("$id$", geoId);
        Calendar c = new GregorianCalendar();
        c.set(Calendar.HOUR_OF_DAY, 6);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        Date d1 = c.getTime();//from   w  ww.  j  a  v a  2  s. com
        boolean isNotification = false;
        File dbFile = mContext.getDatabasePath("hiq_in_app.sqlite");
        SQLiteDatabase inAppDb = SQLiteDatabase.openDatabase(dbFile.getPath(), null,
                SQLiteDatabase.OPEN_READWRITE);
        if (geoName.equalsIgnoreCase("home")) {
            String lastTriggeredHome = HIQSharedPrefrence.getString("lastTriggeredHome", mContext);
            if (lastTriggeredHome == null) {
                sendNotification(notificationStringTitle, notificationStringContent, notificationStringDeeplink,
                        context, isBanner);
                HIQSharedPrefrence.putString("lastTriggeredHome", System.currentTimeMillis() + "", mContext);
                isNotification = true;
            } else {
                long previouslastTriggeredHome = Long
                        .parseLong(HIQSharedPrefrence.getString("lastTriggeredHome", mContext));
                if (previouslastTriggeredHome < d1.getTime()) {
                    sendNotification(notificationStringTitle, notificationStringContent,
                            notificationStringDeeplink, context, isBanner);
                    HIQSharedPrefrence.putString("lastTriggeredHome", System.currentTimeMillis() + "",
                            mContext);
                    isNotification = true;
                }
            }

        } else if (objType.equalsIgnoreCase("Hotel")) {
            String lastTriggeredHome = HIQSharedPrefrence.getString("lastTriggeredHotel", mContext);
            if (lastTriggeredHome == null) {
                sendNotification(notificationStringTitle, notificationStringContent, notificationStringDeeplink,
                        context, isBanner);
                HIQSharedPrefrence.putString("lastTriggeredHotel", System.currentTimeMillis() + "", mContext);
                isNotification = true;
            } else {
                long previouslastTriggeredHome = Long
                        .parseLong(HIQSharedPrefrence.getString("lastTriggeredHotel", mContext));
                if (previouslastTriggeredHome < d1.getTime()) {
                    sendNotification(notificationStringTitle, notificationStringContent,
                            notificationStringDeeplink, context, isBanner);
                    HIQSharedPrefrence.putString("lastTriggeredHotel", System.currentTimeMillis() + "",
                            mContext);
                    isNotification = true;
                }
            }
        } else if (objType.equalsIgnoreCase("SS")) {
            Cursor res = null;
            try {
                String lastNotificationTriggerd = null;
                res = inAppDb.rawQuery("Select * from " + GeoDbHelper.SIGHT_SEEING_TABLE_NAME + " where "
                        + GeoDbHelper.SIGHT_SEEING_COULUMN_ID + " = " + geoId, null);
                if (res != null) {
                    if (res.moveToFirst()) {
                        lastNotificationTriggerd = res.getString(res.getColumnIndex("lastTimeStamp"));
                    }
                }
                if (lastNotificationTriggerd == null) {
                    sendNotification(notificationStringTitle, notificationStringContent,
                            notificationStringDeeplink, context, isBanner);
                    isNotification = true;
                    Cursor cur = inAppDb.rawQuery("update " + GeoDbHelper.SIGHT_SEEING_TABLE_NAME
                            + " SET lastTimeStamp = '" + currentTime + "' where "
                            + GeoDbHelper.SIGHT_SEEING_COULUMN_ID + " = " + geoId, null);
                    cur.moveToFirst();
                    cur.close();
                } else {
                    long time = Long.parseLong(lastNotificationTriggerd);
                    if (time < d1.getTime()) {
                        sendNotification(notificationStringTitle, notificationStringContent,
                                notificationStringDeeplink, context, isBanner);
                        isNotification = true;
                        Cursor cur = inAppDb.rawQuery("update " + GeoDbHelper.SIGHT_SEEING_TABLE_NAME
                                + " SET lastTimeStamp = '" + currentTime + "' where "
                                + GeoDbHelper.SIGHT_SEEING_COULUMN_ID + " = " + geoId, null);
                        cur.moveToFirst();
                        cur.close();
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
                ExceptionUtils.logException(e);
            } finally {
                if (res != null && !res.isClosed()) {
                    res.close();
                }
                res = null;
                if (inAppDb != null && inAppDb.isOpen()) {
                    inAppDb.close();
                }
                inAppDb = null;
            }
        } else if (objType.equalsIgnoreCase("Destination")) {
            Cursor res = null;
            try {
                String lastNotificationTriggerd = null;
                res = inAppDb.rawQuery("Select * from " + GeoDbHelper.DESTINATION_TABLE_NAME + " where "
                        + GeoDbHelper.DESTINATION_COLUMN_ID + " = " + geoId, null);
                if (res != null) {
                    try {
                        if (res.moveToFirst()) {
                            lastNotificationTriggerd = res.getString(res.getColumnIndex("lastTimeStamp"));
                        }
                    } catch (Exception e) {

                    }
                }
                if (lastNotificationTriggerd == null) {
                    sendNotification(notificationStringTitle, notificationStringContent,
                            notificationStringDeeplink, context, isBanner);
                    isNotification = true;
                    Cursor cur = inAppDb.rawQuery("update " + GeoDbHelper.DESTINATION_TABLE_NAME
                            + " SET lastTimeStamp = '" + currentTime + "' where "
                            + GeoDbHelper.DESTINATION_COLUMN_ID + " = " + geoId, null);
                    cur.moveToFirst();
                    cur.close();
                } else {
                    long time = Long.parseLong(lastNotificationTriggerd);
                    if (time < d1.getTime()) {
                        sendNotification(notificationStringTitle, notificationStringContent,
                                notificationStringDeeplink, context, isBanner);
                        isNotification = true;
                        Cursor cur = inAppDb.rawQuery("update " + GeoDbHelper.DESTINATION_TABLE_NAME
                                + " SET lastTimeStamp = '" + currentTime + "' where "
                                + GeoDbHelper.DESTINATION_COLUMN_ID + " = " + geoId, null);
                        cur.moveToFirst();
                        cur.close();
                    }
                }

            } catch (Exception e) {
                ExceptionUtils.logException(e);
            } finally {
                if (res != null && !res.isClosed()) {
                    res.close();
                }
                res = null;
                if (inAppDb != null && inAppDb.isOpen()) {
                    inAppDb.close();
                }
                inAppDb = null;
            }
        }
        HashMap<String, Object> oMap = new HashMap<String, Object>();
        oMap.put("Type", eventType);
        oMap.put("Name", geoName);
        oMap.put("ID", geoId);
        oMap.put("Object Type", objType);
        oMap.put("Date", new Date());

        if (isNotification) {
        }
    }

    // HIQUtil.sendEventToGAFromObject("GeoFenceEvent", "GeoFenceEvent in Android", oMap);

}

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

/**
 * Weekly Breakdown/*ww w  .j  a v a 2  s  .c  om*/
 */

public boolean calculateWeeklyBreakdown(int type) {
    mTitle = R.string.stats_weekly_breakdown;
    mAxisTitles = new int[] { R.string.stats_day_of_week, R.string.stats_percentage_correct,
            R.string.stats_reviews };

    mValueLabels = new int[] { R.string.stats_percentage_correct, R.string.stats_answers };
    mColors = new int[] { R.color.stats_counts, R.color.stats_hours };

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

    if (lim.length() > 0) {
        lim = " and " + lim;
    }

    Calendar sd = GregorianCalendar.getInstance();
    sd.setTimeInMillis(mCol.getSched().getDayCutoff() * 1000);

    int pd = _periodDays();
    if (pd > 0) {
        lim += " and id > " + ((mCol.getSched().getDayCutoff() - (86400 * pd)) * 1000);
    }

    long cutoff = mCol.getSched().getDayCutoff();
    long cut = cutoff - sd.get(Calendar.HOUR_OF_DAY) * 3600;

    ArrayList<double[]> list = new ArrayList<double[]>();
    Cursor cur = null;
    String query = "SELECT strftime('%w',datetime( cast(id/ 1000  -" + sd.get(Calendar.HOUR_OF_DAY) * 3600
            + " as int), 'unixepoch')) as wd, " + "sum(case when ease = 1 then 0 else 1 end) / "
            + "cast(count() as float) * 100, " + "count() " + "from revlog " + "where type in (0,1,2) " + lim
            + " " + "group by wd " + "order by wd";
    Timber.d(sd.get(Calendar.HOUR_OF_DAY) + " : " + cutoff + " weekly breakdown 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 breakdown, for now only copied from intervals
    // small adjustment for a proper chartbuilding with achartengine
    if (list.size() == 0) {
        list.add(0, new double[] { 0, 0, 0 });
    }

    mSeriesList = new double[4][list.size()];
    mPeak = 0.0;
    mMcount = 0.0;
    double minHour = Double.MAX_VALUE;
    double maxHour = 0;
    for (int i = 0; i < list.size(); i++) {
        double[] data = list.get(i);
        int hour = (int) data[0];

        //double hour = data[0];
        if (hour < minHour)
            minHour = hour;

        if (hour > maxHour)
            maxHour = hour;

        double pct = data[1];
        if (pct > mPeak)
            mPeak = pct;

        mSeriesList[0][i] = hour;
        mSeriesList[1][i] = pct;
        mSeriesList[2][i] = data[2];
        if (i == 0) {
            mSeriesList[3][i] = pct;
        } else {
            double prev = mSeriesList[3][i - 1];
            double diff = pct - prev;
            diff /= 3.0;
            diff = Math.round(diff * 10.0) / 10.0;

            mSeriesList[3][i] = prev + diff;
        }

        if (data[2] > mMcount)
            mMcount = data[2];
        if (mSeriesList[1][i] > mMaxCards)
            mMaxCards = (int) mSeriesList[1][i];
    }
    mFirstElement = mSeriesList[0][0];
    mLastElement = mSeriesList[0][mSeriesList[0].length - 1];
    mMaxElements = (int) (maxHour - minHour);

    //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 list.size() > 0;
}

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

/**
 * Insert the values existing in the file specified by
 * {@link DATA_FILE_PATH_AND_NAME} into the form specified by params.
 * <p>/* w  ww  .  ja v a2  s. com*/
 * If the display name is not defined in the {@code params} parameter then the
 * string resource is used.
 * <p>
 * The inserted row is marked as INCOMPLETE.
 * <p>
 * PRECONDITION: in order to be populated with data, the data file containing
 * the row's data must have been written, most likely by calling
 * writeRowDataToBeEdited().
 * <p>
 * PRECONDITION: previous instances should already have been deleted by now,
 * or the passed in file names should be uniqued by adding timestamps, or
 * something.
 *
 * @param params
 *          the identifying parameters for the form. Should be the same object
 *          used to write the instance file.
 * @param rowNum
 *          the row number of the row being edited
 * @param resolver
 *          the ContentResolver of the activity making the request.
 * @return
 */
/*
 * This is based on the code at: http://code.google.com/p/opendatakit/source/
 * browse/src/org/odk/collect/android/tasks/SaveToDiskTask.java?repo=collect
 * in the method updateInstanceDatabase().
 */
private static Uri getUriForCollectInstanceForRowData(Context context, String appName, String tableId,
        CollectFormParameters params, String rowId, boolean shouldUpdate) {

    String instanceFilePath = getEditRowFormFile(appName, tableId, rowId).getAbsolutePath();

    ContentValues values = new ContentValues();
    // First we need to fill the values with various little things.
    values.put(COLLECT_KEY_STATUS, COLLECT_KEY_STATUS_INCOMPLETE);
    values.put(COLLECT_KEY_CAN_EDIT_WHEN_COMPLETE, Boolean.toString(true));
    values.put(COLLECT_KEY_INSTANCE_FILE_PATH, instanceFilePath);
    values.put(COLLECT_KEY_JR_FORM_ID, params.getFormId());
    values.put(COLLECT_KEY_DISPLAY_NAME,
            params.getRowDisplayName() + "_" + WebUtils.get().iso8601Date(new Date()));
    // only add the version if it exists (ie not null)
    if (params.getFormVersion() != null) {
        values.put(COLLECT_KEY_JR_VERSION, params.getFormVersion());
    }

    ContentResolver resolver = context.getContentResolver();
    Uri uriOfForm;
    if (shouldUpdate) {
        int count = resolver.update(CONTENT_INSTANCE_URI, values, COLLECT_KEY_INSTANCE_FILE_PATH + "=?",
                new String[] { instanceFilePath });
        if (count == 0) {
            uriOfForm = resolver.insert(CONTENT_INSTANCE_URI, values);
        } else {
            Cursor c = null;
            try {
                c = resolver.query(CONTENT_INSTANCE_URI, null, COLLECT_KEY_INSTANCE_FILE_PATH + "=?",
                        new String[] { instanceFilePath }, COLLECT_INSTANCE_ORDER_BY);

                if (c.moveToFirst()) {
                    // we got a result, meaning that the form exists in collect.
                    // so we just need to set the URI.
                    int collectInstanceKey; // this is the primary key of the form in
                    // Collect's
                    // database.
                    collectInstanceKey = ODKDatabaseUtils.get().getIndexAsType(c, Integer.class,
                            c.getColumnIndexOrThrow(BaseColumns._ID));
                    uriOfForm = (Uri.parse(CONTENT_INSTANCE_URI + "/" + collectInstanceKey));
                    c.close();
                } else {
                    c.close();
                    throw new IllegalStateException("it was updated we should have found the record!");
                }
            } finally {
                if (c != null && !c.isClosed()) {
                    c.close();
                }
            }
        }
    } else {
        // now we want to get the uri for the insertion.
        uriOfForm = resolver.insert(CONTENT_INSTANCE_URI, values);
    }
    return uriOfForm;
}

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

public String emptyCardReport(List<Long> cids) {
    StringBuilder rep = new StringBuilder();
    Cursor cur = null;
    try {// www.  j av a2  s. c om
        cur = mDb.getDatabase().rawQuery("select group_concat(ord+1), count(), flds from cards c, notes n "
                + "where c.nid = n.id and c.id in " + Utils.ids2str(cids) + " group by nid", null);
        while (cur.moveToNext()) {
            String ords = cur.getString(0);
            int cnt = cur.getInt(1);
            String flds = cur.getString(2);
            rep.append(String.format("Empty card numbers: %s\nFields: %s\n\n", ords,
                    flds.replace("\u001F", " / ")));
        }
    } finally {
        if (cur != null && !cur.isClosed()) {
            cur.close();
        }
    }
    return rep.toString();
}

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

/**
 * Remove definitions from the Forms database that are no longer present on
 * disk.//from   w w w .j  a va2 s  .  co m
 */
private final void removeStaleFormInfo() {
    Log.i(t, "[" + instanceCounter + "] removeStaleFormInfo " + appName + " begin");
    ArrayList<Uri> badEntries = new ArrayList<Uri>();
    Cursor c = null;
    try {
        c = context.getContentResolver().query(Uri.withAppendedPath(formsProviderContentUri, appName), null,
                null, null, null);

        if (c == null) {
            Log.w(t, "[" + instanceCounter + "] removeStaleFormInfo " + appName
                    + " null cursor returned from query.");
            return;
        }

        if (c.moveToFirst()) {
            do {
                String id = c.getString(c.getColumnIndex(FormsColumns.FORM_ID));
                Uri otherUri = Uri.withAppendedPath(Uri.withAppendedPath(formsProviderContentUri, appName), id);

                int appRelativeFormMediaPathIdx = c.getColumnIndex(FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH);
                if (appRelativeFormMediaPathIdx == -1) {
                    throw new IllegalStateException("Column " + FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH
                            + " missing from database table. Incompatible versions?");
                }
                String appRelativeFormMediaPath = c.getString(appRelativeFormMediaPathIdx);
                File f = ODKFileUtils.asAppFile(appName, appRelativeFormMediaPath);
                if (!f.exists() || !f.isDirectory()) {
                    // the form definition does not exist
                    badEntries.add(otherUri);
                }
            } while (c.moveToNext());
        }
    } catch (Exception e) {
        Log.e(t, "[" + instanceCounter + "] removeStaleFormInfo " + appName + " exception: " + e.toString());
        e.printStackTrace();
    } finally {
        if (c != null && !c.isClosed()) {
            c.close();
        }
    }

    // delete the other entries (and directories)
    for (Uri badUri : badEntries) {
        Log.i(t, "[" + instanceCounter + "] removeStaleFormInfo: " + appName + " deleting: "
                + badUri.toString());
        try {
            context.getContentResolver().delete(badUri, null, null);
        } catch (Exception e) {
            Log.e(t, "[" + instanceCounter + "] removeStaleFormInfo " + appName + " exception: "
                    + e.toString());
            e.printStackTrace();
            // and continue -- don't throw an error
        }
    }
    Log.i(t, "[" + instanceCounter + "] removeStaleFormInfo " + appName + " end");
}

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

/**
 * Todays statistics//from w w w.  j a  v a  2s  .com
 */
public int[] calculateTodayStats() {
    String lim = _revlogLimit();
    if (lim.length() > 0)
        lim = " and " + lim;

    Cursor cur = null;
    String query = "select count(), sum(time)/1000, " + "sum(case when ease = 1 then 1 else 0 end), "
            + /* failed */
            "sum(case when type = 0 then 1 else 0 end), " + /* learning */
            "sum(case when type = 1 then 1 else 0 end), " + /* review */
            "sum(case when type = 2 then 1 else 0 end), " + /* relearn */
            "sum(case when type = 3 then 1 else 0 end) " + /* filter */
            "from revlog where id > " + ((mCol.getSched().getDayCutoff() - 86400) * 1000) + " " + lim;
    Timber.d("todays statistics query: %s", query);

    int cards, thetime, failed, lrn, rev, relrn, filt;
    try {
        cur = mCol.getDb().getDatabase().rawQuery(query, null);

        cur.moveToFirst();
        cards = cur.getInt(0);
        thetime = cur.getInt(1);
        failed = cur.getInt(2);
        lrn = cur.getInt(3);
        rev = cur.getInt(4);
        relrn = cur.getInt(5);
        filt = cur.getInt(6);

    } finally {
        if (cur != null && !cur.isClosed()) {
            cur.close();
        }
    }
    query = "select count(), sum(case when ease = 1 then 0 else 1 end) from revlog "
            + "where lastIvl >= 21 and id > " + ((mCol.getSched().getDayCutoff() - 86400) * 1000) + " " + lim;
    Timber.d("todays statistics query 2: %s", query);

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

        cur.moveToFirst();
        mcnt = cur.getInt(0);
        msum = cur.getInt(1);
    } finally {
        if (cur != null && !cur.isClosed()) {
            cur.close();
        }
    }

    return new int[] { cards, thetime, failed, lrn, rev, relrn, filt, mcnt, msum };
}