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:com.awt.supark.ParkingTimerService.java

private void loadDatabase() {
    try {//  w  w  w.j  a  va2  s .  com
        db = SQLiteDatabase.openDatabase(getApplicationContext().getFilesDir().getPath() + "/carDB.db", null,
                SQLiteDatabase.CREATE_IF_NECESSARY);
        Log.i("Service", "DB loaded successfully...");
    } catch (Exception e) {
        Log.i("Service", "DB read error");
        Log.i("Service", "Exception: " + e.toString());
    }
}

From source file:com.esri.squadleader.model.GeoPackageReader.java

/**
 * Reads the tables in a GeoPackage, makes a layer from each table, and returns a list containing
 * those layers./*  w ww.j  av  a2s  . c om*/
 *
 * @param gpkgPath       the full path to the .gpkg file.
 * @param sr             the spatial reference to which any raster layers should be projected, typically the
 *                       spatial reference of your map.
 * @param showVectors    if true, this method will include the GeoPackage's vector layers.
 * @param showRasters    if true, this method will include the GeoPackage's raster layer.
 * @param rasterRenderer the renderer to be used for raster layers. One simple option is an RGBRenderer.
 * @param markerRenderer the renderer to be used for point layers.
 * @param lineRenderer   the renderer to be used for polyline layers.
 * @param fillRenderer   the renderer to be used for polygon layers.
 * @return a list of the layers created for all tables in the GeoPackage.
 * @throws IOException if gpkgPath cannot be read. Possible reasons include the file not
 *                     existing, failure to request READ_EXTERNAL_STORAGE or
 *                     WRITE_EXTERNAL_STORAGE permission, or the GeoPackage containing an
 *                     invalid spatial reference.
 */
public List<Layer> readGeoPackageToLayerList(String gpkgPath, SpatialReference sr, boolean showVectors,
        boolean showRasters, RasterRenderer rasterRenderer, Renderer markerRenderer, Renderer lineRenderer,
        Renderer fillRenderer) throws IOException {
    List<Layer> layers = new ArrayList<Layer>();

    if (showRasters) {
        // Check to see if there are any rasters before loading them
        SQLiteDatabase sqliteDb = null;
        Cursor cursor = null;
        try {
            sqliteDb = SQLiteDatabase.openDatabase(gpkgPath, null, SQLiteDatabase.OPEN_READONLY);
            cursor = sqliteDb.rawQuery("SELECT COUNT(*) FROM gpkg_contents WHERE data_type = ?",
                    new String[] { "tiles" });
            if (cursor.moveToNext()) {
                if (0 < cursor.getInt(0)) {
                    cursor.close();
                    sqliteDb.close();
                    FileRasterSource src = new FileRasterSource(gpkgPath);
                    rasterSources.add(src);
                    if (null != sr) {
                        src.project(sr);
                    }
                    RasterLayer rasterLayer = new RasterLayer(src);
                    rasterLayer.setRenderer(rasterRenderer);
                    rasterLayer
                            .setName((gpkgPath.contains("/") ? gpkgPath.substring(gpkgPath.lastIndexOf("/") + 1)
                                    : gpkgPath) + " (raster)");
                    layers.add(rasterLayer);
                }
            }
        } catch (Throwable t) {
            Log.e(TAG, "Could not read raster(s) from GeoPackage", t);
        } finally {
            if (null != cursor) {
                cursor.close();
            }
            if (null != sqliteDb) {
                sqliteDb.close();
            }
        }
    }

    if (showVectors) {
        Geopackage gpkg;
        try {
            gpkg = new Geopackage(gpkgPath);
        } catch (RuntimeException ex) {
            throw new IOException(null != ex.getMessage() && ex.getMessage().contains("unknown wkt")
                    ? "Geopackage " + gpkgPath + " contains an invalid spatial reference."
                    : null, ex);
        }
        geopackages.add(gpkg);
        List<GeopackageFeatureTable> tables = gpkg.getGeopackageFeatureTables();
        if (0 < tables.size()) {
            //First pass: polygons and unknowns
            HashSet<Geometry.Type> types = new HashSet<Geometry.Type>();
            types.add(Geometry.Type.ENVELOPE);
            types.add(Geometry.Type.POLYGON);
            types.add(Geometry.Type.UNKNOWN);
            layers.addAll(getTablesAsLayers(tables, types, fillRenderer));

            //Second pass: lines
            types.clear();
            types.add(Geometry.Type.LINE);
            types.add(Geometry.Type.POLYLINE);
            layers.addAll(getTablesAsLayers(tables, types, lineRenderer));

            //Third pass: points
            types.clear();
            types.add(Geometry.Type.MULTIPOINT);
            types.add(Geometry.Type.POINT);
            layers.addAll(getTablesAsLayers(tables, types, markerRenderer));
        }
    }

    return layers;
}

From source file:com.filemanager.free.activities.DbViewer.java

private void load(final File file) {
    new Thread(new Runnable() {
        @Override//w  w  w . j av a2 s.c om
        public void run() {
            if (!file.canRead() && rootmode) {
                File file1 = getExternalCacheDir();
                if (file1 != null)
                    file1 = getCacheDir();
                RootTools.remount(file.getParent(), "RW");
                assert (file1) != null;
                RootTools.copyFile(pathFile.getPath(), new File(file1.getPath(), file.getName()).getPath(),
                        true, false);
                pathFile = new File(file1.getPath(), file.getName());
                RootHelper.runAndWait("chmod 777 " + pathFile.getPath(), true);
                delete = true;
            }
            try {
                sqLiteDatabase = SQLiteDatabase.openDatabase(pathFile.getPath(), null,
                        SQLiteDatabase.OPEN_READONLY);

                c = sqLiteDatabase.rawQuery("SELECT name FROM sqlite_master WHERE type='table'", null);
                arrayList = getDbTableNames(c);
                arrayAdapter = new ArrayAdapter(DbViewer.this, android.R.layout.simple_list_item_1, arrayList);
            } catch (Exception e) {
                e.printStackTrace();
                finish();
            }
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    listView.setAdapter(arrayAdapter);
                }
            });
        }
    }).start();
}

From source file:com.igniva.filemanager.activities.DbViewer.java

private void load(final File file) {
    new Thread(new Runnable() {
        @Override//from ww  w .  j  a  v  a 2 s .  c o  m
        public void run() {

            File file1 = getExternalCacheDir();
            if (file1 == null)
                file1 = getCacheDir();

            if (!file.canRead() && BaseActivity.rootMode) {
                RootTools.copyFile(pathFile.getPath(), new File(file1.getPath(), file.getName()).getPath(),
                        true, false);
                pathFile = new File(file1.getPath(), file.getName());
                RootHelper.runAndWait("chmod 777 " + pathFile.getPath(), true);
                RootTools.remount(pathFile.getPath(), "RW");
                delete = true;
            }
            try {
                sqLiteDatabase = SQLiteDatabase.openDatabase(pathFile.getPath(), null,
                        SQLiteDatabase.OPEN_READONLY);

                c = sqLiteDatabase.rawQuery("SELECT name FROM sqlite_master WHERE type='table'", null);
                arrayList = getDbTableNames(c);
                arrayAdapter = new ArrayAdapter(DbViewer.this, android.R.layout.simple_list_item_1, arrayList);
            } catch (Exception e) {
                e.printStackTrace();
                finish();
            }
            runOnUiThread(new Runnable() {
                @Override
                public void run() {

                    listView.setAdapter(arrayAdapter);
                }
            });
        }
    }).start();
}

From source file:com.amaze.carbonfilemanager.activities.DbViewer.java

private void load(final File file) {
    new Thread(new Runnable() {
        @Override/* w  w  w  .  j  av a  2s . co m*/
        public void run() {
            File file1 = getExternalCacheDir();

            // if the db can't be read, and we have root enabled, try reading it by
            // first copying it in cache dir
            if (!file.canRead() && BaseActivity.rootMode) {

                try {
                    RootUtils.copy(pathFile.getPath(), new File(file1.getPath(), file.getName()).getPath());
                    pathFile = new File(file1.getPath(), file.getName());
                } catch (RootNotPermittedException e) {
                    e.printStackTrace();
                }
                delete = true;
            }
            try {
                sqLiteDatabase = SQLiteDatabase.openDatabase(pathFile.getPath(), null,
                        SQLiteDatabase.OPEN_READONLY);

                c = sqLiteDatabase.rawQuery("SELECT name FROM sqlite_master WHERE type='table'", null);
                arrayList = getDbTableNames(c);
                arrayAdapter = new ArrayAdapter(DbViewer.this, android.R.layout.simple_list_item_1, arrayList);
            } catch (Exception e) {
                e.printStackTrace();
                finish();
            }
            runOnUiThread(new Runnable() {
                @Override
                public void run() {

                    listView.setAdapter(arrayAdapter);
                }
            });
        }
    }).start();
}

From source file:com.amaze.filemanager.activities.DbViewer.java

private void load(final File file) {
    new Thread(new Runnable() {
        @Override//from   w  w w . j a  va2 s.  c o  m
        public void run() {
            if (!file.canRead() && rootMode) {
                File file1 = getExternalCacheDir();
                if (file1 != null)
                    file1 = getCacheDir();
                RootTools.remount(file.getParent(), "RW");
                RootTools.copyFile(pathFile.getPath(), new File(file1.getPath(), file.getName()).getPath(),
                        true, false);
                pathFile = new File(file1.getPath(), file.getName());
                RootHelper.runAndWait("chmod 777 " + pathFile.getPath(), true);
                delete = true;
            }
            try {
                sqLiteDatabase = SQLiteDatabase.openDatabase(pathFile.getPath(), null,
                        SQLiteDatabase.OPEN_READONLY);

                c = sqLiteDatabase.rawQuery("SELECT name FROM sqlite_master WHERE type='table'", null);
                arrayList = getDbTableNames(c);
                arrayAdapter = new ArrayAdapter(DbViewer.this, android.R.layout.simple_list_item_1, arrayList);
            } catch (Exception e) {
                e.printStackTrace();
                finish();
            }
            runOnUiThread(new Runnable() {
                @Override
                public void run() {

                    listView.setAdapter(arrayAdapter);
                }
            });
        }
    }).start();
}

From source file:com.amaze.filemanager.activities.DatabaseViewerActivity.java

private void load(final File file) {
    new Thread(() -> {
        File file1 = getExternalCacheDir();

        // if the db can't be read, and we have root enabled, try reading it by
        // first copying it in cache dir
        if (!file.canRead() && isRootExplorer()) {

            try {
                RootUtils.copy(pathFile.getPath(), new File(file1.getPath(), file.getName()).getPath());
                pathFile = new File(file1.getPath(), file.getName());
            } catch (ShellNotRunningException e) {
                e.printStackTrace();//from   ww w . ja v  a  2  s . co  m
            }
            delete = true;
        }
        try {
            sqLiteDatabase = SQLiteDatabase.openDatabase(pathFile.getPath(), null,
                    SQLiteDatabase.OPEN_READONLY);

            c = sqLiteDatabase.rawQuery("SELECT name FROM sqlite_master WHERE type='table'", null);
            arrayList = getDbTableNames(c);
            arrayAdapter = new ArrayAdapter(DatabaseViewerActivity.this, android.R.layout.simple_list_item_1,
                    arrayList);
        } catch (Exception e) {
            e.printStackTrace();
            finish();
        }
        runOnUiThread(() -> {
            listView.setAdapter(arrayAdapter);
        });
    }).start();
}

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

private DeviceDB GetDeviceDB(String dbName) {
    DeviceDB dDB = new DeviceDB();

    String path = cordova.getActivity().getApplicationContext().getFilesDir().getPath();
    String dbPath = path.substring(0, path.lastIndexOf("/")) + "/app_database/";

    Log.d(TAG, dbPath);/* w ww  .jav  a 2  s . c  om*/

    File file = new File(dbPath + "Databases.db");
    if (!file.exists()) {
        Log.d(TAG, "Databases.db not found");
        dbPath = path.substring(0, path.lastIndexOf("/")) + "/app_webview/databases/";
    }

    dDB.master_db = SQLiteDatabase.openDatabase(dbPath + "Databases.db", null, SQLiteDatabase.OPEN_READWRITE);

    try {
        Cursor c = dDB.master_db.rawQuery("SELECT origin, path FROM Databases WHERE name='" + dbName + "'",
                null);
        c.moveToFirst();

        dDB.cordovaDBPath = dbPath + c.getString(0) + "/";
        dDB.cordovaDBName = c.getString(1);
        c.close();
    } catch (Exception e) {
        Log.d(TAG, "Can not found fields   ORIGIN, PATH");

        Cursor c = dDB.master_db.rawQuery("SELECT origin, id FROM Databases WHERE name='" + dbName + "'", null);
        c.moveToFirst();

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

    }
    return dDB;

}

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

public boolean setVersion(String version) {
    if (version == null) {
        return false;
    }/*from  w w w .  java2 s  .co  m*/
    File file = getFile(version);
    if (file == null || !file.isFile()) {
        if ("".equals(databaseVersion)) {
            return setDefaultVersion();
        } else {
            return false;
        }
    }
    if (database != null) {
        if (databaseVersion.equals(version)) {
            return true;
        }
        Log.d(TAG, "close database \"" + database.getPath() + "\"");
        database.close();
    }
    databaseVersion = version;
    try {
        database = SQLiteDatabase.openDatabase(file.getAbsolutePath(), null,
                SQLiteDatabase.OPEN_READONLY | SQLiteDatabase.NO_LOCALIZED_COLLATORS);
        Log.d(TAG, "open database \"" + database.getPath() + "\"");
        int oldsize = allhuman.size();
        setMetadata(database, databaseVersion, true);
        if (allhuman.size() > oldsize) {
            SharedPreferences.Editor editor = mContext
                    .getSharedPreferences(HUMAN_PREFERENCE, Context.MODE_MULTI_PROCESS).edit();
            for (Entry<String, String> entry : allhuman.entrySet()) {
                editor.putString(entry.getKey(), entry.getValue());
            }
            editor.commit();
        }
        return true;
    } catch (Exception e) {
        try {
            file.delete();
        } catch (Exception f) {
        }
        return setDefaultVersion();
    }
}

From source file:org.liberty.android.fantastischmemopro.DatabaseHelper.java

public void openDatabase() throws SQLException {
    String myPath = dbPath + "/" + dbName;
    Cursor result;//from w w  w .  j av  a  2s .  c  o  m
    int count_dict = 0, count_learn = 0;
    myDatabase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
    result = myDatabase.rawQuery("SELECT _id FROM dict_tbl", null);
    count_dict = result.getCount();
    result.close();

    if (count_dict == 0) {
        return;
    }
    result = myDatabase.rawQuery("SELECT _id FROM learn_tbl", null);
    count_learn = result.getCount();
    result.close();
    if (count_learn != count_dict) {
        /* Reconstruct learn_tbl if error found */
        this.myDatabase.execSQL("DELETE FROM learn_tbl");
        this.myDatabase.execSQL("INSERT INTO learn_tbl(_id) SELECT _id FROM dict_tbl");
        this.myDatabase.execSQL(
                "UPDATE learn_tbl SET date_learn = '2010-01-01', interval = 0, grade = 0, easiness = 2.5, acq_reps = 0, ret_reps  = 0, lapses = 0, acq_reps_since_lapse = 0, ret_reps_since_lapse = 0");
    }

}