Java Code Examples for android.content.Context#getDatabasePath()

The following examples show how to use android.content.Context#getDatabasePath() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ApnDatabase.java    From Silence with GNU General Public License v3.0 6 votes vote down vote up
private ApnDatabase(final Context context) throws IOException {
  this.context = context;

  File dbFile = context.getDatabasePath(DATABASE_NAME);

  if (!dbFile.getParentFile().exists() && !dbFile.getParentFile().mkdir()) {
    throw new IOException("couldn't make databases directory");
  }

  Util.copy(context.getAssets().open(ASSET_PATH, AssetManager.ACCESS_STREAMING),
            new FileOutputStream(dbFile));

  try {
    this.db = SQLiteDatabase.openDatabase(context.getDatabasePath(DATABASE_NAME).getPath(),
                                          null,
                                          SQLiteDatabase.OPEN_READONLY | SQLiteDatabase.NO_LOCALIZED_COLLATORS);
  } catch (SQLiteException e) {
    throw new IOException(e);
  }
}
 
Example 2
Source File: TodoApp.java    From NexusData with Apache License 2.0 6 votes vote down vote up
public static PersistentStoreCoordinator getStoreCoordinator() {
    if (storeCoordinator == null) {
        ObjectModel model;
        try {
            model = new ObjectModel(app.getAssets().open("todo.model.json"));
        } catch (IOException ex) {
            throw new RuntimeException("Could not find models file", ex);
        }

        storeCoordinator = new PersistentStoreCoordinator(model);

        Context ctx = app.getApplicationContext();
        PersistentStore cacheStore = new AndroidSqlPersistentStore(ctx, ctx.getDatabasePath("todo"));
        storeCoordinator.addStore(cacheStore);
    }

    return storeCoordinator;
}
 
Example 3
Source File: BackupManager.java    From HeartBeat with Apache License 2.0 6 votes vote down vote up
public static String restore(Context context, Intent data) {
    try {
        File curDB = context.getDatabasePath(DB);
        OutputStream out = new FileOutputStream(curDB);
        InputStream in = context.getContentResolver().openInputStream(data.getData());
        // 使用解密
        if (!FileDES.doDecryptFile(in, out)) {
            return context.getString(R.string.restore_failed);
        }
        in.close();
        out.close();
        return context.getString(R.string.restore_ok);
    } catch (Exception e) {
        e.printStackTrace();
        return context.getString(R.string.restore_failed);
    }
}
 
Example 4
Source File: DatabaseHelper.java    From NetGuard with GNU General Public License v3.0 6 votes vote down vote up
private DatabaseHelper(Context context) {
    super(context, DB_NAME, null, DB_VERSION);
    prefs = PreferenceManager.getDefaultSharedPreferences(context);

    if (!once) {
        once = true;

        File dbfile = context.getDatabasePath(DB_NAME);
        if (dbfile.exists()) {
            Log.w(TAG, "Deleting " + dbfile);
            dbfile.delete();
        }

        File dbjournal = context.getDatabasePath(DB_NAME + "-journal");
        if (dbjournal.exists()) {
            Log.w(TAG, "Deleting " + dbjournal);
            dbjournal.delete();
        }
    }
}
 
Example 5
Source File: ContextImpl.java    From AndroidComponentPlugin with Apache License 2.0 5 votes vote down vote up
@Override
public boolean moveDatabaseFrom(Context sourceContext, String name) {
    synchronized (ContextImpl.class) {
        final File source = sourceContext.getDatabasePath(name);
        final File target = getDatabasePath(name);
        return moveFiles(source.getParentFile(), target.getParentFile(),
                source.getName()) != -1;
    }
}
 
Example 6
Source File: DecryptTest.java    From cwac-saferoom with Apache License 2.0 5 votes vote down vote up
@After
public void tearDown() {
  Context ctxt=InstrumentationRegistry.getTargetContext();
  File db=ctxt.getDatabasePath(DB_NAME);

  if (db.exists()) {
    db.delete();
  }

  File journal=new File(db.getParentFile(), DB_NAME+"-journal");

  if (journal.exists()) {
    journal.delete();
  }
}
 
Example 7
Source File: DatabaseHelper.java    From mobile-android-survey-app with MIT License 5 votes vote down vote up
public void copyAttachedDatabase(Context context, String databaseName) {
	final File dbPath = context.getDatabasePath(databaseName);

	// If the database already exists, return
	if (dbPath.exists()) {
		return;
	}

	// Make sure we have a path to the file
	dbPath.getParentFile().mkdirs();

	// Try to copy database file
	try {
		final InputStream inputStream = context.getAssets().open(databaseName);
		final OutputStream output = new FileOutputStream(dbPath);

		byte[] buffer = new byte[8192];
		int length;

		while ((length = inputStream.read(buffer, 0, 8192)) > 0) {
			output.write(buffer, 0, length);
		}

		output.flush();
		output.close();
		inputStream.close();
	}
	catch (IOException e) {
		Log.e("Failed to open file", e);
	}
}
 
Example 8
Source File: AriaManager.java    From Aria with Apache License 2.0 5 votes vote down vote up
/**
 * 初始化数据库
 */
private void initDb(Context context) {
  String oldDbName = "AriaLyyDb";
  File oldDbFile = context.getDatabasePath(oldDbName);
  if (oldDbFile != null && oldDbFile.exists()) {
    File dbConfig = new File(String.format("%s/%s", oldDbFile.getParent(), "AriaLyyDb-journal"));
    oldDbFile.renameTo(new File(String.format("%s/%s", oldDbFile.getParent(), "AndroidAria.db")));
    // 如果数据库是在/data/data/{packagename}/databases/下面,journal文件因权限问题将无法删除和重命名
    if (dbConfig.exists()) {
      dbConfig.delete();
    }
  }
  mDbWrapper = DelegateWrapper.init(context.getApplicationContext());
  amendTaskState();
}
 
Example 9
Source File: PreHookSqlTest.java    From cwac-saferoom with Apache License 2.0 5 votes vote down vote up
@After
public void tearDown() {
  Context ctxt=InstrumentationRegistry.getTargetContext();
  File db=ctxt.getDatabasePath(DB_NAME);

  for (File f : db.getParentFile().listFiles()) {
    f.delete();
  }
}
 
Example 10
Source File: SQLiteTestDatabase.java    From kripton with Apache License 2.0 5 votes vote down vote up
/**
 * Delete database file.
 *
 * @param context
 *            the context
 */
public static void clearDatabase(Context context) {
	File dbFile = context.getDatabasePath(SQLiteTestDatabase.TEST_DATABASE);
	Logger.info("Clear database file %s", dbFile.getAbsolutePath());
	if (!dbFile.delete()) {
		Logger.warn("Can not delete database " + dbFile.getAbsolutePath());
	}
}
 
Example 11
Source File: DatabaseUtil.java    From xDrip with GNU General Public License v3.0 5 votes vote down vote up
public static String saveSql(Context context) {
    try {

        final String databaseName = new Configuration.Builder(context).create().getDatabaseName();

        final String dir = getExternalDir();
        makeSureDirectoryExists(dir);

        final StringBuilder sb = new StringBuilder();
        sb.append(dir);
        sb.append("/export");
        sb.append(DateFormat.format("yyyyMMdd-kkmmss", System.currentTimeMillis()));
        sb.append(".sqlite");

        final String filename = sb.toString();
        final File sd = Environment.getExternalStorageDirectory();
        if (sd.canWrite()) {
            final File currentDB = context.getDatabasePath(databaseName);
            final File backupDB = new File(filename);
            if (currentDB.exists()) {
                final FileInputStream srcStream = new FileInputStream(currentDB);
                final FileChannel src = srcStream.getChannel();
                final FileOutputStream destStream = new FileOutputStream(backupDB);
                final FileChannel dst = destStream.getChannel();
                dst.transferFrom(src, 0, src.size());
                src.close();
                srcStream.close();
                dst.close();
                destStream.close();
            }
        }

        return filename;
    } catch (final Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 12
Source File: SavedWallpaperImages.java    From Trebuchet with GNU General Public License v3.0 5 votes vote down vote up
public static void moveFromCacheDirectoryIfNecessary(Context context) {
    // We used to store the saved images in the cache directory, but that meant they'd get
    // deleted sometimes-- move them to the data directory
    File oldSavedImagesFile = new File(context.getCacheDir(),
            LauncherFiles.WALLPAPER_IMAGES_DB);
    File savedImagesFile = context.getDatabasePath(LauncherFiles.WALLPAPER_IMAGES_DB);
    if (oldSavedImagesFile.exists()) {
        oldSavedImagesFile.renameTo(savedImagesFile);
    }
}
 
Example 13
Source File: BackupManager.java    From HeartBeat with Apache License 2.0 5 votes vote down vote up
public static String backupSD(Context context) {
    try {
        File curDb = context.getDatabasePath(DB);
        File bakFile = FileUtils.generateBackupFile(context);
        FileDES.doEncryptFile(curDb, bakFile);
        return bakFile.toString();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 14
Source File: DataBaseUtils.java    From UltimateAndroid with Apache License 2.0 5 votes vote down vote up
/**
 * Open a database which is used for both reading and writing.
 * If the database is not exists,the method will create a database from the assets{@link #copyDatabase(android.content.Context, java.io.File, String)}.
 * @param context
 * @param databaseName
 * @return
 */
public synchronized SQLiteDatabase getWritableDatabase(Context context,String databaseName) {
    File dbFile = context.getDatabasePath(databaseName);
    if (dbFile != null && !dbFile.exists()) {
        try {
            copyDatabase(context,dbFile,databaseName);
        } catch (IOException e) {
            throw new RuntimeException("Copying database error", e);
        }
    }

    return SQLiteDatabase.openDatabase(dbFile.getPath(), null, SQLiteDatabase.OPEN_READWRITE);
}
 
Example 15
Source File: Tools.java    From android-discourse with Apache License 2.0 4 votes vote down vote up
public static final boolean dbExist(Context ctx, String dbName) {
    File path = ctx.getDatabasePath(dbName);
    return path.exists();
}
 
Example 16
Source File: FileHelper.java    From OmniList with GNU Affero General Public License v3.0 4 votes vote down vote up
public static File getDatabaseFile(Context context) {
    return context.getDatabasePath(PalmDB.DATABASE_NAME);
}
 
Example 17
Source File: DbAdapter.java    From sa-sdk-android with Apache License 2.0 4 votes vote down vote up
private DbAdapter(Context context, String packageName) {
    mContext = context.getApplicationContext();
    contentResolver = mContext.getContentResolver();
    mDatabaseFile = context.getDatabasePath(DbParams.DATABASE_NAME);
    mDbParams = DbParams.getInstance(packageName);
}
 
Example 18
Source File: DBAdapter.java    From clevertap-android-sdk with MIT License 4 votes vote down vote up
DatabaseHelper(Context context, String dbName) {
    super(context, dbName, null, DATABASE_VERSION);
    databaseFile = context.getDatabasePath(dbName);
}
 
Example 19
Source File: DriveSyncController.java    From Drive-Database-Sync with Apache License 2.0 4 votes vote down vote up
/**
 * Constructs a new {@link DriveSyncController}.
 * @param context the Activity Context
 * @param dbName the local SQLite Database name
 * @param newerStatusCallback the callback to notify of local/cloud newer status
 */
private DriveSyncController(final Context context, String dbName, NewerDatabaseCallback newerStatusCallback) {
    mDriveClient = DriveApiFactory.getClient(context, new GoogleApiClient.ConnectionCallbacks() {
                @Override
                public void onConnected(Bundle bundle) {
                    // mDriveLayer.getFile(localDb.getName());
                    if (debug) {
                        Log.d("DriveSyncController", "mDriveClient Connected");
                    }
                    doQueue();
                }

                @Override
                public void onConnectionSuspended(int i) {
                    // Don't care
                    if (debug) {
                        Log.d("DriveSyncController", "mDriveClient Suspended");
                    }
                }
            },
            new GoogleApiClient.OnConnectionFailedListener() {
                @Override
                public void onConnectionFailed(ConnectionResult connectionResult) {

                    if (debug) {
                        Log.d("DriveSyncController", "mDriveClient Connection Failed");
                        Log.d("DriveSyncController", connectionResult.toString());
                    }

                    // Resolve
                    if (!connectionResult.hasResolution()) {
                        // Show the localized error dialog
                        GooglePlayServicesUtil.getErrorDialog(connectionResult.getErrorCode(),
                                (Activity) context, 0).show();
                        return;
                    }

                    try {
                        connectionResult.startResolutionForResult((Activity) context, 0);
                    } catch (IntentSender.SendIntentException e) {
                        Log.e("GoogleApiClient", "Exception while starting resolution activity");
                    }
                }
            },
            debug
    );

    if (debug) {
        Log.d("DriveSyncController", "Connecting mDriveApiClient");
    }

    mDriveClient.connect();

    mDriveLayer = new DriveLayer(mDriveClient, this);
    mDriveLayer.setDebug(debug);

    if (debug) {
        Log.d("DriveSyncController", "Getting Database Path");
    }

    localDb = context.getDatabasePath(dbName);

    if (debug) {
        Log.d("Database Path", localDb.toString());
    }

    mRequestQueue = new LinkedList<>();

    this.newerStatusCallback = newerStatusCallback;
}
 
Example 20
Source File: DatabaseLoader.java    From android-project-wo2b with Apache License 2.0 2 votes vote down vote up
/**
 * 返回数据库文件
 * 
 * @param dbname
 * @return
 */
public static File getDatabaseFile(Context context, String dbname)
{
	return context.getDatabasePath(dbname);
}