Example usage for android.database.sqlite SQLiteException printStackTrace

List of usage examples for android.database.sqlite SQLiteException printStackTrace

Introduction

In this page you can find the example usage for android.database.sqlite SQLiteException printStackTrace.

Prototype

public void printStackTrace() 

Source Link

Document

Prints this throwable and its backtrace to the standard error stream.

Usage

From source file:com.digicorp.plugin.sqlitePlugin.SQLitePlugin.java

/**
 * Executes a batch request and sends the results via sendJavascriptCB().
 *
 * @param dbname//  w  w  w .  j av a  2  s .co  m
 *            The name of the database.
 *
 * @param queryarr
 *            Array of query strings
 *
 * @param jsonparams
 *            Array of JSON query parameters
 *
 * @param queryIDs
 *            Array of query ids
 *
 * @param tx_id
 *            Transaction id
 *
 */
private void executeSqlBatch(String dbname, String[] queryarr, JSONArray[] jsonparams, String[] queryIDs,
        String tx_id) {
    SQLiteDatabase mydb = this.getDatabase(dbname);

    if (mydb == null)
        return;

    try {
        mydb.beginTransaction();

        String query = "";
        String query_id = "";
        int len = queryarr.length;

        for (int i = 0; i < len; i++) {
            query = queryarr[i];
            query_id = queryIDs[i];
            if (query.toLowerCase().startsWith("insert") && jsonparams != null) {
                SQLiteStatement myStatement = mydb.compileStatement(query);
                for (int j = 0; j < jsonparams[i].length(); j++) {
                    if (jsonparams[i].get(j) instanceof Float || jsonparams[i].get(j) instanceof Double) {
                        myStatement.bindDouble(j + 1, jsonparams[i].getDouble(j));
                    } else if (jsonparams[i].get(j) instanceof Number) {
                        myStatement.bindLong(j + 1, jsonparams[i].getLong(j));
                    } else if (jsonparams[i].isNull(j)) {
                        myStatement.bindNull(j + 1);
                    } else {
                        myStatement.bindString(j + 1, jsonparams[i].getString(j));
                    }
                }
                long insertId = myStatement.executeInsert();

                String result = "{'insertId':'" + insertId + "'}";
                this.sendJavascriptCB("window.SQLitePluginTransactionCB.queryCompleteCallback('" + tx_id + "','"
                        + query_id + "', " + result + ");");
            } else {
                String[] params = null;

                if (jsonparams != null) {
                    params = new String[jsonparams[i].length()];

                    for (int j = 0; j < jsonparams[i].length(); j++) {
                        if (jsonparams[i].isNull(j))
                            params[j] = "";
                        else
                            params[j] = jsonparams[i].getString(j);
                    }
                }

                Cursor myCursor = mydb.rawQuery(query, params);

                if (query_id.length() > 0)
                    this.processResults(myCursor, query_id, tx_id);

                myCursor.close();
            }
        }
        mydb.setTransactionSuccessful();
    } catch (SQLiteException ex) {
        ex.printStackTrace();
        Log.v("executeSqlBatch", "SQLitePlugin.executeSql(): Error=" + ex.getMessage());
        this.sendJavascriptCB("window.SQLitePluginTransactionCB.txErrorCallback('" + tx_id + "', '"
                + ex.getMessage() + "');");
    } catch (JSONException ex) {
        ex.printStackTrace();
        Log.v("executeSqlBatch", "SQLitePlugin.executeSql(): Error=" + ex.getMessage());
        this.sendJavascriptCB("window.SQLitePluginTransactionCB.txErrorCallback('" + tx_id + "', '"
                + ex.getMessage() + "');");
    } finally {
        mydb.endTransaction();
        Log.v("executeSqlBatch", tx_id);
        this.sendJavascriptCB("window.SQLitePluginTransactionCB.txCompleteCallback('" + tx_id + "');");
    }
}

From source file:com.zetaDevelopment.phonegap.plugin.sqlitePlugin.SQLitePlugin.java

/**
 * Executes a batch request and sends the results via sendJavascriptCB().
 *
 * @param dbname//from   ww w.j  a va  2s . c  om
 *            The name of the database.
 *
 * @param queryarr
 *            Array of query strings
 *
 * @param jsonparams
 *            Array of JSON query parameters
 *
 * @param queryIDs
 *            Array of query ids
 *
 * @param tx_id
 *            Transaction id
 *
 */
private void executeSqlBatch(String dbname, String[] queryarr, JSONArray[] jsonparams, String[] queryIDs,
        String tx_id) {
    SQLiteDatabase mydb = this.getDatabase(dbname);

    if (mydb == null)
        return;

    try {
        mydb.beginTransaction();

        String query = "";
        String query_id = "";
        int len = queryarr.length;

        for (int i = 0; i < len; i++) {
            query = queryarr[i];
            query_id = queryIDs[i];
            if (query.toLowerCase(Locale.getDefault()).startsWith("insert") && jsonparams != null) {
                SQLiteStatement myStatement = mydb.compileStatement(query);
                for (int j = 0; j < jsonparams[i].length(); j++) {
                    if (jsonparams[i].get(j) instanceof Float || jsonparams[i].get(j) instanceof Double) {
                        myStatement.bindDouble(j + 1, jsonparams[i].getDouble(j));
                    } else if (jsonparams[i].get(j) instanceof Number) {
                        myStatement.bindLong(j + 1, jsonparams[i].getLong(j));
                    } else {
                        myStatement.bindString(j + 1, jsonparams[i].getString(j));
                    }
                }
                long insertId = myStatement.executeInsert();

                String result = "{'insertId':'" + insertId + "'}";
                this.sendJavascriptCB("window.SQLitePluginTransactionCB.queryCompleteCallback('" + tx_id + "','"
                        + query_id + "', " + result + ");");
            } else {
                String[] params = null;

                if (jsonparams != null) {
                    params = new String[jsonparams[i].length()];

                    for (int j = 0; j < jsonparams[i].length(); j++) {
                        if (jsonparams[i].isNull(j))
                            params[j] = "";
                        else
                            params[j] = jsonparams[i].getString(j);
                    }
                }

                Cursor myCursor = mydb.rawQuery(query, params);

                if (query_id.length() > 0)
                    this.processResults(myCursor, query_id, tx_id);

                myCursor.close();
            }
        }
        mydb.setTransactionSuccessful();
    } catch (SQLiteException ex) {
        ex.printStackTrace();
        Log.v("executeSqlBatch", "SQLitePlugin.executeSql(): Error=" + ex.getMessage());
        this.sendJavascriptCB("window.SQLitePluginTransactionCB.txErrorCallback('" + tx_id + "', '"
                + ex.getMessage() + "');");
    } catch (JSONException ex) {
        ex.printStackTrace();
        Log.v("executeSqlBatch", "SQLitePlugin.executeSql(): Error=" + ex.getMessage());
        this.sendJavascriptCB("window.SQLitePluginTransactionCB.txErrorCallback('" + tx_id + "', '"
                + ex.getMessage() + "');");
    } finally {
        mydb.endTransaction();
        Log.v("executeSqlBatch", tx_id);
        this.sendJavascriptCB("window.SQLitePluginTransactionCB.txCompleteCallback('" + tx_id + "');");
    }
}

From source file:com.siddroid.offlinews.SendOffline.java

/**
 * Initialize database helper.//from www . j  av a2  s .  com
 *
 * @param context the context
 */
private void initDb(Context ctx) {

    try {
        mDbHelper = DbHelper.getInstance(ctx);
        db = mDbHelper.createOrOpenDb();
    } catch (SQLiteException e) {
        // Our app fires an event spawning the db creation task...
        e.printStackTrace();
    } catch (Exception e) {
        // Our app fires an event spawning the db creation task...
        e.printStackTrace();
    }
}

From source file:com.polyvi.xface.extension.XMessagingExt.java

/**
 * ??/* ww  w  .  ja v a 2  s .c  o  m*/
 * @param messageType       ?MMS,SMS,Email
 * @param  folderType       
 * @param  index            ?
 * @return                  ?
 */
private JSONObject getMessage(String messageType, String folderType, int index) throws JSONException {
    //TODO:???Email?
    if (null == folderType) {// folderTypenull?
        folderType = FOLDERTYPE_DRAFT;
    }

    JSONObject message = new JSONObject();
    try {
        // ???
        String[] projection = new String[] { "_id", "subject", "address", "body", "date", "read" };
        folderType = folderType.toLowerCase();
        Uri uri = Uri.withAppendedPath(mSMSContentUri, folderType);
        ContentResolver resolver = getContext().getContentResolver();
        Cursor cursor = resolver.query(uri, projection, null, null, "date desc");

        if (null == cursor) {
            return message;
        }
        // ??
        if (!cursor.moveToPosition(index)) {
            cursor.close();
            return message;
        }
        //TODO:?SIM??
        message = getMessageFromCursor(cursor);
        cursor.close();

    } catch (SQLiteException ex) {
        ex.printStackTrace();
    }
    return message;
}

From source file:com.polyvi.xface.extension.XMessagingExt.java

/**
 * ??//from  w w  w  . ja  va  2s  .c  om
 * @param messageType       ?MMS,SMS,Email
 * @param  folderType       
 * @return                  ?
 */
private JSONArray getAllMessages(String messageType, String folderType) throws JSONException {
    //TODO:???Email?
    if (null == folderType) {// folderTypenull?
        folderType = FOLDERTYPE_DRAFT;
    }
    JSONArray messages = new JSONArray();
    try {
        // ???
        String[] projection = new String[] { "_id", "subject", "address", "body", "date", "read" };
        folderType = folderType.toLowerCase();
        Uri uri = Uri.withAppendedPath(mSMSContentUri, folderType);
        ContentResolver resolver = getContext().getContentResolver();
        Cursor cursor = resolver.query(uri, projection, null, null, "date desc");

        if (null == cursor) {
            return messages;
        }
        if (!cursor.moveToFirst()) {
            cursor.close();
            return messages;
        }
        do {
            //TODO:?SIM??
            JSONObject message = getMessageFromCursor(cursor);
            messages.put(message);
        } while (cursor.moveToNext());
        cursor.close();

    } catch (SQLiteException ex) {
        ex.printStackTrace();
    }
    return messages;
}

From source file:com.polyvi.xface.extension.messaging.XMessagingExt.java

/**
 * ??//w  ww  .ja v a  2 s.  c o m
 *
 * @param messageType
 *            ?MMS,SMS,Email
 * @param folderType
 *            
 * @param index
 *            ?
 * @return ?
 */
private JSONObject getMessage(String messageType, String folderType, int index) throws JSONException {
    // TODO:???Email?
    if (null == folderType) {// folderTypenull?
        folderType = FOLDERTYPE_DRAFT;
    }

    JSONObject message = new JSONObject();
    try {
        // ???
        String[] projection = new String[] { "_id", "subject", "address", "body", "date", "read" };
        folderType = folderType.toLowerCase();
        Uri uri = Uri.withAppendedPath(mSMSContentUri, folderType);
        ContentResolver resolver = mContext.getContentResolver();
        Cursor cursor = resolver.query(uri, projection, null, null, "date desc");

        if (null == cursor) {
            return message;
        }
        // ??
        if (!cursor.moveToPosition(index)) {
            cursor.close();
            return message;
        }
        // TODO:?SIM??
        message = getMessageFromCursor(cursor);
        cursor.close();

    } catch (SQLiteException ex) {
        ex.printStackTrace();
    }
    return message;
}

From source file:com.polyvi.xface.extension.messaging.XMessagingExt.java

/**
 * ??/*w  ww. ja v  a 2  s.c om*/
 *
 * @param messageType
 *            ?MMS,SMS,Email
 * @param folderType
 *            
 * @return ?
 */
private JSONArray getAllMessages(String messageType, String folderType) throws JSONException {
    // TODO:???Email?
    if (null == folderType) {// folderTypenull?
        folderType = FOLDERTYPE_DRAFT;
    }
    JSONArray messages = new JSONArray();
    try {
        // ???
        String[] projection = new String[] { "_id", "subject", "address", "body", "date", "read" };
        folderType = folderType.toLowerCase();
        Uri uri = Uri.withAppendedPath(mSMSContentUri, folderType);
        ContentResolver resolver = mContext.getContentResolver();
        Cursor cursor = resolver.query(uri, projection, null, null, "date desc");

        if (null == cursor) {
            return messages;
        }
        if (!cursor.moveToFirst()) {
            cursor.close();
            return messages;
        }
        do {
            // TODO:?SIM??
            JSONObject message = getMessageFromCursor(cursor);
            messages.put(message);
        } while (cursor.moveToNext());
        cursor.close();

    } catch (SQLiteException ex) {
        ex.printStackTrace();
    }
    return messages;
}

From source file:com.polyvi.xface.extension.XMessagingExt.java

/**
 * ?//from w w w .ja v  a 2  s. co  m
 * @param comparisonMsg   ??
 * @param folderType      
 * @param startIndex      
 * @param endIndex        ?
 * @return                ?
 */
private JSONArray findMessages(JSONObject comparisonMsg, String folderType, int startIndex, int endIndex)
        throws JSONException {
    // TODO:???Email?
    if (null == folderType) {// folderTypenull?
        folderType = FOLDERTYPE_DRAFT;
    }

    ArrayList<String> projections = new ArrayList<String>();
    projections.add("_id");
    projections.add("subject");
    projections.add("address");
    projections.add("body");
    ArrayList<String> projectionsValue = new ArrayList<String>();
    projectionsValue.add(comparisonMsg.optString("messageId"));
    projectionsValue.add(comparisonMsg.optString("subject"));
    projectionsValue.add(comparisonMsg.optString("destinationAddresses"));
    projectionsValue.add(comparisonMsg.optString("body"));

    StringBuilder selection = XUtils.constructSelectionStatement(projections, projectionsValue);

    int isRead = comparisonMsg.getInt("isRead");
    if (-1 != isRead) {
        if (null == selection) {
            selection = new StringBuilder();
        } else {
            selection.append(" AND ");
        }
        selection.append("read");
        selection.append("=");
        selection.append(isRead);
    }
    String selectionStr = null;
    if (null != selection) {
        selectionStr = selection.toString();
    }

    folderType = folderType.toLowerCase();
    Uri findUri = Uri.withAppendedPath(mSMSContentUri, folderType);
    JSONArray messages = new JSONArray();
    try {
        ContentResolver resolver = getContext().getContentResolver();
        Cursor cursor = resolver.query(findUri, null, selectionStr, null, null);
        if (null == cursor) {
            return messages;
        }
        int count = endIndex - startIndex + 1;
        if (cursor.moveToPosition(startIndex)) {
            do {
                JSONObject message = getMessageFromCursor(cursor);
                messages.put(message);
                count--;
            } while (cursor.moveToNext() && count > 0);
        }
        cursor.close();
    } catch (SQLiteException ex) {
        ex.printStackTrace();
    }
    return messages;
}

From source file:com.polyvi.xface.extension.messaging.XMessagingExt.java

/**
 * ?//from   w  w w .  j ava  2 s . c  o  m
 *
 * @param comparisonMsg
 *            ??
 * @param folderType
 *            
 * @param startIndex
 *            
 * @param endIndex
 *            ?
 * @return ?
 */
private JSONArray findMessages(JSONObject comparisonMsg, String folderType, int startIndex, int endIndex)
        throws JSONException {
    // TODO:???Email?
    if (null == folderType) {// folderTypenull?
        folderType = FOLDERTYPE_DRAFT;
    }

    ArrayList<String> projections = new ArrayList<String>();
    projections.add("_id");
    projections.add("subject");
    projections.add("address");
    projections.add("body");
    ArrayList<String> projectionsValue = new ArrayList<String>();
    projectionsValue.add(comparisonMsg.optString("messageId"));
    projectionsValue.add(comparisonMsg.optString("subject"));
    projectionsValue.add(comparisonMsg.optString("destinationAddresses"));
    projectionsValue.add(comparisonMsg.optString("body"));

    StringBuilder selection = XUtils.constructSelectionStatement(projections, projectionsValue);

    int isRead = comparisonMsg.getInt("isRead");
    if (-1 != isRead) {
        if (null == selection) {
            selection = new StringBuilder();
        } else {
            selection.append(" AND ");
        }
        selection.append("read");
        selection.append("=");
        selection.append(isRead);
    }
    String selectionStr = null;
    if (null != selection) {
        selectionStr = selection.toString();
    }

    folderType = folderType.toLowerCase();
    Uri findUri = Uri.withAppendedPath(mSMSContentUri, folderType);
    JSONArray messages = new JSONArray();
    try {
        ContentResolver resolver = mContext.getContentResolver();
        Cursor cursor = resolver.query(findUri, null, selectionStr, null, null);
        if (null == cursor) {
            return messages;
        }
        int count = endIndex - startIndex + 1;
        if (cursor.moveToPosition(startIndex)) {
            do {
                JSONObject message = getMessageFromCursor(cursor);
                messages.put(message);
                count--;
            } while (cursor.moveToNext() && count > 0);
        }
        cursor.close();
    } catch (SQLiteException ex) {
        ex.printStackTrace();
    }
    return messages;
}

From source file:org.cgiar.ilri.odk.pull.backend.services.FetchFormDataService.java

/**
 * Dumps data provided the rows variable into the specified database. The location of the database
 * is in the form's media folder in ODK's SDCard's folder.
 *
 * Indexes in {@param rows} are expected to correspond to rows in {@param org.cgiar.ilri.odk.pull.backend.carriers.Form.DB_DATA_TABLE} for {@param fileName}.
 * Each JSONArray element should be a JSONObject with children being column values (with keys being column names).
 * Make sure all JSONObjects in the JSONArray have the same number of key-value pairs.
 *
 * @param fileName  Then name to be given to the Database (without the .db suffix)
 * @param rows      The {@link org.json.JSONArray} object containing the data
 * @return  TRUE if database created successfully
 *//*from   w w  w. jav  a  2 s.  co m*/
private boolean saveDataInDb(String fileName, JSONArray rows) {
    boolean result = false;
    //TODO: only do this if ODK Collect is not using this file
    String pathToFile = Form.BASE_ODK_LOCATION + formName + Form.EXTERNAL_ITEM_SET_SUFFIX;
    /*File existingDb = new File(pathToFile+File.separator+fileName+Form.SUFFIX_DB);
    existingDb.delete();*/
    final DatabaseHelper databaseHelper = new DatabaseHelper(this, fileName, 1, pathToFile);
    SQLiteDatabase db = null;
    try {
        db = databaseHelper.getWritableDatabase();
    } catch (SQLiteException e) {//probably because the existing .db file is corrupt
        e.printStackTrace();
        Log.w(TAG, "Unable to open database in " + pathToFile + File.separator + fileName + Form.SUFFIX_DB
                + " most likely because the database is corrupt. Trying to recreate db file");
        File existingDbFile = new File(pathToFile + File.separator + fileName + Form.SUFFIX_DB);
        existingDbFile.delete();
        File existingDbJournalFile = new File(
                pathToFile + File.separator + fileName + Form.SUFFIX_DB + Form.SUFFIX_JOURNAL);
        existingDbJournalFile.delete();
        try {
            db = databaseHelper.getWritableDatabase();
        } catch (SQLiteException e1) {
            Log.e(TAG,
                    "Unable to recreate " + pathToFile + File.separator + fileName + Form.SUFFIX_DB + "  file");
            e1.printStackTrace();
        }
    }
    if (rows.length() > 0 && db != null) {
        try {
            List<String> columns = new ArrayList<String>();
            List<String> indexes = new ArrayList<String>();
            Iterator<String> iterator = rows.getJSONObject(0).keys();
            //recreate the tables
            db.execSQL("drop table if exists " + Form.DB_METADATA_TABLE);
            String createMetaTableString = "create table " + Form.DB_METADATA_TABLE + " ("
                    + Form.DB_META_LOCALE_FIELD + " " + Form.DB_META_LOCALE_FIELD_TYPE + ")";
            db.execSQL(createMetaTableString);
            databaseHelper.runInsertQuery(Form.DB_METADATA_TABLE, new String[] { Form.DB_META_LOCALE_FIELD },
                    new String[] { Form.DB_DEFAULT_LOCALE }, -1, db);
            db.execSQL("drop table if exists " + Form.DB_DATA_TABLE);
            String createTableString = "create table " + Form.DB_DATA_TABLE + " (";
            while (iterator.hasNext()) {
                String currKey = iterator.next();
                if (columns.size() > 0) {//this is the first column
                    createTableString = createTableString + ", ";
                }
                createTableString = createTableString + Form.DB_DATA_COLUMN_PREFIX + currKey + " "
                        + Form.DB_DATA_COLUMN_TYPE;
                columns.add(currKey);
                if (currKey.endsWith(Form.SUFFIX_INDEX_FIELD)) {
                    Log.d(TAG, fileName + " has an index column " + currKey);
                    indexes.add(currKey);
                }
            }
            //only continue if we have at least one column
            if (columns.size() > 0) {
                createTableString = createTableString + ", " + Form.DB_DATA_SORT_FIELD + " "
                        + Form.DB_DATA_SORT_COLUMN_TYPE + ")";
                db.execSQL(createTableString);
                for (int index = 0; index < indexes.size(); index++) {
                    db.execSQL("create index " + indexes.get(index) + Form.SUFFIX_INDEX + " on "
                            + Form.DB_DATA_TABLE + "(" + Form.DB_DATA_COLUMN_PREFIX + indexes.get(index) + ")");
                }
                for (int rowIndex = 0; rowIndex < rows.length(); rowIndex++) {
                    JSONObject currRow = rows.getJSONObject(rowIndex);
                    String[] currColumns = new String[columns.size() + 1];
                    String[] currValues = new String[columns.size() + 1];
                    for (int columnIndex = 0; columnIndex < columns.size(); columnIndex++) {
                        currColumns[columnIndex] = Form.DB_DATA_COLUMN_PREFIX + columns.get(columnIndex);
                        currValues[columnIndex] = currRow.getString(columns.get(columnIndex));
                    }
                    currColumns[columns.size()] = Form.DB_DATA_SORT_FIELD;
                    currValues[columns.size()] = String.valueOf((double) rowIndex);//TODO: not sure if should be float or double
                    databaseHelper.runInsertQuery(Form.DB_DATA_TABLE, currColumns, currValues, -1, db);//do not add unique key field index in argument list. Will end up being an extra query
                }
                result = true;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    } else {
        Log.w(TAG, "Provided jsonArray to be dumped into a db is empty");
    }
    db.close();
    //copy db to the ADB push directory
    File adbFormDir = new File(
            Form.BASE_ODK_LOCATION + formName.replaceAll("[^A-Za-z0-9]", "_") + Form.EXTERNAL_ITEM_SET_SUFFIX);
    if (!adbFormDir.exists() || !adbFormDir.isDirectory()) {
        adbFormDir.setWritable(true);
        adbFormDir.setReadable(true);
        Log.i(TAG, "Trying to create dir " + adbFormDir.getPath());
    }
    File sourceDbFile = new File(pathToFile + File.separator + fileName + Form.SUFFIX_DB);
    File destDbFile = new File(Form.BASE_ODK_LOCATION + formName.replaceAll("[^A-Za-z0-9]", "_")
            + Form.EXTERNAL_ITEM_SET_SUFFIX + File.separator + fileName + Form.SUFFIX_DB);
    InputStream in = null;
    OutputStream out = null;
    try {
        in = new FileInputStream(sourceDbFile);
        out = new FileOutputStream(destDbFile);
        // Copy the bits from instream to outstream
        byte[] buf = new byte[1024];
        int len;
        while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        in.close();
        out.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return result;
}