Example usage for android.database.sqlite SQLiteDatabase openDatabase

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

Introduction

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

Prototype

public static SQLiteDatabase openDatabase(@NonNull String path, @Nullable CursorFactory factory,
        @DatabaseOpenFlags int flags) 

Source Link

Document

Open the database according to the flags #OPEN_READWRITE #OPEN_READONLY #CREATE_IF_NECESSARY and/or #NO_LOCALIZED_COLLATORS .

Usage

From source file:de.arcus.playmusiclib.PlayMusicManager.java

/**
 * Copies the database to a temp directory and opens it
 * @throws NoSuperUserException No super user permissions
 * @throws de.arcus.playmusiclib.exceptions.CouldNotOpenDatabaseException Could not open the database
 *///from   ww  w.ja va 2s.c o  m
private void loadDatabase() throws NoSuperUserException, CouldNotOpenDatabaseException {
    // Ask for super user
    if (!SuperUser.askForPermissions())
        throw new NoSuperUserException();

    // Close the database
    closeDatabase();

    // Copy the database to the temp folder
    if (!SuperUserTools.fileCopy(getDatabasePath(), getTempDatabasePath()))
        throw new CouldNotOpenDatabaseException();

    // Opens the database
    try {
        mDatabase = SQLiteDatabase.openDatabase(getTempDatabasePath(), null, SQLiteDatabase.OPEN_READONLY);
    } catch (SQLException e) {
        throw new CouldNotOpenDatabaseException();
    }
}

From source file:uk.org.rivernile.edinburghbustracker.android.Application.java

/**
 * Download the stop database from the server and put it in the
 * application's working data directory.
 *
 * @param context The context to use this method with.
 * @param url The URL of the bus stop database to download.
 *//*from  w  w w .j ava 2 s.c o m*/
private static void updateStopsDB(final Context context, final String url, final String checksum) {
    if (context == null || url == null || url.length() == 0 || checksum == null || checksum.length() == 0)
        return;
    try {
        // Connect to the server.
        final URL u = new URL(url);
        final HttpURLConnection con = (HttpURLConnection) u.openConnection();
        final InputStream in = con.getInputStream();

        // Make sure the URL is what we expect.
        if (!u.getHost().equals(con.getURL().getHost())) {
            in.close();
            con.disconnect();
            return;
        }

        // The location the file should be downloaded to.
        final File temp = context.getDatabasePath(BusStopDatabase.STOP_DB_NAME + "_temp");
        // The eventual destination of the file.
        final File dest = context.getDatabasePath(BusStopDatabase.STOP_DB_NAME);
        final FileOutputStream out = new FileOutputStream(temp);

        // Get the file from the server.
        byte[] buf = new byte[1024];
        int len;
        while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }

        // Make sure the stream is flushed then close resources and
        // disconnect.
        out.flush();
        out.close();
        in.close();
        con.disconnect();

        // Do a MD5 checksum on the downloaded file. Make sure it matches
        // what the server reported.
        if (!md5Checksum(temp).equalsIgnoreCase(checksum)) {
            // If it doesn't match, delete the downloaded file.
            temp.delete();
            return;
        }

        try {
            // Open the temp database and execute the index operation on it.
            final SQLiteDatabase db = SQLiteDatabase.openDatabase(temp.getAbsolutePath(), null,
                    SQLiteDatabase.OPEN_READWRITE);
            BusStopDatabase.setUpIndexes(db);
            db.close();
        } catch (SQLiteException e) {
            // If we couldn't create the index, continue anyway. The user
            // will still be able to use the database, it will just run
            // slowly if they want route lines.
        }

        // Close a currently open database. Delete the old database then
        // move the downloaded file in to its place. Do this while
        // synchronized to make sure noting else uses the database in this
        // time.
        final BusStopDatabase bsd = BusStopDatabase.getInstance(context.getApplicationContext());
        synchronized (bsd) {
            try {
                bsd.getReadableDatabase().close();
            } catch (SQLiteException e) {
                // Nothing to do here. Assume it's already closed.
            }

            dest.delete();
            temp.renameTo(dest);
        }

        // Delete the associated journal file because we no longer need it.
        final File journalFile = context.getDatabasePath(BusStopDatabase.STOP_DB_NAME + "_temp-journal");
        if (journalFile.exists())
            journalFile.delete();

        // Alert the user that the database has been updated.
        Looper.prepare();
        Toast.makeText(context, R.string.bus_stop_db_updated, Toast.LENGTH_LONG).show();
        Looper.loop();
    } catch (MalformedURLException e) {
    } catch (IOException e) {
    }
}

From source file:com.androzic.location.LocationService.java

private void openDatabase() {
    Androzic application = Androzic.getApplication();
    if (application.dataPath == null) {
        Log.e(TAG, "Data path is null");
        errorMsg = "Data path is null";
        errorTime = System.currentTimeMillis();
        updateNotification();/*from   w w  w  .j a v a2s  . c  o  m*/
        return;
    }
    File dir = new File(application.dataPath);
    if (!dir.exists() && !dir.mkdirs()) {
        Log.e(TAG, "Failed to create data folder");
        errorMsg = "Failed to create data folder";
        errorTime = System.currentTimeMillis();
        updateNotification();
        return;
    }
    File path = new File(dir, "myTrack.db");
    try {
        trackDB = SQLiteDatabase.openDatabase(path.getAbsolutePath(), null, SQLiteDatabase.OPEN_READWRITE
                | SQLiteDatabase.CREATE_IF_NECESSARY | SQLiteDatabase.NO_LOCALIZED_COLLATORS);
        Cursor cursor = trackDB.rawQuery("SELECT DISTINCT tbl_name FROM sqlite_master WHERE tbl_name = 'track'",
                null);
        if (cursor.getCount() == 0) {
            trackDB.execSQL(
                    "CREATE TABLE track (_id INTEGER PRIMARY KEY, latitude REAL, longitude REAL, code INTEGER, elevation REAL, speed REAL, track REAL, accuracy REAL, datetime INTEGER)");
        }
        cursor.close();
    } catch (SQLiteException e) {
        trackDB = null;
        Log.e(TAG, "openDatabase", e);
        errorMsg = "Failed to open DB";
        errorTime = System.currentTimeMillis();
        updateNotification();
    }
}

From source file:com.ideateam.plugin.DownloadDB.java

private void ReplaceDB() {

    Log.d(TAG, "..Get physical DB name and path. zipPath " + zipPath);

    String dbPath = zipPath.substring(0, zipPath.lastIndexOf("/")) + "/app_database/";
    SQLiteDatabase master_db = null;//from  ww w  .  ja  v a 2 s . com
    String field = "path";

    Log.d(TAG, dbPath + "Databases.db");
    File file = new File(dbPath + "Databases.db");

    if (!file.exists()) {

        Log.d(TAG, "Databases.db not found");
        field = "id";
        dbPath = zipPath.substring(0, zipPath.lastIndexOf("/")) + "/app_webview/databases/";
    }

    try {
        master_db = SQLiteDatabase.openDatabase(dbPath + "Databases.db", null, SQLiteDatabase.OPEN_READONLY);
    } catch (Exception e) {

    }

    if (master_db != null) {
        Cursor c = master_db.rawQuery("SELECT origin, " + field + " FROM Databases WHERE name='" + dbName + "'",
                null);
        c.moveToFirst();

        cordovaDBPath = dbPath + c.getString(0) + "/";
        cordovaDBName = c.getString(1);

        if (field == "id") {
            field += ".db";
        }

        c.close();
        master_db.close();

        Log.d(TAG, ": " + cordovaDBPath + cordovaDBName);

    }
}

From source file:com.markuspage.android.atimetracker.Tasks.java

@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
    case ADD_TASK:
        return openNewTaskDialog();
    case EDIT_TASK:
        return openEditTaskDialog();
    case DELETE_TASK:
        return openDeleteTaskDialog();
    case CHANGE_VIEW:
        return openChangeViewDialog();
    case HELP:/*  ww w. j  av  a  2s .co m*/
        return openAboutDialog();
    case SUCCESS_DIALOG:
        operationSucceed = new AlertDialog.Builder(Tasks.this).setTitle(R.string.success)
                .setIcon(android.R.drawable.stat_notify_sdcard).setMessage(exportMessage)
                .setPositiveButton(android.R.string.ok, null).create();
        return operationSucceed;
    case ERROR_DIALOG:
        operationFailed = new AlertDialog.Builder(Tasks.this).setTitle(R.string.failure)
                .setIcon(android.R.drawable.stat_notify_sdcard).setMessage(exportMessage)
                .setPositiveButton(android.R.string.ok, null).create();
        return operationFailed;
    case PROGRESS_DIALOG:
        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("Copying records...");
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setCancelable(false);
        return progressDialog;
    case MORE:
        return new AlertDialog.Builder(Tasks.this)
                .setItems(R.array.moreMenu, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        DBBackup backup;
                        System.err.println("IN CLICK");
                        switch (which) {
                        case 0: // CHANGE_VIEW:
                            showDialog(CHANGE_VIEW);
                            break;
                        case 1: // EXPORT_VIEW:
                            String fname = export();
                            perform(fname, R.string.export_csv_success, R.string.export_csv_fail);
                            break;
                        case 2: // COPY DB TO SD
                            showDialog(Tasks.PROGRESS_DIALOG);
                            if (new File(dbBackup).exists()) {
                                // Find the database
                                SQLiteDatabase backupDb = SQLiteDatabase.openDatabase(dbBackup, null,
                                        SQLiteDatabase.OPEN_READWRITE);
                                SQLiteDatabase appDb = SQLiteDatabase.openDatabase(dbPath, null,
                                        SQLiteDatabase.OPEN_READONLY);
                                backup = new DBBackup(Tasks.this, progressDialog);
                                backup.execute(appDb, backupDb);
                            } else {
                                InputStream in = null;
                                OutputStream out = null;

                                try {
                                    in = new BufferedInputStream(new FileInputStream(dbPath));
                                    out = new BufferedOutputStream(new FileOutputStream(dbBackup));
                                    for (int c = in.read(); c != -1; c = in.read()) {
                                        out.write(c);
                                    }
                                } catch (Exception ex) {
                                    Logger.getLogger(Tasks.class.getName()).log(Level.SEVERE, null, ex);
                                    exportMessage = ex.getLocalizedMessage();
                                    showDialog(ERROR_DIALOG);
                                } finally {
                                    try {
                                        if (in != null) {
                                            in.close();
                                        }
                                    } catch (IOException ignored) {
                                    }
                                    try {
                                        if (out != null) {
                                            out.close();
                                        }
                                    } catch (IOException ignored) {
                                    }
                                }
                            }
                            break;
                        case 3: // RESTORE FROM BACKUP
                            showDialog(Tasks.PROGRESS_DIALOG);
                            SQLiteDatabase backupDb = SQLiteDatabase.openDatabase(dbBackup, null,
                                    SQLiteDatabase.OPEN_READONLY);
                            SQLiteDatabase appDb = SQLiteDatabase.openDatabase(dbPath, null,
                                    SQLiteDatabase.OPEN_READWRITE);
                            backup = new DBBackup(Tasks.this, progressDialog);
                            backup.execute(backupDb, appDb);
                            break;
                        case 4: // PREFERENCES
                            Intent intent = new Intent(Tasks.this, Settings.class);
                            startActivityForResult(intent, PREFERENCES);
                            break;
                        case 5: // HELP:
                            showDialog(HELP);
                            break;
                        default:
                            break;
                        }
                    }
                }).create();
    }
    return null;
}

From source file:com.modestmaps.providers.connection.TileBaseHelper.java

private boolean checkDatabase() {
    System.out.println("1. checkDatabase()..");
    SQLiteDatabase checkableDatabase = null;
    boolean localDatabaseExists = false;
    //String checkableDatabase = null; //dummy null String..
    System.out.println("1. null checkableDatabase created..!!");
    try {/*w w  w  .  j a v a  2  s . c o  m*/
        checkableDatabase = SQLiteDatabase.openDatabase(DBPATH + DBNAME, null, SQLiteDatabase.OPEN_READONLY);

    } catch (Exception e) {
        System.out.println("1. database doesnt exist/is corrupt..so copy from server.."); //our database doesn't exist, so we'll return false below.
        System.out.println("Copying from: " + serverADD);
        localDatabaseExists = false;
        //checkableDatabase.close();
        checkableDatabase = null;
    }
    if (checkableDatabase != null) {
        localDatabaseExists = true;
        System.out.println("1. huh?? database exists?? " + localDatabaseExists);
        checkableDatabase.close();
    }

    System.out.println("2. returning checkableDatabase().." + localDatabaseExists);
    return localDatabaseExists;
}

From source file:com.modestmaps.providers.connection.TileBaseHelper.java

public void openDatabase() throws SQLException {
    System.out.println("1. openDatabase()..");
    tileDB = SQLiteDatabase.openDatabase(DBPATH + DBNAME, null, SQLiteDatabase.OPEN_READWRITE);

}

From source file:org.lastmilehealth.collect.android.tasks.BluetoothService.java

private void clearForms() {
    SQLiteDatabase db = SQLiteDatabase.openDatabase(Collect.FORMS_DB_PATH, null, SQLiteDatabase.OPEN_READWRITE);
    db.execSQL("delete from forms");
    db.close();/*www  .j a  v  a  2 s .c  o m*/

    deletePreferences();
    try {
        org.apache.commons.io.FileUtils.cleanDirectory(new File(Collect.FORMS_PATH));
        org.apache.commons.io.FileUtils.cleanDirectory(new File(Collect.ROLES_PATH));
    } catch (Exception e) {
    }
}

From source file:org.lastmilehealth.collect.android.tasks.BluetoothService.java

private void instancesProcessing() {
    //fill db with new values
    String dbpath = Collect.TMP_PATH + "/instances.db";
    SQLiteDatabase db = SQLiteDatabase.openDatabase(dbpath, null, SQLiteDatabase.OPEN_READONLY);
    Cursor cursor = db.query(InstanceProvider.INSTANCES_TABLE_NAME, null, null, null, null, null, null);
    Log.d("~", "cursor.getCount(): " + cursor.getCount());

    cursor.moveToPosition(-1);/* w  ww . jav a  2s  .  co m*/
    while (cursor.moveToNext()) {
        String newInstanceName = cursor
                .getString(cursor.getColumnIndex(InstanceProviderAPI.InstanceColumns.DISPLAY_NAME));
        String instanceFilePath = cursor
                .getString(cursor.getColumnIndex(InstanceProviderAPI.InstanceColumns.INSTANCE_FILE_PATH));
        String newFilePath;

        if (new File(instanceFilePath).exists()) { //instance with this path already exist, rare case but not impossible
            newFilePath = getInstanceFilePath(instanceFilePath, 1);
            Log.d(TAG, "instance already exists, new path: " + newFilePath);

            String num = newFilePath.substring(newFilePath.lastIndexOf("(") + 1, newFilePath.lastIndexOf(")"));
            newInstanceName += "(" + num + ")";
            //Log.d(TAG, "newInstanceName: "+newInstanceName);

            final String fromName = instanceFilePath.substring(instanceFilePath.lastIndexOf("instances/") + 10);
            final String toName = newFilePath.substring(instanceFilePath.lastIndexOf("instances/") + 10);

            //raname file in tmp folder to prepare for copy direcory
            try {
                Log.d(TAG, "rename " + fromName + " to " + toName);
                org.apache.commons.io.FileUtils.copyFile(new File(Collect.TMP_PATH, fromName),
                        new File(Collect.TMP_PATH, toName));
                org.apache.commons.io.FileUtils.deleteQuietly(new File(Collect.TMP_PATH, fromName));
            } catch (Exception e) {
            }
        } else {
            newFilePath = new File(Collect.INSTANCES_PATH,
                    instanceFilePath.substring(instanceFilePath.lastIndexOf("/"))).getAbsolutePath();
            Log.d(TAG, "not exist, new path " + newFilePath);
        }

        String submissionUri = null;
        if (!cursor.isNull(cursor.getColumnIndex(InstanceProviderAPI.InstanceColumns.SUBMISSION_URI))) {
            submissionUri = cursor
                    .getString(cursor.getColumnIndex(InstanceProviderAPI.InstanceColumns.SUBMISSION_URI));
        }

        //add to db with new name, it it was duplicated
        ContentValues values = new ContentValues();
        values.put(InstanceProviderAPI.InstanceColumns.DISPLAY_NAME, newInstanceName);
        values.put(InstanceProviderAPI.InstanceColumns.SUBMISSION_URI, submissionUri);
        values.put(InstanceProviderAPI.InstanceColumns.INSTANCE_FILE_PATH, newFilePath);
        values.put(InstanceProviderAPI.InstanceColumns.JR_FORM_ID,
                cursor.getString(cursor.getColumnIndex(InstanceProviderAPI.InstanceColumns.JR_FORM_ID)));
        values.put(InstanceProviderAPI.InstanceColumns.JR_VERSION,
                cursor.getString(cursor.getColumnIndex(InstanceProviderAPI.InstanceColumns.JR_VERSION)));
        values.put(InstanceProviderAPI.InstanceColumns.STATUS,
                cursor.getString(cursor.getColumnIndex(InstanceProviderAPI.InstanceColumns.STATUS)));
        values.put(InstanceProviderAPI.InstanceColumns.CAN_EDIT_WHEN_COMPLETE, cursor
                .getString(cursor.getColumnIndex(InstanceProviderAPI.InstanceColumns.CAN_EDIT_WHEN_COMPLETE)));

        Log.d(TAG, "insert new instance record: " + newInstanceName + " with path :" + newFilePath);
        Collect.getInstance().getContentResolver().insert(InstanceProviderAPI.InstanceColumns.CONTENT_URI,
                values);
    }
    cursor.close();
    db.close();

    //copy directory after deleting metadata, clear all temporary data
    org.apache.commons.io.FileUtils.deleteQuietly(new File(Collect.TMP_PATH, "instances.db"));
    org.apache.commons.io.FileUtils.deleteQuietly(new File(Collect.ZIP_PATH));
    try {
        org.apache.commons.io.FileUtils.copyDirectory(new File(Collect.TMP_PATH),
                new File(Collect.INSTANCES_PATH));
        org.apache.commons.io.FileUtils.deleteDirectory(new File(Collect.TMP_PATH));
    } catch (Exception e) {
    }
}

From source file:me.piebridge.bible.Bible.java

private boolean checkVersionMeta(File file, String version) {
    SQLiteDatabase metadata = null;/*from  ww  w . j a va 2 s  . c  om*/
    try {
        metadata = SQLiteDatabase.openDatabase(file.getAbsolutePath(), null,
                SQLiteDatabase.OPEN_READONLY | SQLiteDatabase.NO_LOCALIZED_COLLATORS);
        String dataversion = version.replace("demo", "");
        if (!versionFullnames.containsKey(version)) {
            versionFullnames.put(version, getVersionMetadata("fullname", metadata, dataversion));
        }
        if (!versionNames.containsKey(version)) {
            versionNames.put(version, getVersionMetadata("name", metadata, dataversion));
        }
        versionDates.put(version, getVersionMetadata("date", metadata, "0"));
        // setMetadata(metadata, dataversion, false);
        return true;
    } catch (Exception e) {
        try {
            file.delete();
        } catch (Exception f) {
        }
        return false;
    } finally {
        if (metadata != null) {
            metadata.close();
        }
    }
}