Tuesday 7 April 2015

Restricting user from clearing internal app data like DB (SQLite), Shared Preference

As an android developer we should be aware of  the options provided by android for saving app data.

Android provides several options for you to save persistent application data. The solution you choose depends on your specific needs, such as whether the data should be private to your application or accessible to other applications (and the user) and how much space your data requires.  

SQLite : Android platform includes the SQLite embedded database and provides out of the box support to use it via Android APIs.

Shared Preference : Android provides some ways of storing data of an application. One of this way is called Shared Preferences. Shared Preferences allow you to save and retrieve data in the form of key,value pair.

Internal or External Storage : All Android devices have two file storage areas: "internal" and "external" storage. These names come from the early days of Android, when most devices offered built-in non-volatile memory (internal storage), plus a removable storage medium such as a micro SD card (external storage). Some devices divide the permanent storage space into "internal" and "external" partitions, so even without a removable storage medium, there are always two storage spaces and the API behavior is the same whether the external storage is removable or not.

Android provides an option for clearing all the internal saved data. If users tap on "Clear data" from app setting all internal data of the app will be lost, shared preference , internal files, database, account settings, persistent preferences, etc.. 
Clearing the data should revert the application back to it's state as it was when you first installed it. So for developers its a bitter task when some users do this.

In this tutorial we are going to learn how to divert users when they go for "Clear data".

Step 1 : Create a new project by going to File ⇒ New Android Application Project. Fill all the details and name your activity as MainActivity.

Step 2 : When an app is having some internal data saved like sqlite, shared preference then we can find the "Clear data" button enabled in app settings. So in this project we are including the local database (SQLite) access.

Step 3 :  Create a new package for placing DataBaseHandler. Right Click on src/package folder ⇒ New ⇒ Package and name it as yourchoice.

Step 4 :  Create a new class under src/yourchoice package. Right Click on src/package folder ⇒ New ⇒ Class and name it as DataBaseHandler.java and fill it with following code.

                                                     DataBaseHandler.java

package com.androiddelight.cleardatademo.db;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.content.ContentValues;

public class DataBaseHandler extends  SQLiteOpenHelper {

// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "ClearDataDemo";
// Table Name

private static final String TABLE_DEMO = "demo";
// Demo Table Columns names 
private static final String ID = "id";
private static final String NAME = "name";

private static final String PASS = "pass";
public DataBaseHandler (Context context){
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

@Override
public void onCreate(SQLiteDatabase db){
// TODO Auto-generated method stub
   String CREATE_DEMO_TABLE = "CREATE TABLE " + TABLE_DEMO + "("
                + ID + " INTEGER PRIMARY KEY,"
                + NAME + " TEXT,"
                + PASS + " TEXT" + ")";
   db.execSQL(CREATE_DEMO_TABLE); 
 }
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
// Drop older table if existed

   db.execSQL("DROP TABLE IF EXISTS " + TABLE_DEMO);
   onCreate(db);
 }
// Saving to DB
public void saveDemo_data(String name, String pass){
// TODO Auto-generated method stub

   System.out.println(name +" " + pass);
   SQLiteDatabase db = this.getWritableDatabase();
   ContentValues values = new ContentValues();
        values.put(NAME, name);
        values.put(PASS, pass);
               
        db.insert(TABLE_DEMO, null, values);
       
        db.close();
 } 
// Getting row count from table
public int getTable_Count(){

   String selectQuery = null;
   selectQuery = "SELECT  * FROM " + TABLE_DEMO ;
   SQLiteDatabase db = this.getReadableDatabase();
   Cursor cursor = db.rawQuery(selectQuery, null);
   return cursor.getCount();
  }
}

Step 5 :  Open the activity_main.xml file under res/layout. Drag and drop a button and place it in center of the layout. Text the button as "Save data" eg: android:text = "Save data"

Step 6 :  Open the MainActivity.java file under src/package. We need to declare and reference the button in java file like Button btn_save = (Button) findViewById(R.id.button1);

Step 7 :  Set OnClickListener for btn_save. When the users taps on button one row is saved in sqlite by calling the method saveDemo_data and the total row count is retrieved by calling getTable_Count method in DataBaseHandler. It is displayed in Toast for the users.

Now the SQLite implementation and storing data all are finished.

To start, open your phone’s Settings app. Scroll down and tap Apps under the Device heading.
From there, find the app "ClearDataDemo" and tap on it.
Once you do that, you’ll be taken to an "app info" screen that provides some technical details including the app’s version number and how much storage space it eats up. There you can find the button "Clear data" as shown in the image below side


The main objective of this tutorial is to remove the "Clear data" and replace "Manage space" button as shown below which will launch an activity.

Step 8 : Create a new Activity by going to File ⇒ New Other ⇒ Android Activity. Fill all the details and name your activity as ManageData.

Step 9 : Open the activity_manage_data.xml file under res/layout. Drag and drop a TextView and place it in center of the layout. Add text to TextView as "Sorry! you don't have permission to clear app data". This is to prompt users that they don't have access to clear app data.

Step 10 : Open the AndroidManifest.xml file under project folder and add the following code.


AndroidManifest.xml
<application>
    android : allowBackup = "true" 
   android : icon = "@drawable/ic_launcher"  
  android : label = "@string/app_name"
  android : manageSpaceActivity = ".ManageData" >  <!--This activity is  launched on taping the Manage space button from setting  -->
 And declare the ManageData activity in Manifest as below 

<activity
    android : name = ".ManageData"  

  android : label = "@string/title_activity_manage_data" >

Finally when you try to tap on the Manage space button it will launch an Activity as shown below



There you go!!! Click here for source code.  Share this if it is helpful :-)

No comments:

Post a Comment