Android - 卸载应用程序时不删除Sqlite数据库文件?

时间:2011-11-29 04:46:24

标签: java android sqlite

将我的应用程序安装到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();

    }

}

2 个答案:

答案 0 :(得分:16)

您应该始终使用Context.getExternalFilesDir(String)来查找在SD卡上存储应用程序所拥有文件的路径。请勿在此处或任何其他标准位置使用任何类型的手工制作路径;始终使用平台在ContextEnvironment

中提供的API

请注意,平台仅在引入此API的位置(API level 8)开始删除这些文件。在此之前,您无法在SD卡上存储文件,导致在卸载应用程序时删除这些文件。

答案 1 :(得分:14)

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

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