每次启动应用程序时如何清除SQLite数据库?

时间:2010-12-21 12:50:59

标签: android sqlite

我想在程序启动时擦除我的SQLite数据库实例。

我尝试的是在我的类MyDBAdapter.java上创建一个方法,如下所示:

public class MyDbAdapter {
    private static final String TAG = "NotesDbAdapter";
    private DatabaseHelper mDbHelper;
    private SQLiteDatabase mDb;
    private static final String DATABASE_NAME = "gpslocdb";
    private static final String PERMISSION_TABLE_CREATE = "CREATE TABLE permission ( fk_email1 varchar, fk_email2 varchar, validated tinyint, hour1 time default '08:00:00', hour2 time default '20:00:00', date1 date, date2 date, weekend tinyint default '0', fk_type varchar, PRIMARY KEY  (fk_email1,fk_email2))";
    private static final String USER_TABLE_CREATE = "CREATE TABLE user ( email varchar, password varchar, fullName varchar, mobilePhone varchar, mobileOperatingSystem varchar, PRIMARY KEY  (email))";

    private static final int DATABASE_VERSION = 2;
    private final Context mCtx;
    private static class DatabaseHelper extends SQLiteOpenHelper {

        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL(PERMISSION_TABLE_CREATE);
            db.execSQL(USER_TABLE_CREATE);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            db.execSQL("DROP TABLE IF EXISTS user");
            db.execSQL("DROP TABLE IF EXISTS permission");
            onCreate(db);
        }
    }

    /**
     * Constructor - takes the context to allow the database to be
     * opened/created
     * 
     * @param ctx the Context within which to work
     */
    public MyDbAdapter(Context ctx) {
        this.mCtx = ctx;
    }

    /**
     * Open the database. If it cannot be opened, try to create a new
     * instance of the database. If it cannot be created, throw an exception to
     * signal the failure
     * 
     * @return this (self reference, allowing this to be chained in an
     *         initialization call)
     * @throws SQLException if the database could be neither opened or created
     */
    public MyDbAdapter open() throws SQLException {
        mDbHelper = new DatabaseHelper(mCtx);
        mDb = mDbHelper.getWritableDatabase();
        return this;
    }

    public void close() {
        mDbHelper.close();
    }

    public long createUser(String email, String password, String fullName, String mobilePhone, String mobileOperatingSystem) 
    {
        ContentValues initialValues = new ContentValues();
        initialValues.put("email",email);
        initialValues.put("password",password);
        initialValues.put("fullName",fullName);
        initialValues.put("mobilePhone",mobilePhone);
        initialValues.put("mobileOperatingSystem",mobileOperatingSystem);
        return mDb.insert("user", null, initialValues);
    }


    public Cursor fetchAllUsers() {

        return mDb.query("user", new String[] {"email", "password", "fullName", "mobilePhone", "mobileOperatingSystem"}, null, null, null, null, null);
    }

    public Cursor fetchUser(String email) throws SQLException {

        Cursor mCursor = mDb.query(true, "user", new String[] {"email", "password", "fullName", "mobilePhone", "mobileOperatingSystem"}
            , "email" + "=" + email, null, null, null, null, null);
        if (mCursor != null) {
            mCursor.moveToFirst();
        }
        return mCursor;
    }
    public List<Friend> retrieveAllUsers() 
    {
        List <Friend> friends=new ArrayList<Friend>();

        Cursor result=fetchAllUsers();

        if( result.moveToFirst() ){
            do{
                //note.getString(note.getColumnIndexOrThrow(NotesDbAdapter.KEY_TITLE)));
                friends.add(new Friend(result.getString(result.getColumnIndexOrThrow("email")), "","","",""));
            }while( result.moveToNext() );
        }


        return friends;
    }

}

这样做的最佳方式是什么?

4 个答案:

答案 0 :(得分:13)

onCreate()onUpgrade()旁边,您可以覆盖onOpen()。删除所有表格并拨打onCreate()

public class MyApplication extends Application {
    protected static final String           LOG_TAG = "MyApplication";

    private static DatabaseAdapter          mDb;

    private static MyApplication    mInstance;

    /**
     * @return The instance of the database adapter.
     */
    public static DatabaseAdapter getDatabaseAdapter() {
        return mDb;
    }

    /**
     * @return The instance of the application.
     */
    public static Context getInstance() {
        return mInstance;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.w(LOG_TAG, "Application::onCreate");
        mInstance = this;
        mDb = new DatabaseAdapter();
    }

    @Override
    public void onTerminate() {
        // Close the internal db
        getDatabaseAdapter().close(DatabaseAdapter.INTERNAL);

        Log.e(LOG_TAG, "::onTerminate::");
        super.onTerminate();
    }
}

子类化Application的优点是,当您的应用程序启动或终止时,它将始终被调用。独立于已启动的活动。 打开/关闭数据库等全局操作应该放在这里。

文档:

  

需要的人的基础课程   维护全球申请状态。您   可以提供您自己的实现   在你的中指定它的名字   AndroidManifest.xml中的   标记,这将导致该类   在进程时为您实例化   对于您的应用程序/包是   创建

答案 1 :(得分:7)

我使用的快速简便的解决方案是通过调用另一个名为OnCreate()的方法来删除doDBCheck()方法中的数据库文件。 doDBCheck()在模拟器/手机的文件系统中查找文件,如果存在,请将其删除。

 private static final String DB_PATH = "data/data/<package name here>/databases/<db name>";

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    mainView = (TextView) findViewById(R.id.mainView);
    doDBCheck();

}

private void doDBCheck()
{
    try{
            File file = new File(DB_PATH);
            file.delete();
    }catch(Exception ex)
    {}
}

答案 2 :(得分:4)

使用内存中标志,因此无需清除它。

答案 3 :(得分:2)

您可以使用一种方法告诉SQLiteDatabase以编程方式删除其中一个数据库:

context.deleteDatabase(DATABASE_NAME);

您需要删除数据库的Context和名称。

您可以将其粘贴在与SQLite数据库建立连接的构造函数中。

更多信息:how to drop database in sqlite?