• 第六章 详解持久化技术


    一、持久化技术简介

    持久化技术提供了一种机制可以让数据从内存转换到存储设备中

    Android提供了3种方式实现数据持久化功能:文件存储、SharedPreference存储和数据库存储

    二、文件存储

    1.将数据存储到文件中

    Context类提供了一个openFileOutput()方法,可以将数据存储到指定的文件。

    第一个参数是文件名(不包含路径),第二个参数是文件的操作模式,MODE_PRIVATE是默认操作模式,表示指定同样文件名时,写入的内容会覆盖原有的内容;MODE_APPEND表示文件名已存在时追加内容,不存在时创建新文件。

    public class MainActivity extends AppCompatActivity {
     
        private EditText edit;
     
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            edit = findViewById(R.id.edit);
        }
     
        @Override
        protected void onDestroy() {
            super.onDestroy();
            String s = edit.getText().toString();
            save(s);
        }
     
        public void save(String s) {
            FileOutputStream out = null;
            BufferedWriter writer = null;
            try {
                //openFileOutput是ContextWrapper类的方法
                out = openFileOutput("data", Context.MODE_PRIVATE);
                writer = new BufferedWriter(new OutputStreamWriter(out));
                writer.write(s);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (writer != null) {
                    try {
                        writer.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39

    2.从文件中读取数据

    public class MainActivity extends AppCompatActivity {
     
        private EditText edit;
     
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            edit = findViewById(R.id.edit);
            String s = load();
            //TextUtils.isEmpty()方法可以一次性进行两种空值的判断,传入的字符串等于null或等于空字符串时都会返回true
            if(!TextUtils.isEmpty(s)){
                edit.setText(s);
                //调用setSelection()方法将输入光标移动到文本的末尾位置以便继续输入
                edit.setSelection(s.length());
                Toast.makeText(this, "Restoring succeeded", Toast.LENGTH_SHORT).show();
            }
        }
     
        ...
     
        private String load(){
            FileInputStream in = null;
            BufferedReader reader = null;
            StringBuilder builder = new StringBuilder();
            try {
                in = openFileInput("data");
                reader = new BufferedReader(new InputStreamReader(in));
                String line = "";
                while ((line = reader.readLine())!=null){
                    builder.append(line);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                if(reader!=null){
                    try {
                        reader.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return builder.toString();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46

    三、SharedPreference存储

    以键值对的方式存储数据

    获取Sharedpreferences对象的三种方法:

    1. Context类中的getSharedPreferences()方法:第一个参数指定SharedPreferences文件的名称,指定的文件不存在则会创建一个,第二个参数指定操作模式,只有MODE_PRIVATE一种模式可选,表示只有当前的应用程序才可以对这个SharedPreferences文件进行读写
    2. Activity类中的getPreferences()方法:只接收一个操作模式参数,因为这个方法会自动将当前活动的类名作为SharedPreferences的文件名
    3. PreferenceManager类中的getDefaultSharedPreferences()方法:这是一个静态方法,接收一个Context参数,自动使用当前应用程序的包名作为前缀来命名Sharedpreferences文件

    1.将数据存储到SharedPreferences

    调用SharedPreferences对象的edit()方法获取SharedPreferences.Editor对象
    使用putString()putBoolean()方法向SharedPreferences.Editor对象添加数据
    调用apply()方法将添加的数据提交

    public class MainActivity extends AppCompatActivity {
     
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            Button save = findViewById(R.id.save);
            save.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    SharedPreferences.Editor editor = getSharedPreferences("data", Context.MODE_PRIVATE).edit();
                    editor.putString("name", "jack");
                    editor.putInt("age", 28);
                    editor.putBoolean("married", false);
                    //提交,完成数据存储操作
                    editor.apply();
                }
            });
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    2.从SharedPreferences中读取数据

    调用SharedPreferences对象的getString()getInt()和getBoolean()方法,这些get方法接收两个参数,第一个参数是键,第二个参数是默认值

    public class MainActivity extends AppCompatActivity {
     
        private static final String TAG = "Jack";
        
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            ...
     
            Button restore = findViewById(R.id.restore);
            restore.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    SharedPreferences pref = getSharedPreferences("data", Context.MODE_PRIVATE);
                    String name = pref.getString("name", "");
                    int age = pref.getInt("age", 0);
                    boolean married = pref.getBoolean("married", false);
                    Log.d(TAG, "name is " + name);
                    Log.d(TAG, "name is " + age);
                    Log.d(TAG, "name is " + married);
                }
            });
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25

    3.实现记住密码的功能

    public class LoginActivity extends BaseAcitvity {
        
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.login_layout);
            Button login = findViewById(R.id.login);
            EditText account = findViewById(R.id.account);
            EditText password = findViewById(R.id.password);
            SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
            CheckBox rememberPassword = findViewById(R.id.remember_password);
            boolean aBoolean = pref.getBoolean("remember_password", false);
            if(aBoolean){
                String account1 = pref.getString("account", "");
                String password1 = pref.getString("password", "");
                account.setText(account1);
                password.setText(password1);
                rememberPassword.setChecked(true);
            }
            login.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    String s_acount = account.getText().toString();
                    String s_password = password.getText().toString();
                    if ("admin".equals(s_acount) && "123456".equals(s_password)) {
                        SharedPreferences.Editor editor = pref.edit();
                        if(rememberPassword.isChecked()){
                            editor.putString("account",s_acount);
                            editor.putString("password",s_password);
                            editor.putBoolean("remember_password",true);
                        }else {
                            editor.clear();
                        }
                        editor.apply();
                        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                        startActivity(intent);
                        finish();
                    }else {
                        Toast.makeText(LoginActivity.this, "account or password is invalid", Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
  • 相关阅读:
    TCP IP网络编程(三) 地址族与数据序列
    ros指令 rqt_bag <bagname>
    ubuntu 22.04 卸载不常用软件,安装常用软件两行解决
    RS笔记:深度推荐模型之SIM(基于搜索的超长行为序列上的用户长期兴趣建模)[CIKM 2020, 阿里妈妈广告团队]
    C++构造函数
    Spring——简介和IOC底层原理
    具有Postman + Swagger + Mock + JMeter所有功能的工具
    【实例分割】YOLACT++:Better Real-time Instance Segmentation论文详解
    如何通过链路追踪进行定时任务诊断
    WPF控件10
  • 原文地址:https://blog.csdn.net/weixin_61653908/article/details/134487590