美文网首页
Android 数据持久化的简单使用

Android 数据持久化的简单使用

作者: oven小区 | 来源:发表于2019-02-06 17:39 被阅读0次

    Android 数据持久化主要有三种:
    文件,SharePreference, 数据库

    文件存储

    不对存储的文件进行任何格式化的处理,所有数据都是直接存入文件中,因此比较适合保存一些简单的文本数据和二进制数据

    • 存入读取:
     FileOutputStream out = null;
            BufferedWriter writer = null;
            try {
                out = openFileOutput("data", Context.MODE_PRIVATE);
                /*主要有两种模式:
                1.MODE_PRIVATE:当指定同名文件时,自动覆盖
                2.MODE_APPEND:已存在就追加
                */
                writer = new BufferedWriter(new OutputStreamWriter(out));//得到一个OutputStreamwriter对象
                //再构建一个bufferedWriter
                writer.write(inputText);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (writer != null) {
                        writer.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    
    public String load() {
            FileInputStream in = null;
            BufferedReader reader = null;
            StringBuilder content = new StringBuilder();
            try {
                in = openFileInput("data");
                reader = new BufferedReader(new InputStreamReader(in));
                String line = "";
                while ((line = reader.readLine()) != null) {
                    content.append(line);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return content.toString();
        }
    
    • java知识小补点
      String,StringBuffer,StringBuilder区别:
      String 利用字符数组保存数据,源码中有final修饰,因而实际上是不可变的
      当String a = "b"+"c"时,实际上创建了两个对象
      而StringBuffer和StringBuilder都只创建一个实例
      SringBuffer 线程安全,而StringBuider线程不安全
      三者的效率,String < StringBuffer < StringBuilder

    SharedPreference 存储

    这是一种应用私有的,利用键值对存储数据的方式,支持对不同类型的数据类型进行储存,存为xml格式,方便小巧效率高
    存入:

    SharedPreferences.Editor editor = getSharedPreferences("data", MODE_PRIVATE).edit();
                    editor.putString("name", "Tom");
                    editor.putInt("age", 28);
                    editor.putBoolean("married", false);
                    editor.apply();
    

    取出:

    SharedPreferences pref = getSharedPreferences("data", MODE_PRIVATE);
                    String name = pref.getString("name", "");
                    int age = pref.getInt("age", 0);
                    boolean married = pref.getBoolean("married", false);
    

    这是context类中的getSharedPreferences()方法的模式
    2.Activity类中的getPreferences()方法
    3.PrefenceMangager类中的getDefaultSharedPreferences
    e.g.
    读取

     SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(WeatherActivity.this);
    

    存入

      SharedPreferences.Editor editor =PreferenceManager.getDefaultSharedPreferences(WeatherActivity.this).edit();
    editor.putString("weather",mresponse);
    editor.apply();
    
    • SQLite数据库
      SQLite 是一个 Android 自带的轻量型的数据库。
    • 利用数据库的 DBHelper 建库建表
    • e.g.
     class AreaDBHelper extends SQLiteOpenHelper {
     //定义 private static 语句 用于直观呈现数据库所需要的参数
        private static final int DB_VERSION = 1;
        private static final String DB_NAME = "area.db";
        private static final String PROVINCE_NAME = "province";
        private static final String CITY_NAME = "city";
        private static final String COUNTY_NAME = "county";
    
         AreaDBHelper(Context context) {
            super(context, DB_NAME, null, DB_VERSION);
        //构造方法需要提供四个参数,context, 库名,cursor,版本号
    
        }
    
        //建表建库,sql 语句要特别留意!
        @Override
        public void onCreate(SQLiteDatabase db) {
            String sql1 = "create table if not exists "
                    + PROVINCE_NAME
                    + " (Id integer primary key autoincrement,"
                    + "ProvinceName text,"
                    + "ProvinceId integer)";
            String sql2 = "create table if not exists "
                    + CITY_NAME
                    + " (Id integer primary key autoincrement,"
                    + "CityName text,"
                    +"CityId integer,"
                    +"ProvinceId integer)";
             String sql3 = "create table if not exists "
                     +COUNTY_NAME
                     + " (Id integer primary key autoincrement,"
                     + "ProvinceId integer,"
                     + "CityId integer,"
                     + "CountyName text,"
                     + "WeatherId text)";
            db.execSQL(sql1);
            db.execSQL(sql2);
            db.execSQL(sql3);
        }
    
     //数据库的升级方法
        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            String sql1 = "DROP TABLE IF EXISTS" + PROVINCE_NAME;
            String sql2 = "DROP TABLE IF EXISTS" + CITY_NAME;
            String sql3 = "DROP TABLE IF EXISTS" + COUNTY_NAME;
            db.execSQL(sql1);
            db.execSQL(sql2);
            db.execSQL(sql3);
            onCreate(db);
        }
    
    }
    
    • 利用 DBDao 类对有关数据库进行操作
    public class DBDao {
        private Context mcontext;
        private AreaDBHelper areaDBHelper;
        /*
        *自定义构造器的做法,将传入的 context 赋值给mcontext
         */
        public DBDao(Context context){
            this.mcontext = context;
            areaDBHelper = new AreaDBHelper(context);
        }
    
        /**
         * 将省级列表存入数据库
         * @param provinceList
         */
        public void initProvinceTable(List<Province> provinceList){
            SQLiteDatabase db = areaDBHelper.getWritableDatabase();
            ContentValues values = new ContentValues();
            for(Province province:provinceList){
                values.put("ProvinceName",province.getProvinceName());
                values.put("ProvinceId",province.getProvinceCode());
                db.insert("province",null,values);
                values.clear();
            }
            db.close();
        }
        /**
        *在数据库中查询省级
        */
        
       public List<Province> queryProvince(){
           List<Province> provinceList = new ArrayList<>();
           SQLiteDatabase db = areaDBHelper.getWritableDatabase();
           Cursor cursor = db.query("province",null,null,null,null,null,null);
           if(cursor.moveToFirst()){
               do{
                   String provinceName = cursor.getString(cursor.getColumnIndex("ProvinceName"));
                   int provinceCode = cursor.getInt(cursor.getColumnIndex("ProvinceId"));
                   Province province = new Province();
                   province.setProvinceCode(provinceCode);
                   province.setProvinceName(provinceName);
                   provinceList.add(province);
               }while (cursor.moveToNext());
           }
            cursor.close();
           db.close();
           return provinceList;
       }
      }
    }
    
    • 数据库是耗资源的操作,应避免频繁访问,用完记得关闭连接

    相关文章

      网友评论

          本文标题:Android 数据持久化的简单使用

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