android中SharedPreferences的使用

1.使用需知

SharedPreferences是Android平台上一个轻量级的存储类,用来保存应用的一些常用配置。
最终以xml方式来保存,整体效率来看不是特别的高,适用于存储信息量不大的数据。


2.操作模式

SharedPreferences数据有以下四种操作模式

  • Context.MODE_PRIVATE
  • Context.MODE_APPEND
  • Context.MODE_WORLD_READABLE
  • Context.MODE_WORLD_WRITEABLE

Context.MODE_PRIVATE:为默认操作模式,代表该文件是私有数据,只能被应用本身访问,在该模式下,写入的内容会覆盖原文件的内容;
Context.MODE_APPEND:模式会检查文件是否存在,存在就往文件追加内容,否则就创建新文件;
Context.MODE_WORLD_READABLE和Context.MODE_WORLD_WRITEABLE用来控制其他应用是否有权限读写该文件.;
MODE_WORLD_READABLE:表示当前文件可以被其他应用读取;
MODE_WORLD_WRITEABLE:表示当前文件可以被其他应用写入。


3.具体用法

SharedPreferences 可以用来进行数据的共享,包括应用程序之间,或者同一个应用程序中的不同组件。比如两个activity除了通过Intent传递数据之外,也可以通过ShreadPreferences来共享数据。
存:
SharedPreferences sharedata=getSharedPreferences(“data”, Context.MODE_PRIVATE);
Editor edit=sharedata .edit();
edit.putString(“item”,”hello getSharedPreferences”);
edit.commit();
取:
SharedPreferences sharedata = getSharedPreferences(“data”, 0);
String data = sharedata.getString(“item”, null);


4.代码

(这里一个保存用户名和密码的小案例来进行展示)

  • java代码:
import android.app.Activity;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

public class MySharedPreference extends Activity {

    EditText et_user,et_password;
    CheckBox check;
    SharedPreferences sharedPreferences;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //初始化UI
        initUI();
        //根据SharedPreferences保存的内容,自动添加信息
        autoAddInformation();
    }


    private void initUI() {
        et_user=(EditText) findViewById(R.id.user);
        et_password=(EditText) findViewById(R.id.password);
        check=(CheckBox) findViewById(R.id.check);
    }

    private void autoAddInformation() {
        sharedPreferences=getSharedPreferences("info", MODE_PRIVATE);

        //getString()第二个参数为缺省值,如果preference中不存在该key,将返回缺省值
        et_user.setText(sharedPreferences.getString("user", ""));
        et_password.setText(sharedPreferences.getString("password", ""));
    }

    //相应“登录”的点击事件
    public void login(View v){
        if(check.isChecked()){
            //获取sharedPreferences对象,并为其设置文件名及类型
            sharedPreferences=getSharedPreferences("info", MODE_PRIVATE);
            //拿到sharedPreferences的编辑器
            Editor editor=sharedPreferences.edit();
            editor.putString("user", et_user.getText().toString());
            editor.putString("password", et_password.getText().toString());
            //提交内容
            editor.commit();
            Toast.makeText(getBaseContext(), "信息保存成功", 0).show();
        }else{
            Toast.makeText(getBaseContext(), "本次未勾选'记住用户名和密码'", 0).show();
        }

    }
}
  • 布局文件:
<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.person.maomao.MySharedPreference"
    android:background="#3333FF" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="24dp"
        android:text="Login"
        android:textSize="45sp" />

    <EditText
        android:id="@+id/user"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/password"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="38dp"
        android:ems="10"
        android:hint="请输入用户名"
        android:inputType="textPersonName"
        android:singleLine="true" />

    <EditText
        android:id="@+id/password"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/user"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="25dp"
        android:ems="10"
        android:hint="请输入密码"
        android:inputType="textPassword"
        android:singleLine="true" >

        <requestFocus />
    </EditText>

    <CheckBox
        android:id="@+id/check"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/user"
        android:layout_below="@+id/password"
        android:layout_marginTop="24dp"
        android:text="记住用户名和密码"
        android:textColor="#938192" />

     <Button
        android:id="@+id/button1"
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:layout_below="@+id/check"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="25dp"
        android:text="登录" 
        android:onClick="login"/>


</RelativeLayout>
  • AndroidManifest.xml:
<activity
            android:name=".MySharedPreference"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

5.结果

输入用户名和密码,点击登录按钮,界面如下

这里写图片描述

返回至主菜单,重新进入后结果如下

这里写图片描述


6.备注

有问题的地方还请各位多多包含,不吝赐教。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值