Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - Sqlite Database file is not deleted while uninstalling an App?

While installing my Application into the Android device, the Database file is storing in the SD card root folder. But it should be placed in the path <SD Card_Root>\<Project_Name>\<dbfile>. After, uninstalling an App from the device the database file including with the project folder should also be deleted. So, Please help me to solve the two Problems as mentioned below:

1. After installation of apk file into the device, the database file should be placed in the path <SD Card_Root>\<Project_Name>\<dbfile>. 2. After uninstallation of apk file, the database file including with the root folder should be deleted automatically.

Please help me with your ideas/links.

Here is my code:

    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();

    }

}

like image 991
Avadhani Y Avatar asked Nov 27 '22 09:11

Avadhani Y


2 Answers

You should always use Context.getExternalFilesDir(String) to find the path for storing files owned by your app on the SD card. Please DO NOT use any kind of hand-built paths for this or any other standard locations like this; always use the APIs that are provided by the platform in Context and Environment.

Note that the platform only started deleting these files at the point where this API was introduced (API level 8). Prior to that, there is nowhere you can store files on the SD card that will result in them being deleted when your app is uninstalled.

like image 187
hackbod Avatar answered Dec 15 '22 00:12

hackbod


If you want DB file (or any other file) to be deleted on app uninstall, it should be placed below path:

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

like image 27
Sver Avatar answered Dec 15 '22 01:12

Sver