Android数据存储(二)——SharePreferences存储

SharePreferences使用键值对的方式存储数据,支持多种数据的存储

一、将数据存起来的步骤

要用SharePreferences存储数据,首先要获取到SharePreferences对象,有三种方法:

  1. Context.getSharePreferences()
    • 第一个参数:指定文件名,不存在则会创建一个。存放目录:/data/data/<package name>/share_prefs
    • 第二个参数:指定操作模式,填写MODE_PRIVATE0,表示只有当前应用程序可以对文件读写
  2. Activity.getPreferences()
    • 只接收一个参数,指定操作模式
    • 会自动将文件名设置为当前活动的类名
  3. PreferenceManger.getDefaultSharedPreferences()
    • 这是一个静态方法,接收一个Context参数
    • 自动使用当前应用的包名做前缀来命名文件

得到SharePreferences对象以后就可以向文件中存储数据了,存储数据也分三步:

  1. 调用edit()获取SharePreferences.Editor对象
  2. SharePreferences.Editor对象中添加数据,比如添加字符串用putString(),添加布尔对象用putBoolean()
  3. 调用apply()将添加的数据提交,从而完成数据存储

二、实战:存储数据

新建一个空项目day11_SharedPreferencesTest

1、主布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/save_data"
        android:text="存储数据"/>

</LinearLayout>

2、主活动

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button saveData = findViewById(R.id.save_data);
        saveData.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SharedPreferences.Editor editor = getSharedPreferences("data", MODE_PRIVATE).edit();
                editor.putString("name", "breathy");
                editor.putInt("age", 24);
                editor.putBoolean("married", true);
                editor.apply();
            }
        });
    }
}

3、运行

在这里插入图片描述
点击按钮后,会在/data/data/com.example.day11_sharedpreferencestest/shared_prefs/data.xml目录下找到文件:
在这里插入图片描述
保存并打开,能看到xml格式的数据文件:
在这里插入图片描述

三、将数据读出来

  1. 获取SharePreferences对象
  2. 直接用对应类型的get()取出来,不需要Editor

继续修改代码:

1、主布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
。。。。。。
    
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/load_data"
        android:text="读取数据"/>

</LinearLayout>

2、主活动

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";

。。。。。。

        Button loadData = findViewById(R.id.load_data);
        loadData.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SharedPreferences sharedPreferences = getSharedPreferences("data", MODE_PRIVATE);
                String name = sharedPreferences.getString("name","");
                int age = sharedPreferences.getInt("age",0);
                boolean married = sharedPreferences.getBoolean("married", false);
                Log.d(TAG, "姓名:"+name);
                Log.d(TAG, "年龄:"+age);
                Log.d(TAG, "结婚了:"+married);
            }
        });
    }
}

3、运行

在这里插入图片描述

四、记住密码的功能

继续《Android使用广播的最佳实践——强制下线功能》这篇文章的day10_BroadcastBestPractice项目,为了便于区分保存,改名为day10_BroadcastBestPratice_Modify

1、登录页布局

修改activity_login.xml布局,增加啊复选框

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

......


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <CheckBox
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/remember_pass"/>
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textSize="18sp"
            android:text="记住密码"/>
    </LinearLayout>

......

</LinearLayout>

2、登录页活动

public class LoginActivity extends BaseActivity {
    private EditText accountEdit;
    private EditText passwordEdit;
    private Button login;
    private CheckBox rememberPass;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        accountEdit = findViewById(R.id.account);
        passwordEdit = findViewById(R.id.password);
        login = findViewById(R.id.login);
        rememberPass = findViewById(R.id.remember_pass);
        final SharedPreferences pref = this.getSharedPreferences("SECRET", MODE_PRIVATE);
        boolean isRemember = pref.getBoolean("remember_password", false);
        if (isRemember){
            String account = pref.getString("account","");
            String password = pref.getString("password", "");
            accountEdit.setText(account);
            passwordEdit.setText(password);
            rememberPass.setChecked(true);
            accountEdit.setSelection(account.length());
        }
        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String account = accountEdit.getText().toString();
                String password = passwordEdit.getText().toString();
                SharedPreferences.Editor editor = pref.edit();
                if(rememberPass.isChecked()){
                    editor.putBoolean("remember_password", true);
                    editor.putString("account", account);
                    editor.putString("password", password);
                }else {
                    editor.clear();
                }
                editor.apply();
                if (account.equals("breathy") && password.equals("000000")){
                    Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                    startActivity(intent);
                    finish();
                }else {
                    Toast.makeText(LoginActivity.this, "账号或密码不正确", Toast.LENGTH_LONG).show();
                }
            }
        });
    }
}

3、运行

在这里插入图片描述
成功!

发布了156 篇原创文章 · 获赞 13 · 访问量 7220

猜你喜欢

转载自blog.csdn.net/qq_41205771/article/details/104182852
今日推荐