美文网首页
Android数据存储

Android数据存储

作者: 拙峰朽木 | 来源:发表于2017-07-26 09:39 被阅读23次

    保存到共享首选项(sharedPreference):

    这里说的是SharedPreference不是Preference,关于Preference可以看官方文档:https://developer.android.com/guide/topics/ui/settings.html
    SharedPreferences 类提供了一个通用框架,以便您能够保存和检索原始数据类型的永久性键值对。 您可以使用 SharedPreferences 来保存任何原始数据:布尔值、浮点值、整型值、长整型和字符串。 此数据将跨多个用户会话永久保留(即使您的应用已终止亦如此)。

    要获取应用的 SharedPreferences 对象,请使用以下两个方法之一:

    • getSharedPreferences() - 如果您需要多个按名称(使用第一个参数指定)识别的首选项文件,请使用此方法。
    • getPreferences() - 如果您只需要一个用于 Activity 的首选项文件,请使用此方法。 由于这将是用于 Activity 的唯一首选项文件,因此无需提供名称。

    创建一个指定的首选项文件:

     private SharedPreferences getSharedPreferences() {
            Context context = TrainingApplication.getTrainingApplication().getApplicationContext();
            return context.getSharedPreferences(context.getString(R.string.preference_file_key), Context.MODE_PRIVATE);
        }
    

    第一个参数是文件的名称,第二个参数这是指定文件类型,

    MODE_PRIVATE:文件私有话,只有当前app可用。如果创建了一个MODE_WORLD_READABLE或者MODE_WORLD_WRITEABLE 模式的shared preference文件,则其他任何app均可通过文件名访问该文件。

    向SharedPreference文件写入数据:

     public void setFirstEnter(boolean b) {
            Context context = TrainingApplication.getTrainingApplication().getApplicationContext();
            SharedPreferences.Editor editor = mSharedPreferences.edit();
            editor.putBoolean(context.getString(R.string.first_enter), b);
    //        editor.commit();
            /*考虑在共享首选项上使用apply()而不是commit,apply会在后台处理它,commit将立即写入持久存储器*/
            editor.apply();
        }
    
    

    提交文件变更,可以用commit和apply两种,区别在于commit是立即写入存储器,apply是在后台处理,即异步和同步的缺别。官方建议使用apply()。

    从SharedPreference文件读取数据:

     public boolean getIsFirstEnter() {
            Context context = TrainingApplication.getTrainingApplication().getApplicationContext();
            return mSharedPreferences.getBoolean(context.getString(R.string.first_enter), true);
        }
    

    其他常用API参考:https://developer.android.com/reference/android/content/SharedPreferences.html

    SQLite

    SQL中一个重要的概念是schema(模式):一种DB结构的正式声明,用于表示database的组成结构。schema是从创建DB的SQL语句中生成的。我们会发现创建一个伴随类(companion class)是很有益的,这个类称为合约类(contract class),它用一种系统化并且自动生成文档的方式,显示指定了schema样式。
    Contract Clsss是一些常量的容器。它定义了例如URIs,表名,列名等。这个contract类允许在同一个包下与其他类使用同样的常量。 它让我们只需要在一个地方修改列名,然后这个列名就可以自动传递给整个code。

    组织contract类的一个好方法是在类的根层级定义一些全局变量,然后为每一个table来创建内部类。

    通过实现 BaseColumns 的接口,内部类可以继承到一个名为_ID的主键,这个对于Android里面的一些类似cursor adaptor类是很有必要的。这么做不是必须的,但这样能够使得我们的DB与Android的framework能够很好的相容。

    创建Contract

    public class FeedReaderContract {
        // To prevent someone from accidentally instantiating the contract class,
        // make the constructor private.
        private FeedReaderContract() {
        }
    
        /* Inner class that defines the table contents */
        public static class FeedEntry implements BaseColumns {
            public static final String TABLE_NAME = "entry";
            public static final String COLUMN_NAME_TITLE = "title";
            public static final String COLUMN_NAME_SUBTITLE = "subtitle";
        }
    }
    
    

    SQL Helper

    public class FeedReaderDbHelper extends SQLiteOpenHelper {
        public static final int DATABASE_VERSION = 1;
        public static final String DATABASE_NAME = "FeedReader.db";
    
        private static final String TEXT_TYPE = " TEXT";
        private static final String COMMA_SEP = ",";
        private static final String SQL_CREATE_ENTRIES =
                "CREATE TABLE " + FeedReaderContract.FeedEntry.TABLE_NAME + " (" +
                        FeedReaderContract.FeedEntry._ID + " INTEGER PRIMARY KEY," +
                        FeedReaderContract.FeedEntry.COLUMN_NAME_TITLE + TEXT_TYPE + COMMA_SEP +
                        FeedReaderContract.FeedEntry.COLUMN_NAME_SUBTITLE + TEXT_TYPE +
                        " )";
    
        private static final String SQL_DELETE_ENTRIES =
                "DROP TABLE IF EXISTS " + FeedReaderContract.FeedEntry.TABLE_NAME;
    
        public FeedReaderDbHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }
    
    
        @Override
        public void onCreate(SQLiteDatabase sqLiteDatabase) {
            sqLiteDatabase.execSQL(SQL_CREATE_ENTRIES);
        }
    
        @Override
        public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
            onUpgrade(sqLiteDatabase, oldVersion, newVersion);
        }
    }
    

    插入数据:

      FeedReaderDbHelper f = new FeedReaderDbHelper(this);
            SQLiteDatabase db = f.getWritableDatabase();
            ContentValues values = new ContentValues();
            values.put(FeedReaderContract.FeedEntry.COLUMN_NAME_TITLE, "My Title");
            values.put(FeedReaderContract.FeedEntry.COLUMN_NAME_SUBTITLE, "我是帅哥");
            db.insert(FeedReaderContract.FeedEntry.TABLE_NAME, null, values);
    
    

    查看数据库,发现里面多了个叫"entry"的table,并且里面多了条数据

    image.png

    查找数据:

     FeedReaderDbHelper f = new FeedReaderDbHelper(this);
            SQLiteDatabase dbRead = f.getReadableDatabase();
            String[] projection = {FeedReaderContract.FeedEntry._ID,
                    FeedReaderContract.FeedEntry.COLUMN_NAME_TITLE,
                    FeedReaderContract.FeedEntry.COLUMN_NAME_SUBTITLE};
            String selection = FeedReaderContract.FeedEntry.COLUMN_NAME_TITLE + " = ?";
            String[] selectionArgs = {"frc"};
            String sortOrder = FeedReaderContract.FeedEntry.COLUMN_NAME_SUBTITLE + " DESC";
    
            Cursor c = dbRead.query(
                    FeedReaderContract.FeedEntry.TABLE_NAME,
                    projection,
                    selection,
                    selectionArgs, null, null, sortOrder);
            c.moveToFirst();
            long itemId = c.getLong(c.getColumnIndexOrThrow(FeedReaderContract.FeedEntry._ID));
            String title = c.getString(c.getColumnIndexOrThrow(FeedReaderContract.FeedEntry.COLUMN_NAME_TITLE));
            String sub_title = c.getString(c.getColumnIndexOrThrow(FeedReaderContract.FeedEntry.COLUMN_NAME_SUBTITLE));
            Log.e(TAG, "itemId: " + itemId);
            Log.e(TAG, "title: " + title);
            Log.e(TAG, "sub_title: " + sub_title);
    

    我们查看下打印的数据:

    07-24 18:10:27.661 4485-4485/com.example.frc.trainingapp E/MainActivity: itemId: 2
    07-24 18:10:27.661 4485-4485/com.example.frc.trainingapp E/MainActivity: title: frc
    07-24 18:10:27.661 4485-4485/com.example.frc.trainingapp E/MainActivity: sub_title: 我是帅哥
    

    再对比下数据库:

    image.png

    删除数据:

     FeedReaderDbHelper f = new FeedReaderDbHelper(this);
     String selection = FeedReaderContract.FeedEntry.COLUMN_NAME_TITLE + " LIKE ?";
     String[] selectionArgs = {"xzz"};
     SQLiteDatabase db = f.getReadableDatabase();
     db.delete(FeedReaderContract.FeedEntry.TABLE_NAME, selection, selectionArgs);   
    

    运行下再看下数据库:

    image.png

    我们发现xzz那条被删除了

    相关文章

      网友评论

          本文标题: Android数据存储

          本文链接:https://www.haomeiwen.com/subject/pbjnkxtx.html