Example usage for android.database.sqlite SQLiteDatabase beginTransaction

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

Introduction

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

Prototype

public void beginTransaction() 

Source Link

Document

Begins a transaction in EXCLUSIVE mode.

Usage

From source file:net.smart_json_database.JSONDatabase.java

public boolean deleteTag(String name) {
    boolean returnValue = false;
    SQLiteDatabase db = dbHelper.getWritableDatabase();
    try {//w w  w. ja  v  a2 s .co m
        db.beginTransaction();
        returnValue = deleteTag(name, db);
        db.setTransactionSuccessful();
        notifyListenersOnTagChange(name, IDatabaseChangeListener.CHANGETYPE_DELETE);
    } catch (Exception e) {
    } finally {
        db.endTransaction();
        db.close();
    }
    return returnValue;
}

From source file:net.smart_json_database.JSONDatabase.java

public int insertTag(String name) {
    int returnValue = -1;
    SQLiteDatabase db = dbHelper.getWritableDatabase();

    try {/*from   w  w  w. j a  v  a  2 s  . co m*/
        db.beginTransaction();
        returnValue = insertTag(name, db);
        db.setTransactionSuccessful();
        notifyListenersOnTagChange(name, IDatabaseChangeListener.CHANGETYPE_INSERT);
    } catch (Exception e) {
    } finally {
        db.endTransaction();
        db.close();
    }
    return returnValue;
}

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

@Override
public synchronized Uri insert(Uri uri, ContentValues initialValues) {
    List<String> segments = uri.getPathSegments();

    if (segments.size() != 1) {
        throw new IllegalArgumentException("Unknown URI (too many segments!) " + uri);
    }//from   w w  w  . j  av a  2 s.c o  m

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

    ContentValues values;
    if (initialValues != null) {
        values = new ContentValues(initialValues);
    } else {
        values = new ContentValues();
    }

    // ODK2: require FORM_MEDIA_PATH (different behavior -- ODK1 and
    // required FORM_FILE_PATH)
    if (!values.containsKey(FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH)) {
        throw new IllegalArgumentException(FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH + " must be specified.");
    }

    // Normalize path...
    File mediaPath = ODKFileUtils.asAppFile(appName,
            values.getAsString(FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH));

    // require that the form directory actually exists
    if (!mediaPath.exists()) {
        throw new IllegalArgumentException(FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH
                + " directory does not exist: " + mediaPath.getAbsolutePath());
    }

    patchUpValues(appName, values);

    if (values.containsKey(FormsColumns.DISPLAY_SUBTEXT) == false) {
        Date today = new Date();
        String ts = new SimpleDateFormat(getContext().getString(R.string.added_on_date_at_time),
                Locale.getDefault()).format(today);
        values.put(FormsColumns.DISPLAY_SUBTEXT, ts);
    }

    if (values.containsKey(FormsColumns.DISPLAY_NAME) == false) {
        values.put(FormsColumns.DISPLAY_NAME, mediaPath.getName());
    }

    // first try to see if a record with this filename already exists...
    String[] projection = { FormsColumns.FORM_ID, FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH };
    String[] selectionArgs = { ODKFileUtils.asRelativePath(appName, mediaPath) };
    String selection = FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH + "=?";
    Cursor c = null;

    SQLiteDatabase db = null;
    try {
        db = DatabaseFactory.get().getDatabase(getContext(), appName);
        db.beginTransaction();
        try {
            c = db.query(DatabaseConstants.FORMS_TABLE_NAME, projection, selection, selectionArgs, null, null,
                    null);
            if (c == null) {
                throw new SQLException("FAILED Insert into " + uri
                        + " -- unable to query for existing records: " + mediaPath.getAbsolutePath());
            }
            if (c.getCount() > 0) {
                // already exists
                throw new SQLException("FAILED Insert into " + uri
                        + " -- row already exists for form directory: " + mediaPath.getAbsolutePath());
            }
        } catch (Exception e) {
            log.w(t, "FAILED Insert into " + uri + " -- query for existing row failed: " + e.toString());

            if (e instanceof SQLException) {
                throw (SQLException) e;
            } else {
                throw new SQLException(
                        "FAILED Insert into " + uri + " -- query for existing row failed: " + e.toString());
            }
        } finally {
            if (c != null) {
                c.close();
            }
        }

        try {
            long rowId = db.insert(DatabaseConstants.FORMS_TABLE_NAME, null, values);
            db.setTransactionSuccessful();
            if (rowId > 0) {
                Uri formUri = Uri.withAppendedPath(
                        Uri.withAppendedPath(Uri.parse("content://" + getFormsAuthority()), appName),
                        values.getAsString(FormsColumns.FORM_ID));
                getContext().getContentResolver().notifyChange(formUri, null);
                Uri idUri = Uri.withAppendedPath(
                        Uri.withAppendedPath(Uri.parse("content://" + getFormsAuthority()), appName),
                        Long.toString(rowId));
                getContext().getContentResolver().notifyChange(idUri, null);

                return formUri;
            }
        } catch (Exception e) {
            log.w(t, "FAILED Insert into " + uri + " -- insert of row failed: " + e.toString());

            if (e instanceof SQLException) {
                throw (SQLException) e;
            } else {
                throw new SQLException(
                        "FAILED Insert into " + uri + " -- insert of row failed: " + e.toString());
            }
        }
    } finally {
        if (db != null) {
            db.endTransaction();
            db.close();
        }
    }

    throw new SQLException("Failed to insert row into " + uri);
}

From source file:net.smart_json_database.JSONDatabase.java

/**
 * Deletes all content without the meta data
 * //from ww w  .  java  2  s  . c o  m
 * @return true if all delte operations are succesfull
 */
public boolean clearAllTables() {
    boolean returnValue = true;
    SQLiteDatabase db = dbHelper.getWritableDatabase();
    try {
        db.beginTransaction();
        //db.execSQL("DELETE FROM " + TABLE_Meta);
        db.execSQL("DELETE FROM " + TABLE_TAG);
        db.execSQL("DELETE FROM " + TABLE_JSON_DATA);
        db.execSQL("DELETE FROM " + TABLE_REL_TAG_JSON_DATA);
        db.setTransactionSuccessful();
    } catch (Exception e) {
        returnValue = false;
    } finally {
        db.endTransaction();
        db.close();
    }
    return returnValue;
}

From source file:net.smart_json_database.JSONDatabase.java

public boolean delete(JSONEntity entity) {
    boolean returnValue = false;
    if (entity.getUid() == -1) {
        return returnValue;
    }//from  w  ww  . jav a  2 s . c o  m
    SQLiteDatabase db = dbHelper.getWritableDatabase();
    try {
        db.beginTransaction();
        String[] params = new String[] { "" + entity.getUid() };
        db.delete(TABLE_REL_JSON_DATA_JSON_DATA, "from_id = ?", params);
        db.delete(TABLE_REL_JSON_DATA_JSON_DATA, "to_id = ?", params);
        db.delete(TABLE_REL_TAG_JSON_DATA, "to_id = ?", params);
        db.delete(TABLE_JSON_DATA, "json_uid = ?", params);
        db.setTransactionSuccessful();
        notifyListenersOnEntityChange(entity.getUid(), IDatabaseChangeListener.CHANGETYPE_DELETE);
        returnValue = true;
    } catch (Exception e) {
        returnValue = false;
    } finally {
        db.endTransaction();
        db.close();
    }

    return returnValue;
}

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

/**
 * This method removes the entry from the content provider, and also removes
 * any associated files. files: form.xml, [formmd5].formdef, formname
 * {directory}//from w ww  .j a v  a 2 s .c om
 */
@Override
public int delete(Uri uri, String where, String[] whereArgs) {
    List<String> segments = uri.getPathSegments();

    if (segments.size() < 1 || segments.size() > 2) {
        throw new IllegalArgumentException("Unknown URI (incorrect number of segments!) " + uri);
    }

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

    String uriFormId = ((segments.size() == 2) ? segments.get(1) : null);
    boolean isNumericId = StringUtils.isNumeric(uriFormId);

    // Modify the where clause to account for the presence of
    // a form id. Accept either:
    // (1) numeric _ID value
    // (2) string FORM_ID value.
    String whereId;
    String[] whereIdArgs;

    if (uriFormId == null) {
        whereId = where;
        whereIdArgs = whereArgs;
    } else {
        if (TextUtils.isEmpty(where)) {
            whereId = (isNumericId ? FormsColumns._ID : FormsColumns.FORM_ID) + "=?";
            whereIdArgs = new String[1];
            whereIdArgs[0] = uriFormId;
        } else {
            whereId = (isNumericId ? FormsColumns._ID : FormsColumns.FORM_ID) + "=? AND (" + where + ")";
            whereIdArgs = new String[whereArgs.length + 1];
            whereIdArgs[0] = uriFormId;
            for (int i = 0; i < whereArgs.length; ++i) {
                whereIdArgs[i + 1] = whereArgs[i];
            }
        }
    }

    Cursor del = null;
    Integer idValue = null;
    String tableIdValue = null;
    String formIdValue = null;
    HashMap<File, DirType> mediaDirs = new HashMap<File, DirType>();
    try {
        del = this.query(uri, null, whereId, whereIdArgs, null);
        if (del == null) {
            throw new SQLException("FAILED Delete into " + uri + " -- unable to query for existing records");
        }
        del.moveToPosition(-1);
        while (del.moveToNext()) {
            idValue = ODKDatabaseUtils.get().getIndexAsType(del, Integer.class,
                    del.getColumnIndex(FormsColumns._ID));
            tableIdValue = ODKDatabaseUtils.get().getIndexAsString(del,
                    del.getColumnIndex(FormsColumns.TABLE_ID));
            formIdValue = ODKDatabaseUtils.get().getIndexAsString(del,
                    del.getColumnIndex(FormsColumns.FORM_ID));
            File mediaDir = ODKFileUtils.asAppFile(appName, ODKDatabaseUtils.get().getIndexAsString(del,
                    del.getColumnIndex(FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH)));
            mediaDirs.put(mediaDir, (tableIdValue == null) ? DirType.FRAMEWORK : DirType.FORMS);
        }
    } catch (Exception e) {
        log.w(t, "FAILED Delete from " + uri + " -- query for existing row failed: " + e.toString());

        if (e instanceof SQLException) {
            throw (SQLException) e;
        } else {
            throw new SQLException(
                    "FAILED Delete from " + uri + " -- query for existing row failed: " + e.toString());
        }
    } finally {
        if (del != null && !del.isClosed()) {
            del.close();
        }
    }

    SQLiteDatabase db = null;
    int count;
    try {
        db = DatabaseFactory.get().getDatabase(getContext(), appName);
        db.beginTransaction();
        count = db.delete(DatabaseConstants.FORMS_TABLE_NAME, whereId, whereIdArgs);
        db.setTransactionSuccessful();
    } catch (Exception e) {
        e.printStackTrace();
        log.w(t, "Unable to perform deletion " + e.toString());
        return 0;
    } finally {
        if (db != null) {
            db.endTransaction();
            db.close();
        }
    }

    // and attempt to move these directories to the stale forms location
    // so that they do not immediately get rescanned...

    for (HashMap.Entry<File, DirType> entry : mediaDirs.entrySet()) {
        try {
            moveDirectory(appName, entry.getValue(), entry.getKey());
        } catch (IOException e) {
            e.printStackTrace();
            log.e(t, "Unable to move directory " + e.toString());
        }
    }

    if (count == 1) {
        Uri formUri = Uri.withAppendedPath(
                Uri.withAppendedPath(Uri.parse("content://" + getFormsAuthority()), appName), formIdValue);
        getContext().getContentResolver().notifyChange(formUri, null);
        Uri idUri = Uri.withAppendedPath(
                Uri.withAppendedPath(Uri.parse("content://" + getFormsAuthority()), appName),
                Long.toString(idValue));
        getContext().getContentResolver().notifyChange(idUri, null);
    } else {
        getContext().getContentResolver().notifyChange(uri, null);
    }
    return count;
}

From source file:net.smart_json_database.JSONDatabase.java

public boolean deleteAll() {
    SQLiteDatabase db = dbHelper.getWritableDatabase();
    boolean returnValue = false;
    try {/*from  w  w  w .  jav  a2s .  co  m*/
        db.beginTransaction();
        db.delete(TABLE_REL_JSON_DATA_JSON_DATA, "", null);
        db.delete(TABLE_REL_JSON_DATA_JSON_DATA, "", null);
        db.delete(TABLE_REL_TAG_JSON_DATA, "", null);
        db.delete(TABLE_JSON_DATA, "", null);
        db.setTransactionSuccessful();
        returnValue = true;
    } catch (Exception e) {
        returnValue = false;
    } finally {
        db.endTransaction();
        db.close();
    }
    return returnValue;
}

From source file:net.smart_json_database.JSONDatabase.java

public int insert(JSONEntity entity) {

    int returnValue = -1;
    SQLiteDatabase db = dbHelper.getWritableDatabase();
    try {/*from   ww  w. j  a va2 s.c om*/
        db.beginTransaction();
        ContentValues values = new ContentValues();
        values.put("createDate", Util.DateToString(entity.getCreationDate()));
        values.put("updateDate", Util.DateToString(entity.getUpdateDate()));
        values.put("data", entity.getData().toString());
        values.put("type", entity.getType());
        int uid = Util.LongToInt(db.insert(TABLE_JSON_DATA, null, values));
        returnValue = uid;
        //entity.setUid(uid);
        for (String name : entity.getTags().getToAdd()) {
            int tagid = -1;
            if (!tags.containsKey(name)) {
                tagid = insertTag(name, db);
            } else {
                tagid = tags.get(name);
            }
            if (relateTagWithJsonEntity(tagid, uid, db) == -1) {
                throw new Exception("could not relate entity with tags");
            }
        }

        for (HasMany hasMany : entity.getHasManyRelations().values()) {
            //               for(Integer id : hasMany.getToRemove())
            //               {
            //                  deleteRelation(hasMany.getName(), uid, id, db);
            //               }

            for (Integer id : hasMany.getToAdd()) {
                insertRelation(hasMany.getName(), uid, id, db);
            }
        }

        for (BelongsTo belongsTo : entity.getBelongsToRelations().values()) {
            //               for(Integer id : belongsTo.getToRemove())
            //               {
            //                  deleteRelation(belongsTo.getName(), id ,uid,  db);
            //               }

            for (Integer id : belongsTo.getToAdd()) {
                insertRelation(belongsTo.getName(), id, uid, db);
            }
        }

        db.setTransactionSuccessful();
        notifyListenersOnEntityChange(returnValue, IDatabaseChangeListener.CHANGETYPE_INSERT);
    } catch (Exception e) {
        returnValue = -1;
    } finally {
        db.endTransaction();
        db.close();
    }
    return returnValue;
}

From source file:net.smart_json_database.JSONDatabase.java

public int update(JSONEntity entity) {
    int returnValue = -1;
    if (entity.getUid() == -1) {
        return returnValue;
    }//from w  ww .j ava2 s  . co  m

    SQLiteDatabase db = dbHelper.getWritableDatabase();

    try {
        db.beginTransaction();
        entity.setUpdateDate(new Date());
        ContentValues values = new ContentValues();
        values.put("data", entity.getData().toString());
        values.put("updateDate", Util.DateToString(entity.getUpdateDate()));
        values.put("type", entity.getType());
        String[] params = new String[] { "" + entity.getUid() };
        db.update(TABLE_JSON_DATA, values, "json_uid = ?", params);
        for (String name : entity.getTags().getToAdd()) {
            int tagid = -1;
            if (!tags.containsKey(name)) {
                tagid = insertTag(name, db);
            } else {
                tagid = tags.get(name);
            }
            if (relateTagWithJsonEntity(tagid, entity.getUid(), db) == -1) {
                throw new Exception("could not relate");
            }

        }
        for (String name : entity.getTags().getToRemove()) {
            int tagid = -1;
            if (!tags.containsKey(name)) {
                continue;
            } else {
                tagid = tags.get(name);
            }

            db.delete(TABLE_REL_TAG_JSON_DATA, "to_id = ?", new String[] { "" + tagid });
        }

        for (HasMany hasMany : entity.getHasManyRelations().values()) {
            for (Integer id : hasMany.getToRemove()) {
                deleteRelation(hasMany.getName(), entity.getUid(), id, db);
            }

            for (Integer id : hasMany.getToAdd()) {
                insertRelation(hasMany.getName(), entity.getUid(), id, db);
            }
        }

        for (BelongsTo belongsTo : entity.getBelongsToRelations().values()) {
            for (Integer id : belongsTo.getToRemove()) {
                deleteRelation(belongsTo.getName(), id, entity.getUid(), db);
            }

            for (Integer id : belongsTo.getToAdd()) {
                insertRelation(belongsTo.getName(), id, entity.getUid(), db);
            }
        }

        db.setTransactionSuccessful();
        returnValue = entity.getUid();
        notifyListenersOnEntityChange(returnValue, IDatabaseChangeListener.CHANGETYPE_UPDATE);
    } catch (Exception e) {
        returnValue = -1;
    } finally {
        db.endTransaction();
        db.close();
    }
    return returnValue;

}

From source file:com.geecko.QuickLyric.tasks.WriteToDatabaseTask.java

@Override
public Boolean doInBackground(Object... params) {
    lyricsArray = new Lyrics[params.length - 2];
    SQLiteDatabase database;
    if (params[0] instanceof Fragment) {
        fragment = (Fragment) params[0];
        mContext = fragment.getActivity();
        if (mContext == null || !(mContext instanceof MainActivity))
            cancel(true);//from  w  w  w  .j a  v  a 2  s. com
        database = DatabaseHelper.getInstance(mContext).getWritableDatabase();
    } else
        database = (SQLiteDatabase) params[0];
    item = (MenuItem) params[1];
    if (params[2] instanceof Lyrics[])
        lyricsArray = (Lyrics[]) params[2];
    else
        for (int i = 0; i < lyricsArray.length; i++) {
            lyricsArray[i] = (Lyrics) params[i + 2];
        }
    boolean result = true;
    String[] columns = DatabaseHelper.columns;
    if (database != null && database.isOpen()) {
        database.beginTransaction();
        try {
            for (Lyrics lyrics : lyricsArray) {
                Lyrics storedLyrics = DatabaseHelper.getInstance(mContext)
                        .get(new String[] { lyrics.getArtist(), lyrics.getTitle(), lyrics.getOriginalArtist(),
                                lyrics.getOriginalTrack() });
                if ((storedLyrics == null || (!storedLyrics.isLRC() && lyrics.isLRC()))
                        && !"Storage".equals(lyrics.getSource())) {
                    ContentValues values = new ContentValues(2);
                    values.put(columns[0], lyrics.getArtist());
                    values.put(columns[1], lyrics.getTitle());
                    values.put(columns[2], lyrics.getText());
                    values.put(columns[3], lyrics.getURL());
                    values.put(columns[4], lyrics.getSource());
                    if (lyrics.getCoverURL() != null && lyrics.getCoverURL().startsWith("http://"))
                        values.put(columns[5], lyrics.getCoverURL());
                    values.put(columns[6], lyrics.getOriginalArtist());
                    values.put(columns[7], lyrics.getOriginalTrack());
                    values.put(columns[8], lyrics.isLRC() ? 1 : 0);
                    values.put(columns[9], lyrics.getWriter());
                    values.put(columns[10], lyrics.getCopyright());
                    database.delete(DatabaseHelper.TABLE_NAME,
                            String.format("%s=? AND %s=?", columns[0], columns[1]),
                            new String[] { lyrics.getArtist(), lyrics.getTitle() });
                    database.insert(DatabaseHelper.TABLE_NAME, null, values);
                    if (fragment instanceof LyricsViewFragment)
                        ((LyricsViewFragment) fragment).lyricsPresentInDB = true;
                    result = true;
                } else if (mContext != null) { // if called from activity, not service
                    database.delete(DatabaseHelper.TABLE_NAME,
                            String.format("%s=? AND %s=?", columns[0], columns[1]),
                            new String[] { lyrics.getArtist(), lyrics.getTitle() });
                    if (fragment instanceof LyricsViewFragment)
                        ((LyricsViewFragment) fragment).lyricsPresentInDB = false;
                    result = false;
                }
                database.yieldIfContendedSafely();
            }
            database.setTransactionSuccessful();
        } finally {
            database.endTransaction();
        }
    }
    return result;
}