Android - 卸载应用时Sqlite数据库文件未被删除?

4
在将我的应用程序安装到Android设备时,数据库文件存储在SD卡根目录下。但是它应该放置在路径<SD Card_Root>\<Project_Name>\<dbfile>中。在从设备卸载应用程序后,包括项目文件夹在内的数据库文件也应该被删除。所以,请帮我解决以下两个问题: 1. 在将apk文件安装到设备后,应将数据库文件放置在路径<SD Card_Root>\<Project_Name>\<dbfile>中。 2. 卸载apk文件后,包括根文件夹在内的数据库文件应该自动删除。 请提供您的想法/链接来帮助我。
以下是我的代码:
    import java.io.BufferedInputStream;
    import java.io.ByteArrayOutputStream;
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.util.zip.ZipEntry;
    import java.util.zip.ZipInputStream;

    import android.os.Environment;

    import android.content.Context;
    import android.database.Cursor;
    import android.database.SQLException;
    import android.database.sqlite.SQLiteDatabase;
    import android.database.sqlite.SQLiteException;
    import android.database.sqlite.SQLiteOpenHelper;

    public class DataBaseHelper extends SQLiteOpenHelper{
 private static String DB_PATH = Environment.getExternalStorageDirectory().getAbsolutePath() ;
 private static String DB_NAME = "Database.db";
 private SQLiteDatabase myDataBase; 
 private final Context myContext;  



public DataBaseHelper(Context context) {         
    super(context, DB_NAME, null, 2);
    this.myContext = context;
    }   
 public void createDataBase() throws IOException 
 {
    // boolean dbExist = checkDataBase();        
     DB_PATH = Environment.getExternalStorageDirectory().getAbsolutePath();
     if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) 
     {
         File db = new File(DB_PATH, DB_NAME);
         if(!db.exists())
         {
             db.createNewFile();
             try { 
                  copyFromZipFile(); 
              } catch (IOException e) { 
              throw new Error("Error copying database",e); 
              }
         }


        }        
 }

 private void copyFromZipFile() throws IOException{ 
     InputStream is = myContext.getResources().openRawResource(R.raw.database); 
         // Path to the just created empty db 
         File outFile = new File(DB_PATH ,DB_NAME); 
          //Open the empty db as the output stream 
         OutputStream myOutput = new FileOutputStream(outFile.getAbsolutePath()); 
         ZipInputStream zis = new ZipInputStream(new BufferedInputStream(is)); 
          try { 
              ZipEntry ze =  null; 
              while ((ze = zis.getNextEntry()) != null) { 
                  ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
                  byte[] buffer = new byte[24 * 1024]; 
                  int count; 
                  while ((count = zis.read(buffer)) != -1) { 
                      baos.write(buffer, 0, count); 
                      //Log.d("", buffer.toString()); 
                      baos.writeTo(myOutput); 
                      baos.reset();
                  } 
                  baos.writeTo(myOutput); 


              } 
          } 
          catch (IOException e) {}
              zis.close(); 
              myOutput.flush(); 
              myOutput.close(); 
              is.close(); 


          /*finally { 
              zis.close(); 
              myOutput.flush(); 
              myOutput.close(); 
              is.close(); 
          } */
        }


 private boolean checkDataBase(){        
        SQLiteDatabase checkDB = null;   
        try{
            String myPath = DB_PATH +""+ "/" + DB_NAME;
            checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);   
        }catch(SQLiteException e){

            //database does't exist yet.

        }    
        if(checkDB != null){     
            checkDB.close();     
        }    
        return checkDB != null ? true : false;
    } 
 public void openDataBase() throws SQLException{

        //Open the database
        String myPath = DB_PATH + "/" + DB_NAME;
        myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);

    }
 @Override
    public synchronized void close() {   
            if(myDataBase != null)
                myDataBase.close();  
            super.close();   
    }

 @Override
    public void onCreate(SQLiteDatabase db) {      
     String sql = "create table if not exists info(_id integer primary key autoincrement, Name text not null, firmName text not null);";
     db.execSQL(sql);
     sql = "create table if not exists Client(_id integer primary key autoincrement, Name text not null, clientName text not null);";
     db.execSQL(sql);

    }

  @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {   
     db.execSQL("DROP TABLE IF EXISTS employee");
     db.execSQL("DROP TABLE IF EXISTS info");
     db.execSQL("DROP TABLE IF EXISTS Client");
     onCreate(db);
    }
 public void onDestroy()
 { 
     myDataBase.close(); 
     }
    public Cursor getView(String sql)
       {
 if(myDataBase != null) {
     myDataBase.close();

   }
   openDataBase();
    Cursor xcur =  myDataBase.rawQuery(sql,null);
        return xcur; 

 }
 private void copyDataBase() throws IOException{

        //Open your local db as the input stream
        InputStream myInput = myContext.getAssets().open(DB_NAME);   
        // Path to the just created empty db
        String outFileName = DB_PATH + DB_NAME;  
        //Open the empty db as the output stream
        OutputStream myOutput = new FileOutputStream(outFileName);   
        //transfer bytes from the inputfile to the outputfile
        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();

    }

}


你好,你是在运行时创建数据库还是提供特定路径来创建数据库? - Herry
2个回答

16

您应该始终使用Context.getExternalFilesDir(String)来查找在SD卡上存储您的应用程序拥有的文件的路径。请不要为此类标准位置或任何其他手工构建的路径使用,总是使用ContextEnvironment中提供的API。

请注意,平台只从引入此API(API level 8)的时候开始删除这些文件。在此之前,您无处可以存储在SD卡上的文件,这些文件将在卸载您的应用程序时被删除。


14
如果您希望在应用程序卸载时删除DB文件(或任何其他文件),则应将其放置在以下路径下:

"sd_card/Android/data/your.package.name/"


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接