我对卸载Android应用程序时的SQLite DB状态有些疑问。
答案 0 :(得分:3)
卸载应用程序时SQLite DB会发生什么?
与任何其他类型的文件相同。如果它位于internal storage上,或位于external storage上的应用专用位置(例如getExteranlFilesDir()
),则会删除该数据库。
如果我的设备没有外部存储(SD卡),如何在卸载应用程序时无缝保存SQlite数据库。
这是不可能的。幸运的是,当您的应用程序被卸载时,您的应用无法获得控制权。
建议的方法将数据存储在数据库中/加密数据库,以便在用户具有设备的root访问权限时无法访问它
请勿将数据放在设备上。
答案 1 :(得分:-1)
将数据库放入内部存储空间的代码
public class DatabaseAdapter extends SQLiteOpenHelper
{
private static String DB_PATH = FileUtil.CreateDirByName("database")+"/";
private static String DB_NAME = "YourDBName.sqlite";
private static final int DATABASE_VERSION = 1;
private SQLiteDatabase myDataBase;
private final Context myContext;
public DatabaseAdapter(Context context)
{
super(context, DB_NAME, null, DATABASE_VERSION);
this.myContext = context;
try
{
createDataBase();
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
/**
* Creates a empty database on the system and rewrites it with your own database.
* */
public void createDataBase() throws IOException{
boolean dbExist = checkDataBase();
if(dbExist)
{
//do nothing - database already exist
}
else
{
super.getWritableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
private boolean checkDataBase() {
// TODO Auto-generated method stub
SQLiteDatabase checkDB = null;
try{
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
}catch(SQLiteException e){
e.printStackTrace();
}
if(checkDB != null){
checkDB.close();
}
return checkDB != null ? true : false;
}
@Override
public SQLiteDatabase getReadableDatabase(){
try{
if(myDataBase != null)
myDataBase.close();
String myPath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
}catch(SQLiteException e){
e.printStackTrace();
}
return myDataBase;
}
@Override
public SQLiteDatabase getWritableDatabase(){
try{
if(myDataBase != null)
myDataBase.close();
String myPath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
}catch(SQLiteException e){
e.printStackTrace();
}
return myDataBase;
}
private void copyDataBase() throws IOException{
//Read the DB
InputStream myInput = myContext.getAssets().open(DB_NAME);
String outFileName = DB_PATH + DB_NAME;
OutputStream myOutput = new FileOutputStream(outFileName);
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer))>0){
myOutput.write(buffer, 0, length);
}
//Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
public void openDataBase() throws SQLException
{
String myPath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
}
@Override
public void close() {
if(myDataBase != null)
myDataBase.close();
super.close();
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
onCreate(db);
}
}