下面列出了android.content.Context#getDatabasePath ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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);
}
}
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();
}
}
}
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;
}
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);
}
}
/**
* 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);
}
@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;
}
}
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;
}
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);
}
}
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);
}
}
/**
* 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());
}
}
@After
public void tearDown() {
Context ctxt=InstrumentationRegistry.getTargetContext();
File db=ctxt.getDatabasePath(DB_NAME);
for (File f : db.getParentFile().listFiles()) {
f.delete();
}
}
/**
* 初始化数据库
*/
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();
}
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);
}
}
@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();
}
}
private DbAdapter(Context context, String packageName) {
mContext = context.getApplicationContext();
contentResolver = mContext.getContentResolver();
mDatabaseFile = context.getDatabasePath(DbParams.DATABASE_NAME);
mDbParams = DbParams.getInstance(packageName);
}
public static final boolean dbExist(Context ctx, String dbName) {
File path = ctx.getDatabasePath(dbName);
return path.exists();
}
public static File getDatabaseFile(Context context) {
return context.getDatabasePath(PalmDB.DATABASE_NAME);
}
DatabaseHelper(Context context, String dbName) {
super(context, dbName, null, DATABASE_VERSION);
databaseFile = context.getDatabasePath(dbName);
}
/**
* 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;
}
/**
* 返回数据库文件
*
* @param dbname
* @return
*/
public static File getDatabaseFile(Context context, String dbname)
{
return context.getDatabasePath(dbname);
}