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

Nul*_*ion 5 sqlite android

我想在程序启动时擦除我的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;
    }

}
Run Code Online (Sandbox Code Playgroud)

做这个的最好方式是什么?

War*_*ith 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();
    }
}
Run Code Online (Sandbox Code Playgroud)

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

文档:

需要维护全局应用程序状态的基类.您可以通过在AndroidManifest.xml的标记中指定其名称来提供自己的实现,这将导致在创建应用程序/包的过程时为您实例化该类.

  • 说实话:只是因为你有更多你想要的东西,从答案中删除"被接受"是一种不客气的行为......主题是1个月大...... (11认同)

kwo*_*son 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)
    {}
}
Run Code Online (Sandbox Code Playgroud)