Example usage for android.database.sqlite SQLiteDatabase isOpen

List of usage examples for android.database.sqlite SQLiteDatabase isOpen

Introduction

In this page you can find the example usage for android.database.sqlite SQLiteDatabase isOpen.

Prototype

public boolean isOpen() 

Source Link

Document

Returns true if the database is currently open.

Usage

From source file:com.triarc.sync.SyncAdapter.java

@SuppressLint("NewApi")
private JSONObject getVersions(SyncType type, SyncTypeCollection collection, MutableBoolean hasUpdates) {
    JSONObject changeSet = new JSONObject();
    JSONArray entityVersions = new JSONArray();
    SQLiteDatabase openDatabase = null;
    Cursor query = null;/*from  ww  w.  jav  a2 s. com*/
    try {
        changeSet.put("entityVersions", entityVersions);
        openDatabase = openDatabase(collection);

        query = openDatabase.query(type.getName(),
                new String[] { "_id", "_timestamp", "__internalTimestamp", "__state" }, null, null, null, null,
                "__internalTimestamp ASC");
        while (query.moveToNext()) {
            syncResult.stats.numEntries++;
            JSONObject jsonObject = new JSONObject();

            int fieldType = query.getType(0);
            String id = query.getString(0);
            String queryId = this.getQueryId(fieldType, id);

            jsonObject.put("id", id);
            jsonObject.put("timestamp", query.getLong(1));
            jsonObject.put("clientTimestamp", query.getLong(2));
            int state = query.getInt(3);
            if (state != UNCHANGED) {
                hasUpdates.setValue(true);
            }
            if (state == ADDED || state == UPDATED) {
                appendEntity(type, openDatabase, jsonObject, queryId);
            }
            jsonObject.put("state", state);
            entityVersions.put(jsonObject);
        }
    } catch (Exception e) {
        syncResult.stats.numIoExceptions++;
        syncResult.stats.numSkippedEntries++;
        syncResult.databaseError = true;
        e.printStackTrace();
        sendLogs();
    } finally {
        if (query != null)
            query.close();
        if (openDatabase != null && openDatabase.isOpen())
            closeDb(collection.getName());
    }
    return changeSet;
}

From source file:org.rapidandroid.activity.chart.form.FormDataBroker.java

/**
 * Should return a two element array - the first element is the data, the
 * second are the options// ww  w .  jav  a2 s.c o  m
 * 
 * @return
 */
private JSONGraphData loadHistogramFromField() {
    // JSONObject result = new JSONObject();
    SQLiteDatabase db = rawDB.getReadableDatabase();

    String fieldcol = RapidSmsDBConstants.FormData.COLUMN_PREFIX + fieldToPlot.getName();
    StringBuilder rawQuery = new StringBuilder();
    rawQuery.append("select " + fieldcol);
    rawQuery.append(", count(*) from ");
    rawQuery.append(RapidSmsDBConstants.FormData.TABLE_PREFIX + mForm.getPrefix());

    rawQuery.append(" join rapidandroid_message on (");
    rawQuery.append(RapidSmsDBConstants.FormData.TABLE_PREFIX + mForm.getPrefix());
    rawQuery.append(".message_id = rapidandroid_message._id");
    rawQuery.append(") ");

    if (mStartDate.compareTo(Constants.NULLDATE) != 0 && mEndDate.compareTo(Constants.NULLDATE) != 0) {
        rawQuery.append(" WHERE rapidandroid_message.time > '" + Message.SQLDateFormatter.format(mStartDate)
                + "' AND rapidandroid_message.time < '" + Message.SQLDateFormatter.format(mEndDate) + "' ");
    }

    rawQuery.append(" group by " + fieldcol);
    rawQuery.append(" order by " + fieldcol);

    // the string value is column 0
    // the magnitude is column 1

    Cursor cr = db.rawQuery(rawQuery.toString(), null);
    int barCount = cr.getCount();

    if (barCount != 0) {
        String[] xVals = new String[barCount];
        int[] yVals = new int[barCount];
        cr.moveToFirst();
        int i = 0;
        do {
            xVals[i] = cr.getString(0);
            yVals[i] = cr.getInt(1);
            i++;
        } while (cr.moveToNext());

        // xaxis: { ticks: [0, [Math.PI/2, "\u03c0/2"], [Math.PI, "\u03c0"],
        // [Math.PI * 3/2, "3\u03c0/2"], [Math.PI * 2, "2\u03c0"]]},

        try {
            // result.put("label", fieldToPlot.getName());
            // result.put("data", prepareData(xVals, yVals));
            // result.put("bars", getShowTrue());
            // result.put("xaxis", getXaxisOptions(xVals));
            return new JSONGraphData(prepareHistogramData(xVals, yVals), loadOptionsForHistogram(xVals));
        } 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.rapidandroid.activity.chart.form.FormDataBroker.java

private JSONGraphData loadBooleanPlot() {

    Date startDateToUse = getStartDate();
    DateDisplayTypes displayType = this.getDisplayType(startDateToUse, mEndDate);

    String selectionArg = getSelectionString(displayType);

    StringBuilder rawQuery = new StringBuilder();

    String fieldcol = RapidSmsDBConstants.FormData.COLUMN_PREFIX + fieldToPlot.getName();

    rawQuery.append("select time, " + fieldcol + ", count(*) from  ");
    rawQuery.append(RapidSmsDBConstants.FormData.TABLE_PREFIX + mForm.getPrefix());

    rawQuery.append(" join rapidandroid_message on (");
    rawQuery.append(RapidSmsDBConstants.FormData.TABLE_PREFIX + mForm.getPrefix());
    rawQuery.append(".message_id = rapidandroid_message._id");
    rawQuery.append(") ");
    if (startDateToUse.compareTo(Constants.NULLDATE) != 0 && mEndDate.compareTo(Constants.NULLDATE) != 0) {
        rawQuery.append(" WHERE rapidandroid_message.time > '" + Message.SQLDateFormatter.format(startDateToUse)
                + "' AND rapidandroid_message.time < '" + Message.SQLDateFormatter.format(mEndDate) + "' ");
    }//from  ww w. jav a  2  s .  c o  m

    rawQuery.append(" group by ").append(selectionArg).append(", " + fieldcol);
    rawQuery.append(" order by ").append("time").append(" ASC");

    SQLiteDatabase db = rawDB.getReadableDatabase();
    // the string value is column 0
    // the magnitude is column 1
    Log.d("query", rawQuery.toString());
    Cursor cr = db.rawQuery(rawQuery.toString(), null);
    // TODO Auto-generated method stub
    int barCount = cr.getCount();
    Date[] allDates = new Date[barCount];
    if (barCount == 0) {
        db.close();
        cr.close();
    } else {
        List<Date> xValsTrue = new ArrayList<Date>();
        // Date[] xValsTrue = new Date[barCount];
        List<Integer> yValsTrue = new ArrayList<Integer>();
        List<Date> xValsFalse = new ArrayList<Date>();
        // Date[] xValsTrue = new Date[barCount];
        List<Integer> yValsFalse = new ArrayList<Integer>();
        cr.moveToFirst();
        int i = 0;
        do {
            String trueFalse = cr.getString(1);
            // int trueFalse2 = cr.getInt(fieldcol);
            // String trueFalseStr = cr.getString(1);

            Date thisDate = getDate(displayType, cr.getString(0));
            Log.d("FormDataBroker: ", cr.getString(0) + ", " + trueFalse + " , " + cr.getInt(2));

            if (trueFalse.equals("true")) {
                xValsFalse.add(thisDate);
                yValsFalse.add(new Integer(cr.getInt(2)));
            } else {
                xValsTrue.add(thisDate);
                yValsTrue.add(new Integer(cr.getInt(2)));
            }
            allDates[i] = thisDate;
            i++;
        } while (cr.moveToNext());

        try {
            //            String legend = this.getLegendString(displayType);
            int[] yVals = getIntsFromList(yValsTrue);
            JSONArray trueArray = getJSONArrayForValues(displayType, xValsTrue.toArray(new Date[0]), yVals);
            yVals = getIntsFromList(yValsFalse);
            JSONArray falseArray = getJSONArrayForValues(displayType, xValsFalse.toArray(new Date[0]), yVals);
            JSONArray finalValues = new JSONArray();
            JSONObject trueElem = new JSONObject();
            trueElem.put("data", trueArray);
            trueElem.put("label", "Yes");
            trueElem.put("lines", getShowTrue());
            finalValues.put(trueElem);
            JSONObject falseElem = new JSONObject();
            falseElem.put("data", falseArray);
            falseElem.put("label", "No");
            falseElem.put("lines", getShowTrue());
            finalValues.put(falseElem);
            return new JSONGraphData(finalValues, loadOptionsForDateGraph(allDates, 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: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  .  c  o m*/
        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);

}