Example usage for android.database.sqlite SQLiteException SQLiteException

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

Introduction

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

Prototype

public SQLiteException(String error) 

Source Link

Usage

From source file:edu.washington.cs.mystatus.odk.database.ODKSQLiteOpenHelper.java

/**
 * Create and/or open a database that will be used for reading and writing. Once opened
 * successfully, the database is cached, so you can call this method every time you need to
 * write to the database. Make sure to call {@link #close} when you no longer need it.
 * <p>//from  w  ww  .  j av  a2s  . co  m
 * Errors such as bad permissions or a full disk may cause this operation to fail, but future
 * attempts may succeed if the problem is fixed.
 * </p>
 * 
 * @throws SQLiteException if the database cannot be opened for writing
 * @return a read/write database object valid until {@link #close} is called
 */
public synchronized SQLiteDatabase getWritableDatabase() {
    // adding if the database is locked or not
    if (mDatabase != null && mDatabase.isOpen() && !mDatabase.isReadOnly() && !mHandler.isLocked()) {
        return mDatabase; // The database is already open for business
    }

    if (mHandler == null)
        mHandler = ((MyStatus) mContext).getCacheWordHandler();
    if (mHandler.isLocked())
        throw new SQLiteException("Database locked. Decryption key unavailable.");

    if (mIsInitializing) {
        throw new IllegalStateException("getWritableDatabase called recursively");
    }

    // If we have a read-only database open, someone could be using it
    // (though they shouldn't), which would cause a lock to be held on
    // the file, and our attempts to open the database read-write would
    // fail waiting for the file lock. To prevent that, we acquire the
    // lock on the read-only database, which shuts out other users.

    boolean success = false;
    SQLiteDatabase db = null;
    // if (mDatabase != null) mDatabase.lock();
    try {
        mIsInitializing = true;
        if (mName == null) {
            db = SQLiteDatabase.create(null, encodeRawKey(mHandler.getEncryptionKey()));
        } else {
            db = SQLiteDatabase.openOrCreateDatabase(mPath + File.separator + mName,
                    encodeRawKey(mHandler.getEncryptionKey()), mFactory);
            // db = mContext.openOrCreateDatabase(mName, 0, mFactory);
        }

        int version = db.getVersion();
        if (version != mNewVersion) {
            db.beginTransaction();
            try {
                if (version == 0) {
                    onCreate(db);
                } else {
                    onUpgrade(db, version, mNewVersion);
                }
                db.setVersion(mNewVersion);
                db.setTransactionSuccessful();
            } finally {
                db.endTransaction();
            }
        }

        onOpen(db);
        success = true;
        return db;
    } finally {
        mIsInitializing = false;
        if (success) {
            if (mDatabase != null) {
                try {
                    mDatabase.close();
                } catch (Exception e) {
                }
                // mDatabase.unlock();
            }
            mDatabase = db;
        } else {
            // if (mDatabase != null) mDatabase.unlock();
            if (db != null)
                db.close();
        }
    }
}

From source file:android.database.DatabaseUtils.java

private static final void readExceptionFromParcel(Parcel reply, String msg, int code) {
    switch (code) {
    case 2:/*from  w w  w  . j  a  v a  2s  . c  om*/
        throw new IllegalArgumentException(msg);
    case 3:
        throw new UnsupportedOperationException(msg);
    case 4:
        throw new SQLiteAbortException(msg);
    case 5:
        throw new SQLiteConstraintException(msg);
    case 6:
        throw new SQLiteDatabaseCorruptException(msg);
    case 7:
        throw new SQLiteFullException(msg);
    case 8:
        throw new SQLiteDiskIOException(msg);
    case 9:
        throw new SQLiteException(msg);
    default:
        reply.readException(code, msg);
    }
}

From source file:edu.washington.cs.mystatus.odk.database.ODKSQLiteOpenHelper.java

/**
 * Create and/or open a database. This will be the same object returned by
 * {@link #getWritableDatabase} unless some problem, such as a full disk, requires the database
 * to be opened read-only. In that case, a read-only database object will be returned. If the
 * problem is fixed, a future call to {@link #getWritableDatabase} may succeed, in which case
 * the read-only database object will be closed and the read/write object will be returned in
 * the future.//from   w w w  .  j  ava 2s. co  m
 * 
 * @throws SQLiteException if the database cannot be opened
 * @return a database object valid until {@link #getWritableDatabase} or {@link #close} is
 *         called.
 */
public synchronized SQLiteDatabase getReadableDatabase() {
    if (mDatabase != null && mDatabase.isOpen()) {
        return mDatabase; // The database is already open for business
    }

    if (mIsInitializing) {
        throw new IllegalStateException("getReadableDatabase called recursively");
    }

    // if the cacheword is locked throw exception
    if (mHandler == null)
        mHandler = ((MyStatus) mContext).getCacheWordHandler();

    // work around for now...
    // @CD
    Base64Wrapper b64w = null;
    try {
        b64w = new Base64Wrapper();
    } catch (ClassNotFoundException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    byte[] encryption_key = null;
    if (mHandler.isLocked()) {
        SharedPreferences prefs = mContext.getSharedPreferences("mystatus", mContext.MODE_PRIVATE);
        String key = prefs.getString("encoded_key", null);
        if (key != null)
            encryption_key = b64w.decode(key);
    }
    //throw new SQLiteException("Database locked. Decryption key unavailable.");

    try {
        return getWritableDatabase();
    } catch (SQLiteException e) {
        if (mName == null)
            throw e; // Can't open a temp database read-only!
        Log.e(t, "Couldn't open " + mName + " for writing (will try read-only):", e);
    }

    SQLiteDatabase db = null;
    try {
        mIsInitializing = true;
        String path = mPath + File.separator + mName;
        // mContext.getDatabasePath(mName).getPath();
        // allow open readable database
        if (mHandler.isLocked() && encryption_key != null)
            db = SQLiteDatabase.openDatabase(path, encodeRawKey(encryption_key), mFactory,
                    SQLiteDatabase.OPEN_READONLY);
        else
            db = SQLiteDatabase.openDatabase(path, encodeRawKey(mHandler.getEncryptionKey()), mFactory,
                    SQLiteDatabase.OPEN_READONLY);

        if (db.getVersion() != mNewVersion) {
            throw new SQLiteException("Can't upgrade read-only database from version " + db.getVersion()
                    + " to " + mNewVersion + ": " + path);
        }

        onOpen(db);
        Log.w(t, "Opened " + mName + " in read-only mode");
        mDatabase = db;
        return mDatabase;
    } finally {
        mIsInitializing = false;
        if (db != null && db != mDatabase)
            db.close();
    }
}

From source file:com.shinymayhem.radiopresets.ActivityMain.java

@Override
public void onDialogPositiveClick(View view) {
    // User touched the dialog's positive button
    if (LOCAL_LOGD)
        log("Add station confirmed", "d");
    EditText titleView = (EditText) view.findViewById(R.id.station_title);
    EditText urlView = (EditText) view.findViewById(R.id.station_url);

    //int preset = 1; 
    String title = titleView.getText().toString().trim();
    String url = urlView.getText().toString().trim();
    boolean valid = ServiceRadioPlayer.validateUrl(url);
    if (valid) {/*from   www  . jav  a 2 s.  c om*/
        ContentValues values = new ContentValues();
        //values.put(DbContractRadio.EntryStation.COLUMN_NAME_PRESET_NUMBER, preset);
        values.put(DbContractRadio.EntryStation.COLUMN_NAME_TITLE, title);
        values.put(DbContractRadio.EntryStation.COLUMN_NAME_URL, url);
        Uri uri = getContentResolver().insert(ContentProviderRadio.CONTENT_URI_STATIONS, values);
        int id = (int) ContentUris.parseId(uri);
        if (id == -1) {
            throw new SQLiteException("Insert failed");
        }
        if (LOCAL_LOGV)
            log("uri of addition:" + uri, "v");
        this.updateDetails();
    } else {
        //FIXME code duplication in FragmentStations
        if (LOCAL_LOGV)
            log("URL " + url + " not valid", "v");
        LayoutInflater inflater = LayoutInflater.from(this);
        final View editView = inflater.inflate(R.layout.dialog_station_details, null);
        titleView = ((EditText) editView.findViewById(R.id.station_title));
        titleView.setText(title);
        urlView = ((EditText) editView.findViewById(R.id.station_url));
        urlView.setText(url);
        urlView.requestFocus();
        AlertDialog.Builder builder = new AlertDialog.Builder(this.getContext());
        builder.setView(editView);
        builder.setPositiveButton(R.string.edit_station, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                onDialogPositiveClick(editView);
            }
        });
        builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                onDialogNegativeClick();

            }
        });
        builder.setTitle("URL appears invalid. Try again");
        builder.show();
        //TODO
    }
}

From source file:io.requery.android.database.sqlite.SQLiteConnection.java

private void setLocaleFromConfiguration() {
    // Register the localized collators.
    final String newLocale = mConfiguration.locale.toString();
    nativeRegisterLocalizedCollators(mConnectionPtr, newLocale);

    // If the database is read-only, we cannot modify the android metadata table
    // or existing indexes.
    if (mIsReadOnlyConnection) {
        return;/*from w w  w .j  a va 2 s  .com*/
    }

    try {
        // Ensure the android metadata table exists.
        execute("CREATE TABLE IF NOT EXISTS android_metadata (locale TEXT)", null, null);

        // Check whether the locale was actually changed.
        final String oldLocale = executeForString(
                "SELECT locale FROM android_metadata " + "UNION SELECT NULL ORDER BY locale DESC LIMIT 1", null,
                null);
        if (oldLocale != null && oldLocale.equals(newLocale)) {
            return;
        }

        // Go ahead and update the indexes using the new locale.
        execute("BEGIN", null, null);
        boolean success = false;
        try {
            execute("DELETE FROM android_metadata", null, null);
            execute("INSERT INTO android_metadata (locale) VALUES(?)", new Object[] { newLocale }, null);
            execute("REINDEX LOCALIZED", null, null);
            success = true;
        } finally {
            execute(success ? "COMMIT" : "ROLLBACK", null, null);
        }
    } catch (RuntimeException ex) {
        throw new SQLiteException(
                "Failed to change locale for db '" + mConfiguration.label + "' to '" + newLocale + "'.");
    }
}

From source file:com.shinymayhem.radiopresets.ServiceRadioPlayer.java

protected void previousPreset() {
    if (LOCAL_LOGV)
        log("previousPreset()", "v");
    mPreset--;/*from  w ww .ja  v a 2  s. c o  m*/
    if (mPreset <= 0) {
        ////call() not supported until api 11
        //Uri maxUri = ContentProviderRadio.CONTENT_URI_PRESETS_MAX;
        //Bundle values = getContentResolver().call(maxUri, "getMaxPresetNumber", null, null);  
        //mPreset = values.getInt(DbContractRadio.EntryStation.COLUMN_NAME_PRESET_NUMBER);
        mPreset = getMaxPresetNumber();
        if (mPreset == 0) //no stations? 
        {
            log("No stations found to play", "w");
            return; //TODO notify user?
        }
        //play();
        //return;
    }
    //find out if the desired station exists
    Uri uri = Uri.parse(ContentProviderRadio.CONTENT_URI_PRESETS.toString() + "/" + String.valueOf(mPreset));
    String[] projection = { DbContractRadio.EntryStation.COLUMN_NAME_PRESET_NUMBER };
    String selection = null;
    String[] selectionArgs = null;
    String sortOrder = DbContractRadio.EntryStation.COLUMN_NAME_PRESET_NUMBER;
    Cursor cursor = getContentResolver().query(uri, projection, selection, selectionArgs, sortOrder);
    int count = cursor.getCount();
    if (count < 1) {
        log("No station found below current, but not at 0", "e");
        throw new SQLiteException("No station found below current, but not 0"); //TODO find correct exception to throw, or handle this some other way
    } else {
        cursor.moveToFirst();
        mPreset = (int) cursor
                .getLong(cursor.getColumnIndexOrThrow(DbContractRadio.EntryStation.COLUMN_NAME_PRESET_NUMBER));
        if (LOCAL_LOGV)
            log("decremented preset, playing " + String.valueOf(mPreset), "v");
        play();
    }
    cursor.close();
}

From source file:io.requery.android.database.sqlite.SQLiteConnection.java

private void bindArguments(PreparedStatement statement, Object[] bindArgs) {
    final int count = bindArgs != null ? bindArgs.length : 0;
    if (count != statement.mNumParameters) {
        String message = "Expected " + statement.mNumParameters + " bind arguments but " + count
                + " were provided.";
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            throw new SQLiteBindOrColumnIndexOutOfRangeException(message);
        } else {//from   www.j  a va2 s .c  o m
            throw new SQLiteException(message);
        }
    }
    if (count == 0) {
        return;
    }

    final long statementPtr = statement.mStatementPtr;
    for (int i = 0; i < count; i++) {
        final Object arg = bindArgs[i];
        switch (getTypeOfObject(arg)) {
        case Cursor.FIELD_TYPE_NULL:
            nativeBindNull(mConnectionPtr, statementPtr, i + 1);
            break;
        case Cursor.FIELD_TYPE_INTEGER:
            nativeBindLong(mConnectionPtr, statementPtr, i + 1, ((Number) arg).longValue());
            break;
        case Cursor.FIELD_TYPE_FLOAT:
            nativeBindDouble(mConnectionPtr, statementPtr, i + 1, ((Number) arg).doubleValue());
            break;
        case Cursor.FIELD_TYPE_BLOB:
            nativeBindBlob(mConnectionPtr, statementPtr, i + 1, (byte[]) arg);
            break;
        case Cursor.FIELD_TYPE_STRING:
        default:
            if (arg instanceof Boolean) {
                // Provide compatibility with legacy applications which may pass
                // Boolean values in bind args.
                nativeBindLong(mConnectionPtr, statementPtr, i + 1, (Boolean) arg ? 1 : 0);
            } else {
                nativeBindString(mConnectionPtr, statementPtr, i + 1, arg.toString());
            }
            break;
        }
    }
}

From source file:io.requery.android.database.sqlite.SQLiteConnection.java

private void throwIfStatementForbidden(PreparedStatement statement) {
    if (mOnlyAllowReadOnlyOperations && !statement.mReadOnly) {
        throw new SQLiteException("Cannot execute this statement because it "
                + "might modify the database but the connection is read-only.");
    }//w w w.j  av  a  2s .c  o  m
}

From source file:com.shinymayhem.radiopresets.ServiceRadioPlayer.java

protected void setStationData(int preset) {
    Uri uri = Uri.parse(ContentProviderRadio.CONTENT_URI_PRESETS.toString() + "/" + String.valueOf(preset));
    String[] projection = { DbContractRadio.EntryStation.COLUMN_NAME_PRESET_NUMBER,
            DbContractRadio.EntryStation.COLUMN_NAME_TITLE, DbContractRadio.EntryStation.COLUMN_NAME_URL };
    String selection = null;/*w ww.  j a  va 2 s.co m*/
    String[] selectionArgs = null;
    String sortOrder = DbContractRadio.EntryStation.COLUMN_NAME_PRESET_NUMBER;
    Cursor cursor = getContentResolver().query(uri, projection, selection, selectionArgs, sortOrder);
    int count = cursor.getCount();
    if (count > 1) {
        log("Duplicate preset detected", "w");
    }
    if (count < 1) {
        log("Selected preset not found", "e");
        throw new SQLiteException("Selected preset not found"); //TODO find correct exception to throw, or handle this some other way
    } else {
        cursor.moveToFirst();
        mPreset = (int) cursor
                .getLong(cursor.getColumnIndexOrThrow(DbContractRadio.EntryStation.COLUMN_NAME_PRESET_NUMBER));
        mTitle = cursor.getString(cursor.getColumnIndexOrThrow(DbContractRadio.EntryStation.COLUMN_NAME_TITLE));
        mUrl = cursor.getString(cursor.getColumnIndexOrThrow(DbContractRadio.EntryStation.COLUMN_NAME_URL));
        mArtist = getResources().getString(R.string.loading_artist);
        mSong = getResources().getString(R.string.loading_song);
    }
    cursor.close();
}