小工具知识网

当前位置: 首页 > 行业知识 > Android学习--SharedPreferences存储

行业知识

Android学习--SharedPreferences存储

2026-11-08 11:55:43 来源:互联网转载

SharedPreferences是Android平台上一个轻量级的存储类,当程序中有一些少量数据需要持久化存储时,可以使用SharedPreferences进行存储。

一、SharedPreferences的数据操作

1、将数据存入SharedPreferences中

使用SharedPreferences存储数据时,首先需要调用getSharedPreferences()方法获取SharedPreferences的实例对象。由于该对象本身只能获取数据,不能对数据进行存储和修改,所以需要调用SharedPreferences的edit()方法获取到可编辑的Editor对象,最后通过Editor对象的putXxx()方法存储数据,示例代码如下:

//获取sp对象,参数“data”表示文件名,MODE_PRIVATE表示文件操作模式SharedPreferences sp=getSharedPreferences("data",MODE_PRIVATE);    SharedPreferences.Editor editor=sp.edit();    editor.putString("name","张三");    editor.putInt("age",8);    editor.commit();

由上述代码可知,Editor对象是以键值对的形式保存数据的,value的值只能是Float、Int、Long、Boolean、String和Set类型。同时,需注意,操作完数据后,一定要调用commit()方法进行数据提交,否则所有操作不生效。

2、读取SharedPreferences中的数据

读取SharedPreferences中的数据十分简单,只需要获取到SharedPreferences对象,然后通过该对象的getXxx()方法获取到相应的key即可,示例代码如下:

SharedPreferences sp = getSharedPreferences("data",MODE_PRIVATE)String data = sp.getString("name","");//获取用户名

注意,getXxx()方法的第二个参数为缺省值,如果sp对象中不存在该key,则将返回缺省值,也就是说在上述例子中,如果“name”不存在,则会返回空字符串。

3、删除SharedPreferences中的数据

如果需要删除SharedPreferences中的数据,则只需要调用Editor对象的remove(String key)方法或者clear()方法即可,示例代码如下:

editor.remove("name");editor.clear();

二、实战演练

在Android APP的登录界面中,当用户登录成功时,保存用户名和密码到Shared Preferences中。下一次显示登录界面时,将用户名密码读取到相应的输入框中,避免用户的再次输入。

1、程序源码

SPsave.java(工具类)

public class SPsave {    //保存账号密码到data.xml中    public static boolean saveUserInfo(Context context, String accout, String password){        SharedPreferences sp=context.getSharedPreferences("data",Context.MODE_PRIVATE);        SharedPreferences.Editor edit= sp.edit();        edit.putString("userName",accout);        edit.putString("pwd",password);        edit.commit();        return true;    }    //从data.xml文件中获取存储的QQ账号与密码    public static String[] getUserInfo(Context context){        SharedPreferences sp=context.getSharedPreferences("data",Context.MODE_PRIVATE);        String account= sp.getString("userName",null);        String password= sp.getString("pwd",null);        String []userMap=new String[]{account,password};        return userMap;    }}

MainActivity.java

public class MainActivity extends AppCompatActivity {    private Button btnLogin;    private EditText account;    private EditText password;    private TextView result;    String [] userInfo;    String sAccount;    String sPassword;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.layout);        init();    }    //初始化函数    private void init(){        btnLogin=findViewById(R.id.button);        account=findViewById(R.id.editTextText);        password=findViewById(R.id.editTextTextPassword);        result=findViewById(R.id.tv_result);        //获取SP中的信息        userInfo=SPsave.getUserInfo(this);        //如果SP中有值,则填入SP中存储的值        if(userInfo[0]!=null){            account.setText(userInfo[0]);            password.setText(userInfo[1]);        }        //按钮绑定事件        btnLogin.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View view) {                //获取文本框中的值                sAccount=account.getText().toString();                sPassword=password.getText().toString();               //判断账号、密码是否正确,不可用==判读                if(sAccount.equals("tom") && sPassword.equals("123")){                  result.setText("登录成功!");               }else {                   result.setText("账号或密码错误。。。");               }               //将输入的值存入SP               SPsave.saveUserInfo(MainActivity.this,sAccount,sPassword);            }        });    }}

layout.xml(布局文件)

注意需要在res文件夹下创建drawable-hdpi文件夹存入对应的图片。

                                                            
2、运行结果

        (第一次进入主页)                    (登录成功)                        (再次进入首页)

上一篇:逆水寒账号怎么删除服务器?

下一篇:揭秘高清视频下载秘籍,无特效也能轻松获取!