使用键值对进行本地存储(分类存储、获取)

来源:互联网 发布:数据脱敏 英文 编辑:程序博客网 时间:2024/05/18 03:27

做法:

activity_two.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical">    <EditText        android:id="@+id/ed_name1"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:hint="请输入账号" />    <EditText        android:id="@+id/ed_pass1"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:hint="请输入密码" />    <CheckBox        android:id="@+id/ed_cba"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="记住账号和密码"/>    <Button        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:onClick="login1"        android:text="登陆"/></LinearLayout>
ThreeActivity

package com.liyulei.memoryread;import android.content.SharedPreferences;import android.os.Bundle;import android.support.v7.app.AppCompatActivity;import android.view.View;import android.widget.CheckBox;import android.widget.EditText;import android.widget.Toast;public class ThreeActivity extends AppCompatActivity {    EditText ed_name1,ed_pass1;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_two);    }    //外存卡存储信息    public void login1(View view ) {        //拿到输入框的内容        EditText ed_name1 = (EditText) findViewById(R.id.ed_name1);        EditText ed_pass1 = (EditText) findViewById(R.id.ed_pass1);        String name1 = ed_name1.getText().toString();        String pass1 = ed_pass1.getText().toString();        //判断checkbox是否选中        CheckBox ed_cba = (CheckBox) findViewById(R.id.ed_cba);        if (ed_cba.isChecked()) {           //获取一个sharepreserce            SharedPreferences sp = getSharedPreferences("info",MODE_PRIVATE);            //获取编辑器            SharedPreferences.Editor ed = sp.edit();            ed.putString("name1",name1);            ed.putString("pass1",pass1);            //提交            ed.commit();            }            Toast toast = Toast.makeText(this, "登陆成功", Toast.LENGTH_LONG);            toast.show();        }    //外存卡读取信息    public void Account() {        //获取sharePrefence        SharedPreferences sharedPreferences = getSharedPreferences("info",MODE_PRIVATE);        String name = sharedPreferences.getString("name1"," ");        String pass = sharedPreferences.getString("pass1"," ");        ed_name1.setText(name);        ed_pass1.setText(pass);    }}


0 0