Can i create a file in databases directory?
i need to create, at runtime, a database file in the databases directory (/data/data/pkg-name/databases/). My question is: is it possible?
If i try to create it with:
File unzipped = new File(context.getDatabasePath(filename + ".db").getPath());
unzipped.createNewFile();
the app goes in error with: ...no such file or directo开发者_开发技巧ry...
Some idea how i can do this?
i download from internet the database that i need to create, this is the problem.
Some idea how i can do this?
Create the directory. Android will not create the directory automatically until you try creating your first database with SQLiteDatabase
or SQLiteOpenHelper
.
You have to check if:
- Directory exists, if not create it.
- File exists, if not create it.
But if you re actually trying to create a sqlite database there are better ways of doing that
private static class OpenHelper extends SQLiteOpenHelper {
OpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME
+ "(_id INTEGER PRIMARY KEY, name TEXT)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
while (oldVersion != newVersion) {
Log.w("Example",
"Upgrading database, this will drop tables and recreate.");
if (oldVersion == 4) {
db.execSQL("ALTER TABLE " + TABLE_NAME+ " ADD COLUMN type INTEGER");
}
else if(oldVersion>=5)
{
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
oldVersion++;
}
}
}
精彩评论