安卓之SharedPreferences存储

SharedPreferences存储
首先关于安卓存储我们在这里介绍一下:
持久化技术介绍:
数据持久化就是指将那些内存中瞬间数据保存到存储设备中,保证即使手机或电脑关机的情况下,这些数据仍然不会丢失。保存在内存中的数据是处于瞬时状态的,而保存在存储设备中的数据是处于持久状态的,持久化技术则提供了一种机制可以让数据在瞬间状态和持久状态之间进行转换。(引用第一行代码中的讲解)
SharedPreferences存储
它是一种轻量级的数据存储方式,是使用键值对的方式来存储数据的。通俗的说,当保存一条数据的时候,需要给这条数据提供一个对应的键,这样在读取数据的时候就可以通过这个键把相应的值取出来。类似与bundle。SharedPreferences支持基本数据类型存储。
(1) 首先需要得到SharedPreferences对象:
getSharedPreferences(String name,int mode)
第一个参数用于指定SharedPreferences文件的名称,第二个参数用于指定访问权限(也就是说用于指定操作模式),目前只有MODE_PRIVATE(表示只能被本应用程序读和写,其中写入的内容会覆盖原文件的内容)这个可选,它默认的操作模式。其他的几种操作模式都已经废除了,在这里我就不介绍了。
(2)调用SharedPreferences对象来获取SharePreferences对象:

SharedPreferences.Editor editor=getSharedPreferences(String name,int mode).edit();

(3)向SharedPreferences.Editor对象中添加数据,比如添加一个字符串型数据就使用putString(),其他的和这个类似。
(4)调用commit()方法提交数据,从而完成数据存储操作。(调用apply()方法也可以)。
我感觉不如来个案例了解的更透彻:
首先我们创建一个安卓项目(具体如何创建我就在这里不在介绍了)。
在这里插入图片描述
在activity_main.xml中编写如下代码:

<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=".MainActivity">


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        >
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="应户名:"
            android:textSize="20sp"
            />
        <EditText
            android:id="@+id/username"
            android:layout_width="0dip"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:inputType="text"
            android:textSize="20sp"
            android:layout_marginTop="20sp"
            >
            <requestFocus/>
        </EditText>



    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        >
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="密     码:"
            android:textSize="20sp"
            />
        <EditText
            android:id="@+id/password"
            android:layout_width="0dip"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:textSize="20sp"
            />

    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        >
        <CheckBox
            android:id="@+id/rember_pass"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="18sp"
            android:text="Remember password"
            />
    </LinearLayout>
    <Button
        android:id="@+id/login"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
        android:text="Login"
        />

</LinearLayout>

这是我们创建一个登录界面:
在这里插入图片描述
然后在MainActivity中编写如下代码:


public class MainActivity extends AppCompatActivity {
  private SharedPreferences pref;
  private SharedPreferences.Editor editor;
  private EditText username;
  private EditText passwordEdit;
  private Button login;
  private CheckBox rememberPass;
  private boolean isRemember=false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);
        pref= getSharedPreferences("mode",MODE_PRIVATE);
        username=(EditText)findViewById(R.id.username);
        passwordEdit=(EditText)findViewById(R.id.password);
        rememberPass=(CheckBox)findViewById(R.id.rember_pass);
        login=(Button)findViewById(R.id.login);

           login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String accout1=username.getText().toString();
                String password=passwordEdit.getText().toString();
                //如果账号是name且密码是123,就认为登录成功
                if (accout1.equals("name")&&password.equals("123")){
                    editor=pref.edit();
                    if (rememberPass.isChecked()){//检查复选框是否被选中
                        editor.putBoolean("remember_password",true);
                        editor.putString("account",accout1);
                        editor.putString("password",password);

                    }else {
                        editor.putBoolean("remember_password",false);
                        editor.putString("account",accout1);
                        editor.putString("password",password);
                    }
                    editor.commit();
                    Intent intent=new Intent(MainActivity.this,Main2Activity.class);
                    startActivity(intent);

                }else {
                    Toast.makeText(MainActivity.this,"应户名或密码不对",Toast.LENGTH_SHORT).show();
                }

            }
        });
    }
}

然后在activity_main2.xml中编写如下代码:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".Main2Activity">
    <TextView
        android:id="@+id/username"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        />
    <TextView
        android:id="@+id/password"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        />

</LinearLayout>

用来显示从第一个activity中传来的数据。
在Main2Activity中编写如下代码:


public class Main2Activity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        TextView usernameTV=(TextView)findViewById(R.id.username);
        TextView passwordTV=(TextView)findViewById(R.id.password);
        if (NavUtils.getParentActivityName(Main2Activity.this)!=null){
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }
           SharedPreferences preferences=getSharedPreferences("mode",MODE_PRIVATE);
        boolean isRemember=preferences.getBoolean("remember_password",false);
        if (isRemember){

           String usename=preferences.getString("account","");
           String password=preferences.getString("password","");
           usernameTV.setText(usename);
           passwordTV.setText(password);
        }
        else {

            String usename=preferences.getString("account","");
            usernameTV.setText(usename);
        }


    }
}

到这里这个案例就做完了,你可以运行试一试看看效果。
*当你输入应户名和密码时,不点击复选按钮时,单击按钮时只会在第二个界面出现用户名,当点击复选按钮时就会在第二个界面出现用户名和密码。

希望这篇文章可以帮助你更好的学习安卓SharePreferences存储。

原创文章 16 获赞 18 访问量 5076

猜你喜欢

转载自blog.csdn.net/jzdcuccess/article/details/105851039