SharedPreferences的读写

Posted on 2017-07-10 20:39  番茄番茄  阅读(418)  评论(0编辑  收藏  举报

使用SharedPreferences储存数据,就要获取到SharedPreferences对象一共三种获取方法;

一:Context类中的getSharedPreferences(),该方法接收两个参数,第一个是存储SharedPreferences的名称,第二个参数是操作模式,默认MODE_PRIVATE,只有当前的程序才能对SharedPreferences文件进行操作。和直接传入0的效果相同。 

二:Activity类中的getPreferences()方法,该方法只接受一个操作模式参数,此方法会自动使用当前的活动类名作为SharedPreferences的文件名。

三:PreferencesManager类中的PreferenceManager.getDefaultSharedPreferences(MainActivity.this);该方法接收一个参数,就是上下文参数,

以上三种获取方式 返回的对象都是SharedPreferences对象。

进行存储过程步骤:

  1:调用SharedPreferences对象的Editor来获取SharedPreferences.Editor对象

  2:利用获取的SharedPreferences.Editor对象,调用putXXX()方法,XXX为要存储的数据类型。

  3:利用获取的SharedPreferences.Editor对象,调用apply()方法提交数据,完成数据存储操作。

 

下面是简易登录界面的保存用户名 密码的源码

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<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="ca.sd.zsl.rememberpassword_sharedpreferences.MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:orientation="horizontal">

        <TextView
            android:layout_width="90dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:text="用户名:"
            android:textSize="18sp" />

        <EditText
            android:id="@+id/et_name"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:layout_weight="1" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:orientation="horizontal">

        <TextView
            android:layout_width="90dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:text="密    码:"
            android:textSize="18sp" />

        <EditText
            android:id="@+id/et_password"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:layout_weight="1"
            android:inputType="textPassword" />
    </LinearLayout>
    <CheckBox
        android:id="@+id/cb_remember_checkBox"
        android:text="是否记住密码"
        android:layout_gravity="center_horizontal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/bt_login"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="登录" />
</LinearLayout>

 

 MainActivity.java

package ca.sd.zsl.rememberpassword_sharedpreferences;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

import java.io.File;

public class MainActivity extends AppCompatActivity {
    private SharedPreferences preferences;
    private SharedPreferences.Editor editor;
    EditText et_name, et_password;
    Button bt_Login;
    CheckBox ck_remember;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        et_name = (EditText) findViewById(R.id.et_name);
        et_password = (EditText) findViewById(R.id.et_password);
        bt_Login = (Button) findViewById(R.id.bt_login);
        ck_remember = (CheckBox) findViewById(R.id.cb_remember_checkBox);
        //preferences = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
        // 以此方式创建的SharedPreferences文件,自动使用当前活动的包名作为前缀来命名SharedPreferences文件
        preferences = getSharedPreferences("aa",MODE_PRIVATE);
        //以此方式创建的SharedPreferences文件,指定名称,和类型模式(只有当前的应用程序才能对这个SharedPreferences文件进行读写)
        boolean isremember = preferences.getBoolean("remember_password", false);
        if (isremember) {
            String name = preferences.getString("name", "");
            String password = preferences.getString("password", "");
            et_name.setText(name);
            et_password.setText(password);
            ck_remember.setChecked(true);
        }

        bt_Login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String name = et_name.getText().toString().trim();
                String password = et_password.getText().toString().trim();
                if (name.equals("zsl") && password.equals("123")) {
                    if (ck_remember.isChecked()) {
                        editor = preferences.edit();
                        editor.putBoolean("remember_password", true);
                        editor.putString("name", name);
                        editor.putString("password", password);
                    }else {
                        File file= new File("/data/data/"+getPackageName().toString()+"/shared_prefs","aa.xml");
                        file.delete();
                        Intent intent = new Intent(MainActivity.this, SuccessLogin.class);
                        startActivity(intent);
                        finish();
                    }
                    editor.apply();
                    Intent intent = new Intent(MainActivity.this, SuccessLogin.class);
                    startActivity(intent);
                    finish();
                }else {
                    Toast.makeText(MainActivity.this, "密码或者账号错误", Toast.LENGTH_SHORT).show();
                }

            }
        });

    }
}