Skip to content Skip to sidebar Skip to footer

How Can I Maintain Sq-lite Data. When User Clears Data From Application Manager

In my android app i use SQLite database for storing and retrieving data. When user clear the data from application manager the data will be cleared.But my requirement is when user

Solution 1:

Users can clear data if they want. So you can not make your database static. But, If you want to keep your database, you can copy your database to assets folder and when app invoke method onCreate of SQLiteHelper, you will copy from assets folder to device.

Here is the sample:

DBHelper

package vn.mve.db;

import java.util.List;

publicinterfaceDBHelper<T> {
    booleaninsert(T val);
    booleanupdate(T val);
    booleandelete(T val);
    List<T> getList(int type);
    T getChild(Object val);
}

DBHandler

publicclassDBHandlerextendsSQLiteOpenHelper {
    privatestaticfinalStringTAG= DBHandler.class.getSimpleName();
    protected SQLiteDatabase db; 
    privatefinal Context context;  
    privatestaticStringPACKAGE_NAME="";
    privatestaticintDATABASE_VERSION=1;

    publicDBHandler(Context context) {
        super(context, Def.DBNAME, null, DATABASE_VERSION);
        this.context = context; 
        PACKAGE_NAME = this.context.getPackageName();
        Def.FOLDER_DB = "/data/data/" + PACKAGE_NAME + "/databases/";
        Log.d(TAG, Def.FOLDER_DB);
        try {
            this.createDataBase();
        } catch (IOException e) {
            e.printStackTrace();
        }       
    }
    @OverridepublicvoidonCreate(SQLiteDatabase db) {
        try {
            this.createDataBase();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @OverridepublicvoidonUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        context.deleteDatabase(Def.DBNAME);
        onCreate(db);
    }

    publicvoidcreateDataBase()throws IOException{
        // for first database;booleandbExist= checkDataBase();
        if(!dbExist){
            try {
                copyDataBase("db/" + Def.DBNAME);
            } catch (Exception e) {
                Log.e(TAG, "createDatabse -> Copy failed!");
                thrownewError("Error copying database");
            }
        } else {
            open();
            booleanisExist=false;
            Cursorcursor= db.rawQuery("select DISTINCT tbl_name from sqlite_master where tbl_name = 'config'", null);
            if (cursor != null) {
                isExist = true;
                cursor.close();
            } else {
                isExist = false;
            }
            close();
            Log.d(TAG, isExist + "");
            if (!isExist) {
                this.context.deleteDatabase(Def.DBNAME);
                try {
                    Log.d(TAG, "createDatabase when database has existed");
                    copyDataBase(Def.DBNAME);
                } catch (Exception e) {
                    Log.e(TAG, "createDatabse -> Copy failed!");
                    thrownewError("Error copying database");
                }               
            }
        }
    }   
    /**
     * Copies your database from your local assets-folder to the just created empty database in the
     * system folder, from where it can be accessed and handled.
     * This is done by transfering bytestream.
     * */privatevoidcopyDataBase(String DB) {
        //Open your local db as the input streamInputStreammyInput=null;
        //Open the empty db as the output streamOutputStreammyOutput=null;
        try {
            myInput = context.getResources().getAssets().open(DB);

            // Path to the just created empty dbStringoutFileName= Def.FOLDER_DB + Def.DBNAME; 
            myOutput = newFileOutputStream(outFileName);

            //transfer bytes from the inputfile to the outputfilebyte[] buffer = newbyte[1024];
            int length;
            while ((length = myInput.read(buffer)) > 0){
                myOutput.write(buffer, 0, length);
            }
        } catch (FileNotFoundException e) {
            Log.e(TAG, "copyDatabase -> File not found.");
            e.printStackTrace();
        } catch (IOException e) {
            Log.e(TAG, "copyDatabase");
        } finally {
              //Close the streamstry {
                myOutput.flush();
                myOutput.close();
                myInput.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }   
    privatebooleancheckDataBase(){
        booleancheckDB=false;
        try{
            StringmyPath= Def.FOLDER_DB + Def.DBNAME;
            FiledbFile=newFile(myPath); 
            checkDB = dbFile.isFile();
            Log.d(TAG, "checkDatabase: " + String.valueOf(checkDB));
            try {
                FilefTmp=newFile(Def.FOLDER_DB);
                if (!fTmp.exists()) {
                    fTmp.mkdir();
                }
            } catch (Exception e) {
                Log.e(TAG, "checkDatabase" + e.getMessage());
            }
        }catch(SQLiteException e){}
        return checkDB;
    }
    publicvoidopen() {
        try {
            StringmyPath= Def.FOLDER_DB + Def.DBNAME;
            db = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);          
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    @Overridepublicsynchronizedvoidclose() {
            if(db != null)
                db.close();
            super.close();
    }           
    public SQLiteDatabase getSqlDb() {
        return db;
    }
    publicvoidsetSqlDb(SQLiteDatabase sqlDb) {
        this.db = sqlDb;
    }    
}

And here:

publicclassMVideoextendsDBHandlerimplementsDBHelper<Video> {
    publicstatic final StringTAG = MVideo.class.getSimpleName();
    publicMVideo(Context context) {
        super(context);
    }

    @Overridepublicbooleaninsert(Video val) {
        open();
        ContentValues cValues = newContentValues();
        cValues.put(Def.Video.ID, val.getId());
        cValues.put(Def.Video.TITLE, val.getTitle());
        cValues.put(Def.Video.THUMBNAIL, val.getThumbnail());
        cValues.put(Def.Video.DESCRIPTION, val.getDescription());
        cValues.put(Def.Video.ENGLISH, val.getEnglish());
        cValues.put(Def.Video.VIETNAMESE, val.getVietnamese());
        cValues.put(Def.Video.ISVIEW, val.getIsView());
        long result = db.insert(Def.Video.NAME, null, cValues);
        close();        
        return result > 0;
    }

    publicbooleaninsertList(List<Video> list) {
        open();
        db.execSQL("BEGIN IMMEDIATE TRANSACTION");
        for (Video v : list) {
            db.execSQL(String.format("INSERT INTO " + Def.Video.NAME + " (\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\") VALUES" + 
                    " (\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\")",
                    Def.Video.ID, Def.Video.TITLE, Def.Video.THUMBNAIL, Def.Video.DESCRIPTION, 
                    Def.Video.ENGLISH, Def.Video.VIETNAMESE, Def.Video.ISVIEW,
                    v.getId(), v.getTitle(), v.getThumbnail(), v.getDescription(), v.getEnglish(), v.getVietnamese(), v.getIsView() + ""));
            Log.d(TAG, "insertList -> " + v.toString());
        }
        db.execSQL("COMMIT TRANSACTION");
        close();        
        returntrue;
    }

    @Overridepublicbooleanupdate(Video val) {
        // TODO Auto-generated method stubreturnfalse;
    }

    @Overridepublicbooleandelete(Video val) {
        open();
        db.delete(Def.Video.NAME, Def.Video.ID + "=?", newString[]{val.getId()});
        close();
        returnfalse;
    }

    @OverridepublicList<Video> getList(int type) {
        List<Video> list = newArrayList<Video>();
        open();
        Cursor c = db.rawQuery(Def.Video.GET_ALL, null);
        if (c.moveToFirst()) {
            while (c.moveToNext()) {
                StringID = c.getString(0);
                String title = c.getString(1);
                String thumbnail = c.getString(2);
                String description = c.getString(3);
                String english = c.getString(4);
                String vietnamese = c.getString(5);
                boolean isView = Boolean.parseBoolean(c.getString(6));
                list.add(newVideo(ID, title, thumbnail, description, english, vietnamese, isView));
            }
        }
        close();
        return list;
    }

    @OverridepublicVideogetChild(Object val) {
        open();
        Cursor c = db.query(Def.Video.NAME, newString[]{
                Def.Video.ID, Def.Video.TITLE, Def.Video.THUMBNAIL, Def.Video.DESCRIPTION, 
                Def.Video.ENGLISH, Def.Video.VIETNAMESE, Def.Video.ISVIEW
        }, Def.Video.ID + "=?", newString[]{val.toString()}, null, null, null, null);
        if (c != null) {
            c.moveToFirst();
        }
        Video v = newVideo(c.getString(0), c.getString(1), 
                c.getString(2), c.getString(3), c.getString(4), 
                c.getString(5), Boolean.parseBoolean(c.getString(6)));
        close();
        return v;
    } 
}

Solution 2:

The user is always free to remove application data, otherwise any application could fill up the phone, refuse to uninstall and require a factory reset to clean up.

If you really need the data safely stored, back it up to the cloud and restore it when the user reinstalls the application.

Solution 3:

The database is the place to keep your data for offline usage.

The only possibility I know would be to create a backup of the database on the SDCard in a directory of your choice. This folder will not be deleted when the user clears the data from the application manager. The downside of this "solution" would be that you need to implement the logic about recovering the backup. Also your backup will survive any deinstallation and new installations and I doubt that you want to restore a database from a previous installation.

To make it short: This would be a possible way to go but it has a lot of pitfalls and isn't really recommended. Let the user keep the control over the application and keep in mind: the user once figured out that you have a backup on the sdcard, he will eventually delete it, too.

Post a Comment for "How Can I Maintain Sq-lite Data. When User Clears Data From Application Manager"