Example usage for android.database.sqlite SQLiteDatabase close

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

Introduction

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

Prototype

public void close() 

Source Link

Document

Releases a reference to the object, closing the object if the last reference was released.

Usage

From source file:com.rener.sea.DBHelper.java

private JSONArray getLocation() {

    JSONArray data;//from  www.  ja  va 2s. c  o m
    data = new JSONArray();
    SQLiteDatabase db = getReadableDatabase();
    Cursor cursor = db.query(DBSchema.TABLE_LOCATION,
            new String[] { DBSchema.LOCATION_ID, DBSchema.LOCATION_NAME, DBSchema.LOCATION_ADDRESS_ID,
                    DBSchema.LOCATION_OWNER_ID, DBSchema.LOCATION_MANAGER_ID, DBSchema.LOCATION_LICENSE,
                    DBSchema.LOCATION_AGENT_ID },
            DBSchema.MODIFIED + "=?", new String[] { DBSchema.MODIFIED_YES }, null, null, null, null);
    if (cursor.moveToFirst()) {
        if ((cursor != null) && (cursor.getCount() > 0))
            for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
                JSONObject map = new JSONObject();
                try {
                    if (!cursor.isNull(0))
                        map.put(DBSchema.LOCATION_ID, cursor.getString(0));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                try {
                    if (!cursor.isNull(1))
                        map.put(DBSchema.LOCATION_NAME, cursor.getString(1));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                try {
                    if (!cursor.isNull(2))
                        map.put(DBSchema.LOCATION_ADDRESS_ID, cursor.getString(2));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                try {
                    if (!cursor.isNull(3))
                        map.put(DBSchema.LOCATION_OWNER_ID, cursor.getString(3));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                try {
                    if (!cursor.isNull(4))
                        map.put(DBSchema.LOCATION_MANAGER_ID, cursor.getString(4));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                try {
                    if (!cursor.isNull(5))
                        map.put(DBSchema.LOCATION_LICENSE, cursor.getString(5));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                try {
                    if (!cursor.isNull(6))
                        map.put(DBSchema.LOCATION_AGENT_ID, cursor.getString(6));
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                data.put(map);
            }
    }
    db.close();
    cursor.close();
    return data;

}

From source file:com.example.rartonne.appftur.HomeActivity.java

public void syncDwh() {
    String[] tables = { "pda_sec_id_data",
            //"batch_nr_checking",
            //"customer_incident",
            //"PROCESS_LOG",
            "\"SCAN_LOG\"", "ordernr_sites" };

    for (String table : tables) {
        try {//from w  ww . ja va 2  s  . c  o m
            String fields = "";
            String values = "";
            String urlPost = "http://admin.qr-ut.com/webservice/pdaws.php?action=syncDwh";
            List<NameValuePair> data = new ArrayList<>();
            String param = "";
            String updateScanlog = "";
            String updatePdaSecIdData = "";
            //on initalise la connexion  la base
            SQLiteDatabase bdd;
            DataBaseHelper myDbHelper = new DataBaseHelper(getApplicationContext());
            String format = "yyyy/MM/dd HH:mm:ss";
            SimpleDateFormat formater = new SimpleDateFormat(format);
            String date = formater.format(new Date());

            try {
                myDbHelper.createDataBase();
            } catch (IOException e) {
                e.printStackTrace();
            }

            myDbHelper.openDataBase();

            bdd = myDbHelper.getWritableDatabase();

            Cursor cursor;

            if (table == "\"SCAN_LOG\"") {
                cursor = bdd.rawQuery("SELECT * FROM " + table, null);
            } else if (table == "ordernr_sites") {
                cursor = bdd
                        .rawQuery(
                                "SELECT ordernr, status_code, modified_by, modified_on, installer_id FROM "
                                        + table + " WHERE modified_on > '" + GlobalClass.getLastUpdate() + "'",
                                null);
            } else {
                cursor = bdd.rawQuery("SELECT * FROM " + table + " WHERE createdon > " + "'"
                        + GlobalClass.getLastUpdate() + "'", null);
            }

            while (cursor.moveToNext()) {
                switch (table) {
                case "pda_sec_id_data":
                    fields = "type, value, createdon, modifiedon, gf_sec_id";
                    values = "'" + cursor.getString(1) + "', '" + cursor.getString(2) + "', '"
                            + cursor.getString(3) + "', '" + cursor.getString(4) + "', '" + cursor.getString(5)
                            + "'";
                    updatePdaSecIdData = "UPDATE pda_sec_id_data SET value = '" + cursor.getString(2)
                            + "', modifiedon = '" + cursor.getString(4) + "' WHERE gf_sec_id = '"
                            + cursor.getString(5) + "' AND type = '" + cursor.getString(1) + "';";
                    break;

                case "batch_nr_checking":
                    fields = "createdon, modifiedon, gps_lat, gps_long, createdby, modifiedby, status_code, isonline, checking_source, last_update_batch, last_synchro_blacklist, gf_sec_id, batch_nr_checking_id, batch_nr, article_id";
                    values = "";
                    break;

                case "customer_incident":
                    fields = "";
                    values = "";
                    break;

                case "PROCESS_LOG":
                    fields = "process_type, process_date, comment, object_name, status_code, interface_type, action";
                    values = "'" + cursor.getString(0) + "', '" + cursor.getString(1) + "', '"
                            + cursor.getString(2) + "', '" + cursor.getString(3) + "', " + cursor.getInt(4)
                            + ", '" + cursor.getString(5) + "', '" + cursor.getString(6) + "'";
                    break;

                case "\"SCAN_LOG\"":
                    fields = "gf_sec_id, gps_lat, gps_long, scan_date, user_id, status_code, art_id, customer_order_nr, welding_sketch_nr, serial_wm_nr, fusion_nr, source";
                    values = "'" + cursor.getString(0) + "', " + cursor.getDouble(1) + ", "
                            + cursor.getDouble(2) + ", '" + cursor.getString(3) + "', " + cursor.getInt(4)
                            + ", " + cursor.getInt(5) + ", '" + cursor.getString(6) + "', '"
                            + cursor.getString(7) + "', '" + cursor.getString(8) + "', '" + cursor.getString(9)
                            + "', " + cursor.getInt(10) + ", '" + cursor.getString(11) + "'";
                    updateScanlog += "UPDATE \"SCAN_LOG\" SET gps_lat = " + cursor.getDouble(1)
                            + ", gps_long = " + cursor.getDouble(2) + ", scan_date = '" + cursor.getString(3)
                            + "'" + ", user_id = " + cursor.getInt(4) + ", status_code = " + cursor.getInt(5)
                            + ", art_id = '" + cursor.getString(6) + "', customer_order_nr = '"
                            + cursor.getString(7) + "'" + ", welding_sketch_nr = '" + cursor.getString(8)
                            + "', serial_wm_nr = '" + cursor.getString(9) + "', fusion_nr = "
                            + cursor.getInt(10) + " WHERE gf_sec_id = '" + cursor.getString(0)
                            + "' AND source = 'PDA';";
                    break;

                case "ordernr_sites":
                    fields = "ordernr, status_code, modified_by, modified_on, installer_id";
                    values = "'" + cursor.getString(0) + "', " + cursor.getInt(1) + ", " + cursor.getInt(2)
                            + ", '" + cursor.getString(3) + "', " + cursor.getInt(4);
                    break;
                }
                param += "INSERT INTO " + table + " (" + fields + ") VALUES (" + values + ");";
                //break;
            }

            param += updatePdaSecIdData;
            param += updateScanlog;
            param += "UPDATE pda_settings SET last_update = '" + GlobalClass.getLastUpdate()
                    + "' WHERE pda_id = '" + GlobalClass.getSerialNumber() + "'";
            data.add(new BasicNameValuePair("data", param));

            //on envoie les INSERT
            new HttpAsyncTaskPost(this, data).execute(urlPost);

            cursor.close();

            bdd.close();

            GlobalClass.setLastUpdate(date);
            startActivity(new Intent(this, HomeActivity.class)
                    .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | IntentCompat.FLAG_ACTIVITY_CLEAR_TASK));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:com.rener.sea.DBHelper.java

private JSONArray getPerson() {

    JSONArray data;/* www . ja  v  a 2  s.co m*/
    data = new JSONArray();
    SQLiteDatabase db = getReadableDatabase();
    Cursor cursor = db.query(DBSchema.TABLE_PERSON,
            new String[] { DBSchema.PERSON_ID, DBSchema.PERSON_LAST_NAME1, DBSchema.PERSON_FIRST_NAME,
                    DBSchema.PERSON_EMAIL,
                    //                        DBSchema.PERSON_SPEC_ID,
                    DBSchema.PERSON_LAST_NAME2, DBSchema.PERSON_MIDDLE_INITIAL, DBSchema.PERSON_PHONE_NUMBER },
            DBSchema.MODIFIED + "=?", new String[] { DBSchema.MODIFIED_YES }, null, null, null, null);
    if (cursor.moveToFirst()) {
        if ((cursor != null) && (cursor.getCount() > 0))
            for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
                JSONObject map = new JSONObject();
                try {
                    if (!cursor.isNull(0))
                        map.put(DBSchema.PERSON_ID, cursor.getString(0));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                try {
                    if (!cursor.isNull(1))
                        map.put(DBSchema.PERSON_LAST_NAME1, cursor.getString(1));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                try {
                    if (!cursor.isNull(2))
                        map.put(DBSchema.PERSON_FIRST_NAME, cursor.getString(2));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                try {
                    if (!cursor.isNull(3))
                        map.put(DBSchema.PERSON_EMAIL, cursor.getString(3));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                //                    try {
                //                        if (!cursor.isNull(4))
                //                            map.put(DBSchema.PERSON_SPEC_ID, cursor.getString(4));
                //                    } catch (JSONException e) {
                //                        e.printStackTrace();
                //                    }
                try {
                    if (!cursor.isNull(4))
                        map.put(DBSchema.PERSON_LAST_NAME2, cursor.getString(4));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                try {
                    if (!cursor.isNull(5))
                        map.put(DBSchema.PERSON_MIDDLE_INITIAL, cursor.getString(5));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                try {
                    if (!cursor.isNull(6))
                        map.put(DBSchema.PERSON_PHONE_NUMBER, cursor.getString(6));
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                data.put(map);
            }
    }
    db.close();
    cursor.close();
    return data;

}

From source file:com.rener.sea.DBHelper.java

private JSONArray getReport() {

    JSONArray data;/*  w w w  . ja  va2s . co m*/
    data = new JSONArray();
    SQLiteDatabase db = getReadableDatabase();
    Cursor cursor = db.query(DBSchema.TABLE_REPORT,
            new String[] { DBSchema.REPORT_ID, DBSchema.REPORT_CREATOR_ID, DBSchema.REPORT_LOCATION_ID,
                    //                        DBSchema.REPORT_SUBJECT_ID,
                    DBSchema.REPORT_FLOWCHART_ID, DBSchema.REPORT_NOTE, DBSchema.REPORT_DATE_FILED,
                    DBSchema.REPORT_NAME, DBSchema.REPORT_STATUS },
            DBSchema.MODIFIED + "=?", new String[] { DBSchema.MODIFIED_YES }, null, null, null, null);
    if (cursor.moveToFirst()) {
        if ((cursor != null) && (cursor.getCount() > 0))
            for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
                JSONObject map = new JSONObject();
                try {
                    if (!cursor.isNull(0))
                        map.put(DBSchema.REPORT_ID, cursor.getString(0));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                try {
                    if (!cursor.isNull(1))
                        map.put(DBSchema.REPORT_CREATOR_ID, cursor.getString(1));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                try {
                    if (!cursor.isNull(2))
                        map.put(DBSchema.REPORT_LOCATION_ID, cursor.getString(2));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                //                    try {
                //                        if (!cursor.isNull(3))
                //                            map.put(DBSchema.REPORT_SUBJECT_ID, cursor.getString(3));
                //                    } catch (JSONException e) {
                //                        e.printStackTrace();
                //                    }
                try {
                    if (!cursor.isNull(3))
                        map.put(DBSchema.REPORT_FLOWCHART_ID, cursor.getString(3));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                try {
                    if (!cursor.isNull(4))
                        map.put(DBSchema.REPORT_NOTE, cursor.getString(4));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                try {
                    if (!cursor.isNull(5))
                        map.put(DBSchema.REPORT_DATE_FILED, cursor.getString(5));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                try {
                    if (!cursor.isNull(6))
                        map.put(DBSchema.REPORT_NAME, cursor.getString(6));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                try {
                    if (!cursor.isNull(7))
                        map.put(DBSchema.REPORT_STATUS, cursor.getString(7));
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                data.put(map);
            }
    }
    db.close();
    cursor.close();
    return data;

}

From source file:com.rener.sea.DBHelper.java

private void setSequence(long seq) {
    //        deleteDB();
    getDummy();/*from  www.  ja v a2  s .  c o m*/
    SQLiteDatabase db = getWritableDatabase();
    Log.i(this.toString(), "SQLITE_SEQUENCE = " + seq);

    Log.i(this.toString(), "SQLITE_SEQUENCE = " + seq);
    //        db.execSQL("DELETE FROM sqlite_sequence WHERE 1 = 1");
    db.execSQL("INSERT OR REPLACE INTO sqlite_sequence(seq,name) VALUES(" + seq + ",'" + DBSchema.TABLE_ADDRESS
            + "')");
    db.execSQL("INSERT OR REPLACE INTO sqlite_sequence(seq,name) VALUES(" + seq + ",'"
            + DBSchema.TABLE_APPOINTMENTS + "');");
    db.execSQL("INSERT OR REPLACE INTO sqlite_sequence(seq,name) VALUES(" + seq + ",'" + DBSchema.TABLE_CATEGORY
            + "')");
    db.execSQL("INSERT OR REPLACE INTO sqlite_sequence(seq,name) VALUES(" + seq + ",'"
            + DBSchema.TABLE_FLOWCHART + "')");
    db.execSQL("INSERT OR REPLACE INTO sqlite_sequence(seq,name) VALUES(" + seq + ",'" + DBSchema.TABLE_ITEM
            + "')");
    db.execSQL("INSERT OR REPLACE INTO sqlite_sequence(seq,name) VALUES(" + seq + ",'" + DBSchema.TABLE_LOCATION
            + "')");
    db.execSQL("INSERT OR REPLACE INTO sqlite_sequence(seq,name) VALUES(" + seq + ",'" + DBSchema.TABLE_OPTION
            + "')");
    db.execSQL("INSERT OR REPLACE INTO sqlite_sequence(seq,name) VALUES(" + seq + ",'" + DBSchema.TABLE_PERSON
            + "')");
    db.execSQL("INSERT OR REPLACE INTO sqlite_sequence(seq,name) VALUES(" + seq + ",'" + DBSchema.TABLE_REPORT
            + "');");
    db.execSQL("INSERT OR REPLACE INTO sqlite_sequence(seq,name) VALUES(" + seq + ",'" + DBSchema.TABLE_PATH
            + "')");
    db.execSQL("INSERT OR REPLACE INTO sqlite_sequence(seq,name) VALUES(" + seq + ",'"
            + DBSchema.TABLE_SPECIALIZATION + "')");
    db.execSQL("INSERT OR REPLACE INTO sqlite_sequence(seq,name) VALUES(" + seq + ",'" + DBSchema.TABLE_USERS
            + "')");

    ////        db.execSQL("UPDATE OR REPLACE sqlite_sequence SET seq = "+seq+" WHERE name = '"+DBSchema.TABLE_ADDRESS+"'");
    //        db.execSQL("UPDATE OR REPLACE SQLITE_SEQUENCE SET seq = "+seq+" WHERE name = '"+DBSchema.TABLE_APPOINTMENTS+"'");
    ////        db.execSQL("UPDATE OR REPLACE sqlite_sequence SET seq = "+seq+" WHERE name = '"+DBSchema.TABLE_CATEGORY+"'");
    ////        db.execSQL("UPDATE OR REPLACE sqlite_sequence SET seq = "+seq+" WHERE name = '"+DBSchema.TABLE_FLOWCHART+"'");
    ////        db.execSQL("UPDATE OR REPLACE sqlite_sequence SET seq = "+seq+" WHERE name = '"+DBSchema.TABLE_ITEM+"'");
    ////        db.execSQL("UPDATE OR REPLACE sqlite_sequence SET seq = "+seq+" WHERE name = '"+DBSchema.TABLE_LOCATION+"'");
    ////        db.execSQL("UPDATE OR REPLACE sqlite_sequence SET seq = "+seq+" WHERE name = '"+DBSchema.TABLE_OPTION+"'");
    ////        db.execSQL("UPDATE OR REPLACE sqlite_sequence SET seq = "+seq+" WHERE name = '"+DBSchema.TABLE_PERSON+"'");
    //        db.execSQL("UPDATE OR REPLACE SQLITE_SEQUENCE SET seq = "+seq+" WHERE name = '"+DBSchema.TABLE_REPORT+"'");
    ////        db.execSQL("UPDATE OR REPLACE sqlite_sequence SET seq = "+seq+" WHERE name = '"+DBSchema.TABLE_PATH+"'");
    ////        db.execSQL("UPDATE OR REPLACE sqlite_sequence SET seq = "+seq+" WHERE name = '"+DBSchema.TABLE_SPECIALIZATION+"'");
    ////        db.execSQL("UPDATE OR REPLACE sqlite_sequence SET seq = "+seq+" WHERE name = '"+DBSchema.TABLE_USERS+"'");

    db.close();
}

From source file:com.onesignal.GenerateNotification.java

static void createSummaryNotification(Context inContext, boolean updateSummary, JSONObject gcmBundle) {
    if (updateSummary)
        setStatics(inContext);/*from ww w  .  j  a v  a2 s .c  o  m*/

    String group = null;
    try {
        group = gcmBundle.getString("grp");
    } catch (Throwable t) {
    }

    Random random = new Random();
    PendingIntent summaryDeleteIntent = getNewActionPendingIntent(random.nextInt(),
            getNewBaseDeleteIntent(0).putExtra("summary", group));

    OneSignalDbHelper dbHelper = new OneSignalDbHelper(currentContext);
    SQLiteDatabase writableDb = dbHelper.getWritableDatabase();

    String[] retColumn = { NotificationTable.COLUMN_NAME_ANDROID_NOTIFICATION_ID,
            NotificationTable.COLUMN_NAME_FULL_DATA, NotificationTable.COLUMN_NAME_IS_SUMMARY,
            NotificationTable.COLUMN_NAME_TITLE, NotificationTable.COLUMN_NAME_MESSAGE };

    String[] whereArgs = { group };

    Cursor cursor = writableDb.query(NotificationTable.TABLE_NAME, retColumn,
            NotificationTable.COLUMN_NAME_GROUP_ID + " = ? AND " + // Where String
                    NotificationTable.COLUMN_NAME_DISMISSED + " = 0 AND " + NotificationTable.COLUMN_NAME_OPENED
                    + " = 0",
            whereArgs, null, // group by
            null, // filter by row groups
            NotificationTable._ID + " DESC" // sort order, new to old
    );

    Notification summaryNotification;
    int summaryNotificationId = random.nextInt();

    String firstFullData = null;
    Collection<SpannableString> summeryList = null;

    if (cursor.moveToFirst()) {
        SpannableString spannableString;
        summeryList = new ArrayList<SpannableString>();

        do {
            if (cursor.getInt(cursor.getColumnIndex(NotificationTable.COLUMN_NAME_IS_SUMMARY)) == 1)
                summaryNotificationId = cursor
                        .getInt(cursor.getColumnIndex(NotificationTable.COLUMN_NAME_ANDROID_NOTIFICATION_ID));
            else {
                String title = cursor.getString(cursor.getColumnIndex(NotificationTable.COLUMN_NAME_TITLE));
                if (title == null)
                    title = "";
                else
                    title += " ";

                // Html.fromHtml("<strong>" + line1Title + "</strong> " + gcmBundle.getString("alert"));

                String msg = cursor.getString(cursor.getColumnIndex(NotificationTable.COLUMN_NAME_MESSAGE));
                spannableString = new SpannableString(title + msg);
                if (title.length() > 0)
                    spannableString.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 0, title.length(),
                            0);
                summeryList.add(spannableString);

                if (firstFullData == null)
                    firstFullData = cursor
                            .getString(cursor.getColumnIndex(NotificationTable.COLUMN_NAME_FULL_DATA));
            }
        } while (cursor.moveToNext());

        if (updateSummary) {
            try {
                gcmBundle = new JSONObject(firstFullData);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    if (summeryList != null && (!updateSummary || summeryList.size() > 1)) {
        int notificationCount = summeryList.size() + (updateSummary ? 0 : 1);

        String summaryMessage = null;

        if (gcmBundle.has("grp_msg")) {
            try {
                summaryMessage = gcmBundle.getString("grp_msg").replace("$[notif_count]",
                        "" + notificationCount);
            } catch (Throwable t) {
            }
        }
        if (summaryMessage == null)
            summaryMessage = notificationCount + " new messages";

        JSONObject summaryDataBundle = new JSONObject();
        try {
            summaryDataBundle.put("alert", summaryMessage);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Intent summaryIntent = getNewBaseIntent(summaryNotificationId).putExtra("summary", group)
                .putExtra("onesignal_data", summaryDataBundle.toString());

        PendingIntent summaryContentIntent = getNewActionPendingIntent(random.nextInt(), summaryIntent);

        NotificationCompat.Builder summeryBuilder = getBaseNotificationCompatBuilder(gcmBundle, !updateSummary);

        summeryBuilder.setContentIntent(summaryContentIntent).setDeleteIntent(summaryDeleteIntent)
                .setContentTitle(currentContext.getPackageManager()
                        .getApplicationLabel(currentContext.getApplicationInfo()))
                .setContentText(summaryMessage).setNumber(notificationCount).setOnlyAlertOnce(updateSummary)
                .setGroup(group).setGroupSummary(true);

        if (!updateSummary)
            summeryBuilder.setTicker(summaryMessage);

        NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
        String line1Title = null;

        // Add the latest notification to the summary
        if (!updateSummary) {
            try {
                line1Title = gcmBundle.getString("title");
            } catch (Throwable t) {
            }

            if (line1Title == null)
                line1Title = "";
            else
                line1Title += " ";

            String message = "";
            try {
                message = gcmBundle.getString("alert");
            } catch (Throwable t) {
            }

            SpannableString spannableString = new SpannableString(line1Title + message);
            if (line1Title.length() > 0)
                spannableString.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 0, line1Title.length(),
                        0);
            inboxStyle.addLine(spannableString);
        }

        for (SpannableString line : summeryList)
            inboxStyle.addLine(line);
        inboxStyle.setBigContentTitle(summaryMessage);
        summeryBuilder.setStyle(inboxStyle);

        summaryNotification = summeryBuilder.build();
    } else {
        // There currently isn't a visible notification from this group, save the group summary notification id and post it so it looks like a normal notification.
        ContentValues values = new ContentValues();
        values.put(NotificationTable.COLUMN_NAME_ANDROID_NOTIFICATION_ID, summaryNotificationId);
        values.put(NotificationTable.COLUMN_NAME_GROUP_ID, group);
        values.put(NotificationTable.COLUMN_NAME_IS_SUMMARY, 1);

        writableDb.insert(NotificationTable.TABLE_NAME, null, values);

        NotificationCompat.Builder notifBuilder = getBaseNotificationCompatBuilder(gcmBundle, !updateSummary);

        PendingIntent summaryContentIntent = getNewActionPendingIntent(random.nextInt(),
                getNewBaseIntent(summaryNotificationId).putExtra("onesignal_data", gcmBundle.toString())
                        .putExtra("summary", group));

        addNotificationActionButtons(gcmBundle, notifBuilder, summaryNotificationId, group);
        notifBuilder.setContentIntent(summaryContentIntent).setDeleteIntent(summaryDeleteIntent)
                .setOnlyAlertOnce(updateSummary).setGroup(group).setGroupSummary(true);

        summaryNotification = notifBuilder.build();
    }

    NotificationManagerCompat.from(currentContext).notify(summaryNotificationId, summaryNotification);

    cursor.close();
    writableDb.close();
}

From source file:org.opendatakit.sync.ProcessRowDataChanges.java

private int processRowOutcomes(TableDefinitionEntry te, TableResource resource, TableResult tableResult,
        ArrayList<ColumnDefinition> orderedColumns, ArrayList<ColumnDefinition> fileAttachmentColumns,
        boolean hasAttachments, List<SyncRowPending> rowsToPushFileAttachments, int countSoFar,
        int totalOutcomesSize, List<SyncRow> segmentAlter, ArrayList<RowOutcome> outcomes,
        ArrayList<RowOutcome> specialCases) {

    ArrayList<SyncRowDataChanges> rowsToMoveToInConflictLocally = new ArrayList<SyncRowDataChanges>();

    // For speed, do this all within a transaction. Processing is
    // all in-memory except when we are deleting a client row. In that
    // case, there may be SDCard access to delete the attachments for
    // the client row. But that is local access, and the commit will
    // be accessing the same device.
    ////w  w w  .j  a  v  a2 s .c o  m
    // i.e., no network access in this code, so we can place it all within
    // a transaction and not lock up the database for very long.
    //

    SQLiteDatabase db = null;

    try {
        db = sc.getDatabase();
        db.beginTransaction();

        for (int i = 0; i < segmentAlter.size(); ++i) {
            RowOutcome r = outcomes.get(i);
            SyncRow syncRow = segmentAlter.get(i);
            if (!r.getRowId().equals(syncRow.getRowId())) {
                throw new IllegalStateException("Unexpected reordering of return");
            }
            if (r.getOutcome() == OutcomeType.SUCCESS) {

                if (r.isDeleted()) {
                    // DELETE
                    // move the local record into the 'new_row' sync state
                    // so it can be physically deleted.
                    ODKDatabaseUtils.get().updateRowETagAndSyncState(db, resource.getTableId(), r.getRowId(),
                            null, SyncState.new_row);
                    // !!Important!! update the rowETag in our copy of this row.
                    syncRow.setRowETag(r.getRowETag());
                    // and physically delete row and attachments from database.
                    ODKDatabaseUtils.get().deleteDataInExistingDBTableWithId(db, sc.getAppName(),
                            resource.getTableId(), r.getRowId());
                    tableResult.incServerDeletes();
                } else {
                    ODKDatabaseUtils.get().updateRowETagAndSyncState(db, resource.getTableId(), r.getRowId(),
                            r.getRowETag(),
                            (hasAttachments && !syncRow.getUriFragments().isEmpty())
                                    ? SyncState.synced_pending_files
                                    : SyncState.synced);
                    // !!Important!! update the rowETag in our copy of this row.
                    syncRow.setRowETag(r.getRowETag());
                    if (hasAttachments && !syncRow.getUriFragments().isEmpty()) {
                        rowsToPushFileAttachments.add(new SyncRowPending(syncRow, false, true, true));
                    }
                    // UPDATE or INSERT
                    tableResult.incServerUpserts();
                }
            } else if (r.getOutcome() == OutcomeType.FAILED) {
                if (r.getRowId() == null || !r.isDeleted()) {
                    // should never occur!!!
                    throw new IllegalStateException(
                            "Unexpected null rowId or OutcomeType.FAILED when not deleting row");
                } else {
                    // special case of a delete where server has no record of the row.
                    // server should add row and mark it as deleted.
                }
            } else if (r.getOutcome() == OutcomeType.IN_CONFLICT) {
                // another device updated this record between the time we fetched
                // changes
                // and the time we tried to update this record. Transition the record
                // locally into the conflicting state.
                // SyncState.deleted and server is not deleting
                // SyncState.new_row and record exists on server
                // SyncState.changed and new change on server
                // SyncState.in_conflict and new change on server

                // no need to worry about server in_conflict records.
                // any server in_conflict rows will be cleaned up during the
                // update of the in_conflict state.
                Integer localRowConflictType = syncRow.isDeleted() ? ConflictType.LOCAL_DELETED_OLD_VALUES
                        : ConflictType.LOCAL_UPDATED_UPDATED_VALUES;

                Integer serverRowConflictType = r.isDeleted() ? ConflictType.SERVER_DELETED_OLD_VALUES
                        : ConflictType.SERVER_UPDATED_UPDATED_VALUES;

                // figure out what the localRow conflict type sh
                SyncRow serverRow = new SyncRow(r.getRowId(), r.getRowETag(), r.isDeleted(), r.getFormId(),
                        r.getLocale(), r.getSavepointType(), r.getSavepointTimestamp(), r.getSavepointCreator(),
                        r.getFilterScope(), r.getValues(), fileAttachmentColumns);
                SyncRowDataChanges conflictRow = new SyncRowDataChanges(serverRow, syncRow, false,
                        localRowConflictType);

                rowsToMoveToInConflictLocally.add(conflictRow);
                // we transition all of these later, outside this processing loop...
            } else if (r.getOutcome() == OutcomeType.DENIED) {
                // user does not have privileges...
                specialCases.add(r);
            } else {
                // a new OutcomeType state was added!
                throw new IllegalStateException("Unexpected OutcomeType! " + r.getOutcome().name());
            }

            ++countSoFar;
            ++rowsProcessed;
            if (rowsProcessed % ROWS_BETWEEN_PROGRESS_UPDATES == 0) {
                sc.updateNotification(SyncProgressState.ROWS, R.string.altering_server_row,
                        new Object[] { resource.getTableId(), countSoFar, totalOutcomesSize },
                        10.0 + rowsProcessed * perRowIncrement, false);
            }
        }

        // process the conflict rows, if any
        conflictRowsInDb(db, resource, orderedColumns, rowsToMoveToInConflictLocally, rowsToPushFileAttachments,
                hasAttachments, tableResult);

        // and allow this to happen
        db.setTransactionSuccessful();
    } finally {
        if (db != null) {
            db.endTransaction();
            db.close();
            db = null;
        }
    }

    return countSoFar;
}

From source file:biz.shadowservices.DegreesToolbox.DataFetcher.java

public FetchResult updateData(Context context, boolean force) {
    //Open database
    DBOpenHelper dbhelper = new DBOpenHelper(context);
    SQLiteDatabase db = dbhelper.getWritableDatabase();

    // check for internet connectivity
    try {/*from  w  w w.j ava 2  s. c o m*/
        if (!isOnline(context)) {
            Log.d(TAG, "We do not seem to be online. Skipping Update.");
            return FetchResult.NOTONLINE;
        }
    } catch (Exception e) {
        exceptionReporter.reportException(Thread.currentThread(), e, "Exception during isOnline()");
    }
    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
    if (!force) {
        try {
            if (sp.getBoolean("loginFailed", false) == true) {
                Log.d(TAG, "Previous login failed. Skipping Update.");
                DBLog.insertMessage(context, "i", TAG, "Previous login failed. Skipping Update.");
                return FetchResult.LOGINFAILED;
            }
            if (sp.getBoolean("autoupdates", true) == false) {
                Log.d(TAG, "Automatic updates not enabled. Skipping Update.");
                DBLog.insertMessage(context, "i", TAG, "Automatic updates not enabled. Skipping Update.");
                return FetchResult.NOTALLOWED;
            }
            if (!isBackgroundDataEnabled(context) && sp.getBoolean("obeyBackgroundData", true)) {
                Log.d(TAG, "Background data not enabled. Skipping Update.");
                DBLog.insertMessage(context, "i", TAG, "Background data not enabled. Skipping Update.");
                return FetchResult.NOTALLOWED;
            }
            if (!isAutoSyncEnabled() && sp.getBoolean("obeyAutoSync", true)
                    && sp.getBoolean("obeyBackgroundData", true)) {
                Log.d(TAG, "Auto sync not enabled. Skipping Update.");
                DBLog.insertMessage(context, "i", TAG, "Auto sync not enabled. Skipping Update.");
                return FetchResult.NOTALLOWED;
            }
            if (isWifi(context) && !sp.getBoolean("wifiUpdates", true)) {
                Log.d(TAG, "On wifi, and wifi auto updates not allowed. Skipping Update");
                DBLog.insertMessage(context, "i", TAG,
                        "On wifi, and wifi auto updates not allowed. Skipping Update");
                return FetchResult.NOTALLOWED;
            } else if (!isWifi(context)) {
                Log.d(TAG, "We are not on wifi.");
                if (!isRoaming(context) && !sp.getBoolean("2DData", true)) {
                    Log.d(TAG, "Automatic updates on 2Degrees data not enabled. Skipping Update.");
                    DBLog.insertMessage(context, "i", TAG,
                            "Automatic updates on 2Degrees data not enabled. Skipping Update.");
                    return FetchResult.NOTALLOWED;
                } else if (isRoaming(context) && !sp.getBoolean("roamingData", false)) {
                    Log.d(TAG, "Automatic updates on roaming mobile data not enabled. Skipping Update.");
                    DBLog.insertMessage(context, "i", TAG,
                            "Automatic updates on roaming mobile data not enabled. Skipping Update.");
                    return FetchResult.NOTALLOWED;
                }

            }
        } catch (Exception e) {
            exceptionReporter.reportException(Thread.currentThread(), e,
                    "Exception while finding if to update.");
        }

    } else {
        Log.d(TAG, "Update Forced");
    }

    try {
        String username = sp.getString("username", null);
        String password = sp.getString("password", null);
        if (username == null || password == null) {
            DBLog.insertMessage(context, "i", TAG, "Username or password not set.");
            return FetchResult.USERNAMEPASSWORDNOTSET;
        }

        // Find the URL of the page to send login data to.
        Log.d(TAG, "Finding Action. ");
        HttpGetter loginPageGet = new HttpGetter("https://secure.2degreesmobile.co.nz/web/ip/login");
        String loginPageString = loginPageGet.execute();
        if (loginPageString != null) {
            Document loginPage = Jsoup.parse(loginPageString,
                    "https://secure.2degreesmobile.co.nz/web/ip/login");
            Element loginForm = loginPage.getElementsByAttributeValue("name", "loginFrm").first();
            String loginAction = loginForm.attr("action");
            // Send login form
            List<NameValuePair> loginValues = new ArrayList<NameValuePair>();
            loginValues.add(new BasicNameValuePair("externalURLRedirect", ""));
            loginValues.add(new BasicNameValuePair("hdnAction", "login_userlogin"));
            loginValues.add(new BasicNameValuePair("hdnAuthenticationType", "M"));
            loginValues.add(new BasicNameValuePair("hdnlocale", ""));

            loginValues.add(new BasicNameValuePair("userid", username));
            loginValues.add(new BasicNameValuePair("password", password));
            Log.d(TAG, "Sending Login ");
            HttpPoster sendLoginPoster = new HttpPoster(loginAction, loginValues);
            // Parse result

            String loginResponse = sendLoginPoster.execute();
            Document loginResponseParsed = Jsoup.parse(loginResponse);
            // Determine if this is a pre-pay or post-paid account.
            boolean postPaid;
            if (loginResponseParsed
                    .getElementById("p_CustomerPortalPostPaidHomePage_WAR_customerportalhomepage") == null) {
                Log.d(TAG, "Pre-pay account or no account.");
                postPaid = false;
            } else {
                Log.d(TAG, "Post-paid account.");
                postPaid = true;
            }

            String homepageUrl = "https://secure.2degreesmobile.co.nz/group/ip/home";
            if (postPaid) {
                homepageUrl = "https://secure.2degreesmobile.co.nz/group/ip/postpaid";
            }
            HttpGetter homepageGetter = new HttpGetter(homepageUrl);
            String homepageHTML = homepageGetter.execute();
            Document homePage = Jsoup.parse(homepageHTML);

            Element accountSummary = homePage.getElementById("accountSummary");
            if (accountSummary == null) {
                Log.d(TAG, "Login failed.");
                return FetchResult.LOGINFAILED;
            }
            db.delete("cache", "", null);
            /* This code fetched some extra details for postpaid users, but on reflection they aren't that useful.
             * Might reconsider this.
             *
             if (postPaid) {
                     
               Element accountBalanceSummaryTable = accountSummary.getElementsByClass("tableBillSummary").first();
               Elements rows = accountBalanceSummaryTable.getElementsByTag("tr");
               int rowno = 0;
               for (Element row : rows) {
                  if (rowno > 1) {
             break;
                  }
                  //Log.d(TAG, "Starting row");
                  //Log.d(TAG, row.html());
                  Double value;
                  try {
             Element amount = row.getElementsByClass("tableBillamount").first();
             String amountHTML = amount.html();
             Log.d(TAG, amountHTML.substring(1));
             value = Double.parseDouble(amountHTML.substring(1));
                  } catch (Exception e) {
             Log.d(TAG, "Failed to parse amount from row.");
             value = null;
                  }
                  String expiresDetails = "";
                  String expiresDate = null;
                  String name = null;
                  try {
             Element details = row.getElementsByClass("tableBilldetail").first();
             name = details.ownText();
             Element expires = details.getElementsByTag("em").first();
             if (expires != null) {
                 expiresDetails = expires.text();
             } 
             Log.d(TAG, expiresDetails);
             Pattern pattern;
             pattern = Pattern.compile("\\(payment is due (.*)\\)");
             Matcher matcher = pattern.matcher(expiresDetails);
             if (matcher.find()) {
                /*Log.d(TAG, "matched expires");
                Log.d(TAG, "group 0:" + matcher.group(0));
                Log.d(TAG, "group 1:" + matcher.group(1));
                Log.d(TAG, "group 2:" + matcher.group(2)); *
                String expiresDateString = matcher.group(1);
                Date expiresDateObj;
                if (expiresDateString != null) {
                   if (expiresDateString.length() > 0) {
                      try {
                         expiresDateObj = DateFormatters.EXPIRESDATE.parse(expiresDateString);
                         expiresDate = DateFormatters.ISO8601DATEONLYFORMAT.format(expiresDateObj);
                      } catch (java.text.ParseException e) {
                         Log.d(TAG, "Could not parse date: " + expiresDateString);
                      }
                   }   
                }
             }
                  } catch (Exception e) {
             Log.d(TAG, "Failed to parse details from row.");
                  }
                  String expirev = null;
                  ContentValues values = new ContentValues();
                  values.put("name", name);
                  values.put("value", value);
                  values.put("units", "$NZ");
                  values.put("expires_value", expirev );
                  values.put("expires_date", expiresDate);
                  db.insert("cache", "value", values );
                  rowno++;
               }
            } */
            Element accountSummaryTable = accountSummary.getElementsByClass("tableAccountSummary").first();
            Elements rows = accountSummaryTable.getElementsByTag("tr");
            for (Element row : rows) {
                // We are now looking at each of the rows in the data table.
                //Log.d(TAG, "Starting row");
                //Log.d(TAG, row.html());
                Double value;
                String units;
                try {
                    Element amount = row.getElementsByClass("tableBillamount").first();
                    String amountHTML = amount.html();
                    //Log.d(TAG, amountHTML);
                    String[] amountParts = amountHTML.split("&nbsp;", 2);
                    //Log.d(TAG, amountParts[0]);
                    //Log.d(TAG, amountParts[1]);
                    if (amountParts[0].contains("Included") || amountParts[0].equals("All You Need")
                            || amountParts[0].equals("Unlimited Text*")) {
                        value = Values.INCLUDED;
                    } else {
                        try {
                            value = Double.parseDouble(amountParts[0]);
                        } catch (NumberFormatException e) {
                            exceptionReporter.reportException(Thread.currentThread(), e, "Decoding value.");
                            value = 0.0;
                        }
                    }
                    units = amountParts[1];
                } catch (NullPointerException e) {
                    //Log.d(TAG, "Failed to parse amount from row.");
                    value = null;
                    units = null;
                }
                Element details = row.getElementsByClass("tableBilldetail").first();
                String name = details.getElementsByTag("strong").first().text();
                Element expires = details.getElementsByTag("em").first();
                String expiresDetails = "";
                if (expires != null) {
                    expiresDetails = expires.text();
                }
                Log.d(TAG, expiresDetails);
                Pattern pattern;
                if (postPaid == false) {
                    pattern = Pattern.compile("\\(([\\d\\.]*) ?\\w*? ?expiring on (.*)\\)");
                } else {
                    pattern = Pattern.compile("\\(([\\d\\.]*) ?\\w*? ?will expire on (.*)\\)");
                }
                Matcher matcher = pattern.matcher(expiresDetails);
                Double expiresValue = null;
                String expiresDate = null;
                if (matcher.find()) {
                    /*Log.d(TAG, "matched expires");
                    Log.d(TAG, "group 0:" + matcher.group(0));
                    Log.d(TAG, "group 1:" + matcher.group(1));
                    Log.d(TAG, "group 2:" + matcher.group(2)); */
                    try {
                        expiresValue = Double.parseDouble(matcher.group(1));
                    } catch (NumberFormatException e) {
                        expiresValue = null;
                    }
                    String expiresDateString = matcher.group(2);
                    Date expiresDateObj;
                    if (expiresDateString != null) {
                        if (expiresDateString.length() > 0) {
                            try {
                                expiresDateObj = DateFormatters.EXPIRESDATE.parse(expiresDateString);
                                expiresDate = DateFormatters.ISO8601DATEONLYFORMAT.format(expiresDateObj);
                            } catch (java.text.ParseException e) {
                                Log.d(TAG, "Could not parse date: " + expiresDateString);
                            }
                        }
                    }
                }
                ContentValues values = new ContentValues();
                values.put("name", name);
                values.put("value", value);
                values.put("units", units);
                values.put("expires_value", expiresValue);
                values.put("expires_date", expiresDate);
                db.insert("cache", "value", values);
            }

            if (postPaid == false) {
                Log.d(TAG, "Getting Value packs...");
                // Find value packs
                HttpGetter valuePacksPageGet = new HttpGetter(
                        "https://secure.2degreesmobile.co.nz/group/ip/prevaluepack");
                String valuePacksPageString = valuePacksPageGet.execute();
                //DBLog.insertMessage(context, "d", "",  valuePacksPageString);
                if (valuePacksPageString != null) {
                    Document valuePacksPage = Jsoup.parse(valuePacksPageString);
                    Elements enabledPacks = valuePacksPage.getElementsByClass("yellow");
                    for (Element enabledPack : enabledPacks) {
                        Element offerNameElemt = enabledPack
                                .getElementsByAttributeValueStarting("name", "offername").first();
                        if (offerNameElemt != null) {
                            String offerName = offerNameElemt.val();
                            DBLog.insertMessage(context, "d", "", "Got element: " + offerName);
                            ValuePack[] packs = Values.valuePacks.get(offerName);
                            if (packs == null) {
                                DBLog.insertMessage(context, "d", "",
                                        "Offer name: " + offerName + " not matched.");
                            } else {
                                for (ValuePack pack : packs) {
                                    ContentValues values = new ContentValues();
                                    values.put("plan_startamount", pack.value);
                                    values.put("plan_name", offerName);
                                    DBLog.insertMessage(context, "d", "",
                                            "Pack " + pack.type.id + " start value set to " + pack.value);
                                    db.update("cache", values, "name = '" + pack.type.id + "'", null);
                                }
                            }
                        }
                    }
                }
            }

            SharedPreferences.Editor prefedit = sp.edit();
            Date now = new Date();
            prefedit.putString("updateDate", DateFormatters.ISO8601FORMAT.format(now));
            prefedit.putBoolean("loginFailed", false);
            prefedit.putBoolean("networkError", false);
            prefedit.commit();
            DBLog.insertMessage(context, "i", TAG, "Update Successful");
            return FetchResult.SUCCESS;

        }
    } catch (ClientProtocolException e) {
        DBLog.insertMessage(context, "w", TAG, "Network error: " + e.getMessage());
        return FetchResult.NETWORKERROR;
    } catch (IOException e) {
        DBLog.insertMessage(context, "w", TAG, "Network error: " + e.getMessage());
        return FetchResult.NETWORKERROR;
    } finally {
        db.close();
    }
    return null;
}

From source file:org.opendatakit.survey.android.provider.SubmissionProvider.java

/**
 * The incoming URI is of the form:/*from  w  w w  . j a v a2  s.co  m*/
 * ..../appName/tableId/instanceId?formId=&formVersion=
 *
 * where instanceId is the DataTableColumns._ID
 */
@SuppressWarnings("unchecked")
@Override
public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
    final boolean asXml = uri.getAuthority().equalsIgnoreCase(XML_SUBMISSION_AUTHORITY);

    if (mode != null && !mode.equals("r")) {
        throw new IllegalArgumentException("Only read access is supported");
    }

    // URI == ..../appName/tableId/instanceId?formId=&formVersion=

    List<String> segments = uri.getPathSegments();

    if (segments.size() != 4) {
        throw new IllegalArgumentException("Unknown URI (incorrect number of path segments!) " + uri);
    }

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

    final String tableId = segments.get(1);
    final String instanceId = segments.get(2);
    final String submissionInstanceId = segments.get(3);

    SQLiteDatabase db = null;
    try {
        db = DatabaseFactory.get().getDatabase(getContext(), appName);

        boolean success = false;
        try {
            success = ODKDatabaseUtils.get().hasTableId(db, tableId);
        } catch (Exception e) {
            e.printStackTrace();
            throw new SQLException("Unknown URI (exception testing for tableId) " + uri);
        }
        if (!success) {
            throw new SQLException("Unknown URI (missing data table for tableId) " + uri);
        }

        final String dbTableName = "\"" + tableId + "\"";

        // Get the table properties specific to XML submissions

        String xmlInstanceName = null;
        String xmlRootElementName = null;
        String xmlDeviceIdPropertyName = null;
        String xmlUserIdPropertyName = null;
        String xmlBase64RsaPublicKey = null;

        try {

            Cursor c = null;
            try {
                c = db.query(DatabaseConstants.KEY_VALUE_STORE_ACTIVE_TABLE_NAME,
                        new String[] { KeyValueStoreColumns.KEY, KeyValueStoreColumns.VALUE },
                        KeyValueStoreColumns.TABLE_ID + "=? AND " + KeyValueStoreColumns.PARTITION + "=? AND "
                                + KeyValueStoreColumns.ASPECT + "=? AND " + KeyValueStoreColumns.KEY
                                + " IN (?,?,?,?,?)",
                        new String[] { tableId, KeyValueStoreConstants.PARTITION_TABLE,
                                KeyValueStoreConstants.ASPECT_DEFAULT, KeyValueStoreConstants.XML_INSTANCE_NAME,
                                KeyValueStoreConstants.XML_ROOT_ELEMENT_NAME,
                                KeyValueStoreConstants.XML_DEVICE_ID_PROPERTY_NAME,
                                KeyValueStoreConstants.XML_USER_ID_PROPERTY_NAME,
                                KeyValueStoreConstants.XML_BASE64_RSA_PUBLIC_KEY },
                        null, null, null);
                if (c.getCount() > 0) {
                    c.moveToFirst();
                    int idxKey = c.getColumnIndex(KeyValueStoreColumns.KEY);
                    int idxValue = c.getColumnIndex(KeyValueStoreColumns.VALUE);
                    do {
                        String key = c.getString(idxKey);
                        String value = c.getString(idxValue);
                        if (KeyValueStoreConstants.XML_INSTANCE_NAME.equals(key)) {
                            xmlInstanceName = value;
                        } else if (KeyValueStoreConstants.XML_ROOT_ELEMENT_NAME.equals(key)) {
                            xmlRootElementName = value;
                        } else if (KeyValueStoreConstants.XML_DEVICE_ID_PROPERTY_NAME.equals(key)) {
                            xmlDeviceIdPropertyName = value;
                        } else if (KeyValueStoreConstants.XML_USER_ID_PROPERTY_NAME.equals(key)) {
                            xmlUserIdPropertyName = value;
                        } else if (KeyValueStoreConstants.XML_BASE64_RSA_PUBLIC_KEY.equals(key)) {
                            xmlBase64RsaPublicKey = value;
                        }
                    } while (c.moveToNext());
                }
            } finally {
                c.close();
                c = null;
            }

            ArrayList<ColumnDefinition> orderedDefns = TableUtil.get().getColumnDefinitions(db, appName,
                    tableId);

            // Retrieve the values of the record to be emitted...

            HashMap<String, Object> values = new HashMap<String, Object>();

            // issue query to retrieve the most recent non-checkpoint data record
            // for the instanceId
            StringBuilder b = new StringBuilder();
            b.append("SELECT * FROM ").append(dbTableName).append(" as T WHERE ").append(DataTableColumns.ID)
                    .append("=?").append(" AND ").append(DataTableColumns.SAVEPOINT_TYPE)
                    .append(" IS NOT NULL AND ").append(DataTableColumns.SAVEPOINT_TIMESTAMP)
                    .append("=(SELECT max(V.").append(DataTableColumns.SAVEPOINT_TIMESTAMP).append(") FROM ")
                    .append(dbTableName).append(" as V WHERE V.").append(DataTableColumns.ID).append("=T.")
                    .append(DataTableColumns.ID).append(" AND V.").append(DataTableColumns.SAVEPOINT_TYPE)
                    .append(" IS NOT NULL").append(")");

            String[] selectionArgs = new String[] { instanceId };
            FileSet freturn = new FileSet(appName);

            String datestamp = null;

            try {
                c = db.rawQuery(b.toString(), selectionArgs);
                b.setLength(0);

                if (c.moveToFirst() && c.getCount() == 1) {
                    String rowETag = null;
                    String filterType = null;
                    String filterValue = null;
                    String formId = null;
                    String locale = null;
                    String savepointType = null;
                    String savepointCreator = null;
                    String savepointTimestamp = null;
                    String instanceName = null;

                    // OK. we have the record -- work through all the terms
                    for (int i = 0; i < c.getColumnCount(); ++i) {
                        ColumnDefinition defn = null;
                        String columnName = c.getColumnName(i);
                        try {
                            defn = ColumnDefinition.find(orderedDefns, columnName);
                        } catch (IllegalArgumentException e) {
                            // ignore...
                        }
                        if (defn != null && !c.isNull(i)) {
                            if (xmlInstanceName != null && defn.getElementName().equals(xmlInstanceName)) {
                                instanceName = ODKDatabaseUtils.get().getIndexAsString(c, i);
                            }
                            // user-defined column
                            ElementType type = defn.getType();
                            ElementDataType dataType = type.getDataType();

                            log.i(t, "element type: " + defn.getElementType());
                            if (dataType == ElementDataType.integer) {
                                Integer value = ODKDatabaseUtils.get().getIndexAsType(c, Integer.class, i);
                                putElementValue(values, defn, value);
                            } else if (dataType == ElementDataType.number) {
                                Double value = ODKDatabaseUtils.get().getIndexAsType(c, Double.class, i);
                                putElementValue(values, defn, value);
                            } else if (dataType == ElementDataType.bool) {
                                Integer tmp = ODKDatabaseUtils.get().getIndexAsType(c, Integer.class, i);
                                Boolean value = tmp == null ? null : (tmp != 0);
                                putElementValue(values, defn, value);
                            } else if (type.getElementType().equals("date")) {
                                String value = ODKDatabaseUtils.get().getIndexAsString(c, i);
                                String jrDatestamp = (value == null) ? null
                                        : (new SimpleDateFormat(ISO8601_DATE_ONLY_FORMAT, Locale.ENGLISH))
                                                .format(new Date(TableConstants.milliSecondsFromNanos(value)));
                                putElementValue(values, defn, jrDatestamp);
                            } else if (type.getElementType().equals("dateTime")) {
                                String value = ODKDatabaseUtils.get().getIndexAsString(c, i);
                                String jrDatestamp = (value == null) ? null
                                        : (new SimpleDateFormat(ISO8601_DATE_FORMAT, Locale.ENGLISH))
                                                .format(new Date(TableConstants.milliSecondsFromNanos(value)));
                                putElementValue(values, defn, jrDatestamp);
                            } else if (type.getElementType().equals("time")) {
                                String value = ODKDatabaseUtils.get().getIndexAsString(c, i);
                                putElementValue(values, defn, value);
                            } else if (dataType == ElementDataType.array) {
                                ArrayList<Object> al = ODKDatabaseUtils.get().getIndexAsType(c, ArrayList.class,
                                        i);
                                putElementValue(values, defn, al);
                            } else if (dataType == ElementDataType.string) {
                                String value = ODKDatabaseUtils.get().getIndexAsString(c, i);
                                putElementValue(values, defn, value);
                            } else /* unrecognized */ {
                                throw new IllegalStateException(
                                        "unrecognized data type: " + defn.getElementType());
                            }

                        } else if (columnName.equals(DataTableColumns.SAVEPOINT_TIMESTAMP)) {
                            savepointTimestamp = ODKDatabaseUtils.get().getIndexAsString(c, i);
                        } else if (columnName.equals(DataTableColumns.ROW_ETAG)) {
                            rowETag = ODKDatabaseUtils.get().getIndexAsString(c, i);
                        } else if (columnName.equals(DataTableColumns.FILTER_TYPE)) {
                            filterType = ODKDatabaseUtils.get().getIndexAsString(c, i);
                        } else if (columnName.equals(DataTableColumns.FILTER_VALUE)) {
                            filterValue = ODKDatabaseUtils.get().getIndexAsString(c, i);
                        } else if (columnName.equals(DataTableColumns.FORM_ID)) {
                            formId = ODKDatabaseUtils.get().getIndexAsString(c, i);
                        } else if (columnName.equals(DataTableColumns.LOCALE)) {
                            locale = ODKDatabaseUtils.get().getIndexAsString(c, i);
                        } else if (columnName.equals(DataTableColumns.FORM_ID)) {
                            formId = ODKDatabaseUtils.get().getIndexAsString(c, i);
                        } else if (columnName.equals(DataTableColumns.SAVEPOINT_TYPE)) {
                            savepointType = ODKDatabaseUtils.get().getIndexAsString(c, i);
                        } else if (columnName.equals(DataTableColumns.SAVEPOINT_CREATOR)) {
                            savepointCreator = ODKDatabaseUtils.get().getIndexAsString(c, i);
                        }
                    }

                    // OK got all the values into the values map -- emit
                    // contents
                    b.setLength(0);
                    File submissionXml = new File(ODKFileUtils.getInstanceFolder(appName, tableId, instanceId),
                            (asXml ? "submission.xml" : "submission.json"));
                    File manifest = new File(ODKFileUtils.getInstanceFolder(appName, tableId, instanceId),
                            "manifest.json");
                    submissionXml.delete();
                    manifest.delete();
                    freturn.instanceFile = submissionXml;

                    if (asXml) {
                        // Pre-processing -- collapse all geopoints into a
                        // string-valued representation
                        for (ColumnDefinition defn : orderedDefns) {
                            ElementType type = defn.getType();
                            ElementDataType dataType = type.getDataType();
                            if (dataType == ElementDataType.object && (type.getElementType().equals("geopoint")
                                    || type.getElementType().equals("mimeUri"))) {
                                Map<String, Object> parent = null;
                                List<ColumnDefinition> parents = new ArrayList<ColumnDefinition>();
                                ColumnDefinition d = defn.getParent();
                                while (d != null) {
                                    parents.add(d);
                                    d = d.getParent();
                                }
                                parent = values;
                                for (int i = parents.size() - 1; i >= 0; --i) {
                                    Object o = parent.get(parents.get(i).getElementName());
                                    if (o == null) {
                                        parent = null;
                                        break;
                                    }
                                    parent = (Map<String, Object>) o;
                                }
                                if (parent != null) {
                                    Object o = parent.get(defn.getElementName());
                                    if (o != null) {
                                        if (type.getElementType().equals("geopoint")) {
                                            Map<String, Object> geopoint = (Map<String, Object>) o;
                                            // OK. we have geopoint -- get the
                                            // lat, long, alt, etc.
                                            Double latitude = (Double) geopoint.get("latitude");
                                            Double longitude = (Double) geopoint.get("longitude");
                                            Double altitude = (Double) geopoint.get("altitude");
                                            Double accuracy = (Double) geopoint.get("accuracy");
                                            String gpt = "" + latitude + " " + longitude + " " + altitude + " "
                                                    + accuracy;
                                            parent.put(defn.getElementName(), gpt);
                                        } else if (type.getElementType().equals("mimeUri")) {
                                            Map<String, Object> mimeuri = (Map<String, Object>) o;
                                            String uriFragment = (String) mimeuri.get("uriFragment");
                                            String contentType = (String) mimeuri.get("contentType");

                                            if (uriFragment != null) {
                                                File f = ODKFileUtils.getAsFile(appName, uriFragment);
                                                if (f.equals(manifest)) {
                                                    throw new IllegalStateException(
                                                            "Unexpected collision with manifest.json");
                                                }
                                                freturn.addAttachmentFile(f, contentType);
                                                parent.put(defn.getElementName(), f.getName());
                                            }
                                        } else {
                                            throw new IllegalStateException("Unhandled transform case");
                                        }
                                    }
                                }
                            }
                        }

                        datestamp = (new SimpleDateFormat(ISO8601_DATE_FORMAT, Locale.ENGLISH))
                                .format(new Date(TableConstants.milliSecondsFromNanos(savepointTimestamp)));

                        // For XML, we traverse the map to serialize it
                        Document d = new Document();
                        d.setStandalone(true);
                        d.setEncoding(CharEncoding.UTF_8);
                        Element e = d.createElement(XML_DEFAULT_NAMESPACE,
                                (xmlRootElementName == null) ? "data" : xmlRootElementName);
                        e.setPrefix("jr", XML_OPENROSA_NAMESPACE);
                        e.setPrefix("", XML_DEFAULT_NAMESPACE);
                        d.addChild(0, Node.ELEMENT, e);
                        e.setAttribute("", "id", tableId);
                        DynamicPropertiesCallback cb = new DynamicPropertiesCallback(getContext(), appName,
                                tableId, instanceId);

                        int idx = 0;
                        Element meta = d.createElement(XML_OPENROSA_NAMESPACE, "meta");

                        Element v = d.createElement(XML_OPENROSA_NAMESPACE, "instanceID");
                        v.addChild(0, Node.TEXT, submissionInstanceId);
                        meta.addChild(idx++, Node.ELEMENT, v);
                        meta.addChild(idx++, Node.IGNORABLE_WHITESPACE, NEW_LINE);

                        if (xmlDeviceIdPropertyName != null) {
                            String deviceId = propertyManager.getSingularProperty(xmlDeviceIdPropertyName, cb);
                            if (deviceId != null) {
                                v = d.createElement(XML_OPENROSA_NAMESPACE, "deviceID");
                                v.addChild(0, Node.TEXT, deviceId);
                                meta.addChild(idx++, Node.ELEMENT, v);
                                meta.addChild(idx++, Node.IGNORABLE_WHITESPACE, NEW_LINE);
                            }
                        }
                        if (xmlUserIdPropertyName != null) {
                            String userId = propertyManager.getSingularProperty(xmlUserIdPropertyName, cb);
                            if (userId != null) {
                                v = d.createElement(XML_OPENROSA_NAMESPACE, "userID");
                                v.addChild(0, Node.TEXT, userId);
                                meta.addChild(idx++, Node.ELEMENT, v);
                                meta.addChild(idx++, Node.IGNORABLE_WHITESPACE, NEW_LINE);
                            }
                        }
                        v = d.createElement(XML_OPENROSA_NAMESPACE, "timeEnd");
                        v.addChild(0, Node.TEXT, datestamp);
                        meta.addChild(idx++, Node.ELEMENT, v);
                        meta.addChild(idx++, Node.IGNORABLE_WHITESPACE, NEW_LINE);

                        // these are extra metadata tags...
                        if (instanceName != null) {
                            v = d.createElement(XML_DEFAULT_NAMESPACE, "instanceName");
                            v.addChild(0, Node.TEXT, instanceName);
                            meta.addChild(idx++, Node.ELEMENT, v);
                            meta.addChild(idx++, Node.IGNORABLE_WHITESPACE, NEW_LINE);
                        } else {
                            v = d.createElement(XML_DEFAULT_NAMESPACE, "instanceName");
                            v.addChild(0, Node.TEXT, savepointTimestamp);
                            meta.addChild(idx++, Node.ELEMENT, v);
                            meta.addChild(idx++, Node.IGNORABLE_WHITESPACE, NEW_LINE);
                        }

                        // these are extra metadata tags...
                        // rowID
                        v = d.createElement(XML_DEFAULT_NAMESPACE, "rowID");
                        v.addChild(0, Node.TEXT, instanceId);
                        meta.addChild(idx++, Node.ELEMENT, v);
                        meta.addChild(idx++, Node.IGNORABLE_WHITESPACE, NEW_LINE);

                        // rowETag
                        v = d.createElement(XML_DEFAULT_NAMESPACE, "rowETag");
                        if (rowETag != null) {
                            v.addChild(0, Node.TEXT, rowETag);
                        }
                        meta.addChild(idx++, Node.ELEMENT, v);
                        meta.addChild(idx++, Node.IGNORABLE_WHITESPACE, NEW_LINE);

                        // filterType
                        v = d.createElement(XML_DEFAULT_NAMESPACE, "filterType");
                        if (filterType != null) {
                            v.addChild(0, Node.TEXT, filterType);
                        }
                        meta.addChild(idx++, Node.ELEMENT, v);
                        meta.addChild(idx++, Node.IGNORABLE_WHITESPACE, NEW_LINE);

                        // filterValue
                        v = d.createElement(XML_DEFAULT_NAMESPACE, "filterValue");
                        if (filterValue != null) {
                            v.addChild(0, Node.TEXT, filterValue);
                        }
                        meta.addChild(idx++, Node.ELEMENT, v);
                        meta.addChild(idx++, Node.IGNORABLE_WHITESPACE, NEW_LINE);

                        // formID
                        v = d.createElement(XML_DEFAULT_NAMESPACE, "formID");
                        v.addChild(0, Node.TEXT, formId);
                        meta.addChild(idx++, Node.ELEMENT, v);
                        meta.addChild(idx++, Node.IGNORABLE_WHITESPACE, NEW_LINE);

                        // locale
                        v = d.createElement(XML_DEFAULT_NAMESPACE, "locale");
                        v.addChild(0, Node.TEXT, locale);
                        meta.addChild(idx++, Node.ELEMENT, v);
                        meta.addChild(idx++, Node.IGNORABLE_WHITESPACE, NEW_LINE);

                        // savepointType
                        v = d.createElement(XML_DEFAULT_NAMESPACE, "savepointType");
                        v.addChild(0, Node.TEXT, savepointType);
                        meta.addChild(idx++, Node.ELEMENT, v);
                        meta.addChild(idx++, Node.IGNORABLE_WHITESPACE, NEW_LINE);

                        // savepointCreator
                        v = d.createElement(XML_DEFAULT_NAMESPACE, "savepointCreator");
                        if (savepointCreator != null) {
                            v.addChild(0, Node.TEXT, savepointCreator);
                        }
                        meta.addChild(idx++, Node.ELEMENT, v);
                        meta.addChild(idx++, Node.IGNORABLE_WHITESPACE, NEW_LINE);

                        // savepointTimestamp
                        v = d.createElement(XML_DEFAULT_NAMESPACE, "savepointTimestamp");
                        v.addChild(0, Node.TEXT, savepointTimestamp);
                        meta.addChild(idx++, Node.ELEMENT, v);
                        meta.addChild(idx++, Node.IGNORABLE_WHITESPACE, NEW_LINE);

                        // and insert the meta block into the XML

                        e.addChild(0, Node.IGNORABLE_WHITESPACE, NEW_LINE);
                        e.addChild(1, Node.ELEMENT, meta);
                        e.addChild(2, Node.IGNORABLE_WHITESPACE, NEW_LINE);

                        idx = 3;
                        ArrayList<String> entryNames = new ArrayList<String>();
                        entryNames.addAll(values.keySet());
                        Collections.sort(entryNames);
                        for (String name : entryNames) {
                            idx = generateXmlHelper(d, e, idx, name, values, log);
                        }

                        KXmlSerializer serializer = new KXmlSerializer();

                        ByteArrayOutputStream bo = new ByteArrayOutputStream();
                        serializer.setOutput(bo, CharEncoding.UTF_8);
                        // setting the response content type emits the
                        // xml header.
                        // just write the body here...
                        d.writeChildren(serializer);
                        serializer.flush();
                        bo.close();

                        b.append(bo.toString(CharEncoding.UTF_8));

                        // OK we have the document in the builder (b).
                        String doc = b.toString();

                        freturn.instanceFile = submissionXml;

                        // see if the form is encrypted and we can
                        // encrypt it...
                        EncryptedFormInformation formInfo = EncryptionUtils.getEncryptedFormInformation(appName,
                                tableId, xmlBase64RsaPublicKey, instanceId);
                        if (formInfo != null) {
                            File submissionXmlEnc = new File(submissionXml.getParentFile(),
                                    submissionXml.getName() + ".enc");
                            submissionXmlEnc.delete();
                            // if we are encrypting, the form cannot be
                            // reopened afterward
                            // and encrypt the submission (this is a
                            // one-way operation)...
                            if (!EncryptionUtils.generateEncryptedSubmission(freturn, doc, submissionXml,
                                    submissionXmlEnc, formInfo)) {
                                return null;
                            }
                            // at this point, the freturn object has
                            // been re-written with the encrypted media
                            // and xml files.
                        } else {
                            exportFile(doc, submissionXml, log);
                        }

                    } else {
                        // Pre-processing -- collapse all mimeUri into filename
                        for (ColumnDefinition defn : orderedDefns) {
                            ElementType type = defn.getType();
                            ElementDataType dataType = type.getDataType();

                            if (dataType == ElementDataType.object && type.getElementType().equals("mimeUri")) {
                                Map<String, Object> parent = null;
                                List<ColumnDefinition> parents = new ArrayList<ColumnDefinition>();
                                ColumnDefinition d = defn.getParent();
                                while (d != null) {
                                    parents.add(d);
                                    d = d.getParent();
                                }
                                parent = values;
                                for (int i = parents.size() - 1; i >= 0; --i) {
                                    Object o = parent.get(parents.get(i).getElementName());
                                    if (o == null) {
                                        parent = null;
                                        break;
                                    }
                                    parent = (Map<String, Object>) o;
                                }
                                if (parent != null) {
                                    Object o = parent.get(defn.getElementName());
                                    if (o != null) {
                                        if (dataType == ElementDataType.object
                                                && type.getElementType().equals("mimeUri")) {
                                            Map<String, Object> mimeuri = (Map<String, Object>) o;
                                            String uriFragment = (String) mimeuri.get("uriFragment");
                                            String contentType = (String) mimeuri.get("contentType");
                                            File f = ODKFileUtils.getAsFile(appName, uriFragment);
                                            if (f.equals(manifest)) {
                                                throw new IllegalStateException(
                                                        "Unexpected collision with manifest.json");
                                            }
                                            freturn.addAttachmentFile(f, contentType);
                                            parent.put(defn.getElementName(), f.getName());
                                        } else {
                                            throw new IllegalStateException("Unhandled transform case");
                                        }
                                    }
                                }
                            }
                        }

                        // For JSON, we construct the model, then emit model +
                        // meta + data
                        HashMap<String, Object> wrapper = new HashMap<String, Object>();
                        wrapper.put("tableId", tableId);
                        wrapper.put("instanceId", instanceId);
                        HashMap<String, Object> formDef = new HashMap<String, Object>();
                        formDef.put("table_id", tableId);
                        formDef.put("model", ColumnDefinition.getDataModel(orderedDefns));
                        wrapper.put("formDef", formDef);
                        wrapper.put("data", values);
                        wrapper.put("metadata", new HashMap<String, Object>());
                        HashMap<String, Object> elem = (HashMap<String, Object>) wrapper.get("metadata");
                        if (instanceName != null) {
                            elem.put("instanceName", instanceName);
                        }
                        elem.put("saved", "COMPLETE");
                        elem.put("timestamp", datestamp);

                        b.append(ODKFileUtils.mapper.writeValueAsString(wrapper));

                        // OK we have the document in the builder (b).
                        String doc = b.toString();
                        exportFile(doc, submissionXml, log);
                    }
                    exportFile(freturn.serializeUriFragmentList(getContext()), manifest, log);
                    return ParcelFileDescriptor.open(manifest, ParcelFileDescriptor.MODE_READ_ONLY);

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

        } catch (JsonParseException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    } finally {
        if (db != null) {
            db.close();
        }
    }
    return null;
}