Android---SharedPreferences 记住用户名和密码

SharedPreferences是Android提供的一个轻量级存储类,经常用于保存软件设置参数。存放的格式为xml,文件存放在
/data/data/package name/shared_prefs下。

1.主布局文件 activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout     xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" 
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <RelativeLayout
 xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        >
        <TextView 
            android:layout_width="60dp"
            android:gravity="right"
            android:layout_height="wrap_content" 
            android:text="@string/name"
            android:textSize="16sp"
            android:id="@+id/nameLable" />
        <EditText 
            android:layout_width="match_parent"
            android:layout_height="wrap_content" 
            android:layout_toRightOf="@id/nameLable"
            android:layout_alignTop="@id/nameLable"
            android:background="@drawable/edittext_selector"
            android:layout_marginLeft="10px"
            android:id="@+id/name" />
    </RelativeLayout>
    <RelativeLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        >
        <TextView 
            android:layout_width="60dp"
            android:gravity="right"
            android:layout_height="wrap_content" 
            android:textSize="16sp"
            android:text="@string/password"
            android:id="@+id/passwordLable" />
        <EditText 
            android:layout_width="match_parent"
            android:layout_height="wrap_content" 
            android:layout_toRightOf="@id/passwordLable"
            android:layout_alignTop="@id/passwordLable"
            android:background="@drawable/edittext_selector"
            android:password="true"
            android:layout_marginLeft="10px"
            android:id="@+id/password" />
    </RelativeLayout>

    <CheckBox 
        android:id="@+id/check"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="60dp"
        android:text="记住用户名和密码"
        />
    <RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
        <Button 
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" 
            android:text="@string/btn_save"
            android:layout_marginLeft="60dp"
            android:id="@+id/button" />
        <Button 
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" 
            android:text="@string/btn_show"
            android:layout_toRightOf="@id/button"
            android:layout_alignTop="@id/button"
            android:id="@+id/showButton" />
    </RelativeLayout>
    <TextView 
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" 
            android:textSize="20sp"
            android:id="@+id/showText" />
</LinearLayout>

2.edittext_selector.xml文件

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android"> 
    <item android:state_focused="true">
        <shape android:shape="rectangle">
            <corners android:radius="3dp"/>
            <stroke android:width="1dp" android:color="#3196c9"/>
            <padding android:left="10dp"     
            android:top="10dp" 
            android:bottom="10dp" 
            android:right="10dp"/>
        </shape>
    </item>    
    <item android:state_pressed="true">
        <shape android:shape="rectangle">
            <corners android:radius="3dp"/>
            <stroke android:width="1dp" android:color="#3196c9"/>
            <padding android:left="10dp" 
            android:top="10dp" 
            android:bottom="10dp" 
            android:right="10dp"/>
        </shape>
    </item>
    <item>
        <shape android:shape="rectangle">
            <corners android:radius="3dp"/>
            <stroke android:width="1dp" android:color="#a1a1a1"/>
            <padding android:left="10dp" 
            android:top="10dp" 
            android:bottom="10dp" 
            android:right="10dp"/>
        </shape>
    </item>
</selector>

3.资源文件strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">SharedPreferencesTest</string>
    <string name="name">用户名:</string>
    <string name="password">密码:</string>
    <string name="btn_save">保存设置:</string>
    <string name="btn_show">显示:</string>
</resources>

4.MainActivity.xml文件

public class MainActivity extends Activity {

    private EditText et_name;
    private EditText et_password;
    private TextView resultText;
    private CheckBox checkBox;
    private boolean flag;

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

        et_name = (EditText) this.findViewById(R.id.name);
        et_password = (EditText) this.findViewById(R.id.password);
        resultText = (TextView) this.findViewById(R.id.showText);
        checkBox = (CheckBox) findViewById(R.id.check);

        Button button = (Button) this.findViewById(R.id.button);
        Button showButton = (Button) this.findViewById(R.id.showButton);
        button.setOnClickListener(listener);
        showButton.setOnClickListener(listener);

        // 打开软件的时候回显
        SharedPreferences sharedPreferences = getSharedPreferences("ljq123",
                Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE);
        String nameValue = sharedPreferences.getString("name", "");
        int ageValue = sharedPreferences.getInt("age", 1);
        flag = sharedPreferences.getBoolean("checked", false);
        System.out.println("flag:" + flag);
        if (flag) {
            checkBox.setChecked(true);
            et_name.setText(nameValue);
            et_password.setText(String.valueOf(ageValue));
        }

    }

    private View.OnClickListener listener = new View.OnClickListener() {
        public void onClick(View v) {
            Button button = (Button) v;
            // dong文件存放在/data/data/<package name>/shared_prefs目录下
            SharedPreferences sharedPreferences = getSharedPreferences("dong",
                    Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE);
            switch (button.getId()) {
            case R.id.button:
                String name = et_name.getText().toString();
                String password = et_password.getText().toString();

                if (checkBox.isChecked()) {
                    flag = true;
                } else {
                    flag = false;
                }
                if (flag) {
                    Editor editor = sharedPreferences.edit(); // 获取编辑器
                    editor.putString("name", name);
                    editor.putString("password", password);
                    editor.putBoolean("checked", flag);
                    editor.commit();// 提交修改
                    Toast.makeText(MainActivity.this, "保存成功", Toast.LENGTH_LONG)
                            .show();
                }
                break;
            case R.id.showButton:
                String nameValue = sharedPreferences.getString("name", "");
                String passwordValue = sharedPreferences.getString("password",
                        "");
                resultText.setText("姓名:" + nameValue + ",密码:" + passwordValue);
                break;
            }
        }
    };

}

运行截图:
这里写图片描述

访问其它应用中的SharedPreferences文件

新建一个应用AccessSharePreferenceTest,建立一个单元测试testAccessPreference:

在application节点中增加

<uses-library android:name="android.test.runner" />

在application节点外增加

<instrumentation
     android:name="android.test.InstrumentationTestRunner"
     android:targetPackage="com.example.accesssharepreferencetest" >
</instrumentation>

测试类

public class AccessSharePreferenceTest extends AndroidTestCase {

    private static final String TAG = "AccessSharePreferenceTest";

    public void testAccessPreference() throws Exception {
        Context context = this.getContext().createPackageContext(
                "com.example.sharedpreferencestest",
                Context.CONTEXT_IGNORE_SECURITY);
        SharedPreferences sp = context.getSharedPreferences("dong",
                Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE);
        String name = sp.getString("name", "");
        String password = sp.getString("password", "");
        Log.d(TAG, "name:" + name + " password:" + password);
    }
}

运行截图:
这里写图片描述

源码获取

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值