Android持久化技术

瞬时数据是指存储在内存中的数据。持久化技术可以将内存中的数据和持久状态(保存在存储设备上)之间相互转化。
Android提供了三种持久化方式

文件存储

文件存储不对存储内容进行任何的格式化处理,所有数据都是原封不动保存到文件当中。

将数据存储到文件中

Context类中提供了一个openFileOutput()方法,返回一个FileOutputStream对象,然后就可以用javaI/O流去写文件中了。文件都默认放在/data/data//files/目录下。

public void save(String data){
        FileOutputStream out=null;
        BufferedWriter writer=null;
        try{
            out=openFileOutput("data", Context.MODE_PRIVATE);//第一个参数是文件的名称,第二个参数是模式。MODE_PRIVATE表示覆盖,MODE_APPEND表示追加。
            writer=new BufferedWriter(new OutputStreamWriter(out));
            writer.write(data);
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            try {
                if(writer!=null)
                 writer.close();
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }

从文件中读取数据

Context类还提供了一个openFileInput(),返回的是一个FileInputStream。它接收一个参数,即要读取的文件名。然后系统会去/data/data//files/目录下寻找。

public String load(String name){
        FileInputStream input=null;
        BufferedReader reader=null;
        StringBuilder content=new StringBuilder();
        try {
            input=openFileInput(name);
            reader=new BufferedReader(new InputStreamReader(input));
            String line="";
            while((line=reader.readLine())!=null){
                content.append(line);
            }
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            try {
                if(reader!=null)
                    reader.close();
            }catch (IOException e){
                e.printStackTrace();
            }
        }
        return content.toString();
    }

SharedPreferences存储

SharedPreferences是使用键值对的方式来存储数据的

将数据存储到SharedPreferences中

步骤

1.获取SharedPreferences对象

  • Context类中的getSharedPreferences()方法

此方法接收两个参数,第一个参数用于指定SharedPreferences文件的名称,如果直接的名称文件不存在,则会创建一个文件,SharedPreferences文件都是存放在/data/data//shared_prefs/目录下。第二个参数用于指定操作模式,目前只有MODE_WORLD_READABLE这一种模式可选,它是默认的操作模式,和直接传入0效果是相同的,表示只有当前的应用才可以对这个文件进行读写.

  • Activity类中的getPreferences()方法

只接收一个操作模式参数,因为自动将当前活动的类名当作SharedPreferences的文件名

  • PreferenceManager类中的getDefaultSharedPreferences()方法

这是一个静态方法,它接收一个Context参数,并自动使用当前应用程序的包名作为前缀来命名SharedPreferences文件。


2.向SharedPreferences中存储数据

(1)调用SharedPreferences对象的edit()方法来获取一个SharedPreferences.Editor对象
(2)向SharedPreferences.Editor对象中添加数据,比如添加一个布尔型数据就使用putboolean()方法等
(3)调用apply()方法将添加的数据提交,从而完成数据存储操作

从SharedPreferences中读取数据

步骤

1.获取SharedPreferences对象
2.从SharedPreferences中读取数据

直接使用SharedPreferences对象的getxxx(键,默认值)方法获取对应类型值


实例:用SharedPreferences实现记住密码功能

1.新建LoginActivity活动
布局:

<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="60dp">
        <TextView
            android:layout_width="90dp"
            android:layout_height="wrap_content"
            android:text="Account:"
            android:textSize="18dp"
            android:layout_gravity="center"/>
        <EditText
            android:id="@+id/account"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"/>
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="60dp">
        <TextView
            android:layout_width="90dp"
            android:layout_height="wrap_content"
            android:text="Password:"
            android:textSize="18dp"
            android:layout_gravity="center_vertical"
            />
        <EditText
            android:id="@+id/password"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:inputType="textPassword"
            android:layout_gravity="center_vertical"/>
    </LinearLayout>
    <CheckBox
        android:id="@+id/remeber"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="remember password"/>
    <Button
        android:id="@+id/login"
        android:layout_gravity="center"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Login"/>

</LinearLayout>

LoginActivity类:

ublic class LoginActivity extends AppCompatActivity {
    private SharedPreferences sharedPreferences;
    private SharedPreferences.Editor editor;
    private EditText account;
    private EditText password;
    private CheckBox isRemeber;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        sharedPreferences= PreferenceManager.getDefaultSharedPreferences(this);

        account=(EditText)findViewById(R.id.account);
        password=(EditText)findViewById(R.id.password);
        isRemeber=(CheckBox)findViewById(R.id.remeber);
        if(sharedPreferences.getBoolean("isRemeber",false)){//之前记住过密码
            account.setText(sharedPreferences.getString("account",""));
            password.setText(sharedPreferences.getString("password",""));
            isRemeber.setChecked(true);
        }
        Button button=(Button)findViewById(R.id.login);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String accountstr=account.getText().toString();
                String passwordstr=password.getText().toString();
                if(accountstr.equals("admin")&&passwordstr.equals("123456")) {
                    editor=sharedPreferences.edit();
                    if (isRemeber.isChecked()) {//选择记住密码
                        editor.putBoolean("isRemeber",true);
                        editor.putString("account", accountstr);//保存账户
                        editor.putString("password", passwordstr);//保存密码
                    }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 invald",Toast.LENGTH_SHORT).show();
                }
            }
        });

    }
}
原文地址:https://www.cnblogs.com/code-fun/p/12879762.html