《Android那些事》——SharedPreference的简单使用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zzp961224/article/details/72772073
SharedPreference的使用

      Android系统中主要提供了三种方式用于简单地实现数据持久化功能,即文件存储、SharedPreference存储以及数据库存储。当然,除了这三种方式之外,你还可以将数据保存在手机的 SD卡中,不过使用文件、SharedPreference或数据库来保存数据会相对更简单一些,而且比起将数据保存在 SD卡中会更加的安全

      SharedPreference是Android提供的一种轻量级的数据储存方式,主要用来储存一些简单的配置信息。
      例如:默认欢迎语,登录用户名和密码等。其以键值对的方式储存, 使得我们能够很方便的读取的存入。
      SharedPreferences还支持多种不同的数据类型存储,如果存储的数据类型是整型,那么读取出来的数据也是整型的,存储的数据是一个字符串,读取出来的数据仍然是字符串。

Demo:

public class MainActivity extends AppCompatActivity {

    private EditText edit;
    private CheckBox box;

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

        edit = (EditText) findViewById(R.id.name);
        box = (CheckBox) findViewById(R.id.cb);

        //得到sharedPreferences,键值对形式,将当前页面的数据储存在share里面
        SharedPreferences sharedPreferences=getSharedPreferences("share",
                MainActivity.MODE_PRIVATE);
        //因为不知道name的值是什么,它是由sharedPreferences传过来的,所以设为空
        edit.setText(sharedPreferences.getString("name",""));
        box.setChecked(sharedPreferences.getBoolean("sex",false));

    }

    //当程序彻底退出时,记录当前页面数据,再次打开应用时,恢复关闭前所记录的数据
    @Override
    protected void onStop() {
        super.onStop();
        SharedPreferences sharedPreferences=getSharedPreferences("share",
                MainActivity.MODE_PRIVATE);
        //记录当前的对象数据
        SharedPreferences.Editor editor=sharedPreferences.edit();

        //做储存
        editor.putString("name",edit.getText().toString());
        editor.putBoolean("sex",box.isChecked());
        //保存
        editor.commit();
    }
}

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.administrator.sharedpreferences.MainActivity">

    <EditText
        android:id="@+id/name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <CheckBox
        android:id="@+id/cb"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="CheckBox" />

</LinearLayout>

界面:


猜你喜欢

转载自blog.csdn.net/zzp961224/article/details/72772073