【Android】一个好用的sharedpreferences存储类方法

其实我也不知道sharedpreferences究竟安全不安全,毕竟是android中最简单的存储机制。

如果你手机root了的话,使用MT管理器到data/data/包名/shared_prefs下就可以找到这个xml文件,而且你可以更改它的内容。

所以一般不推荐使用这种方法来存储一些比较重要的信息(密码、个人信息等等)。

因此该类只是用作演示,后期考虑使用Base64对重要信息进行加密处理。

以下是代码:

package com.paul.notebook.dataBase;

import android.content.Context;
import android.content.SearchRecentSuggestionsProvider;
import android.content.SharedPreferences;

import com.paul.notebook.LoginActivity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * 作者:created by 巴塞罗那的余晖 on 2019/3/10 18:45
 * 邮箱:zhubaoluo@outlook.com
 * 不会写BUG的程序猿不是好程序猿,嘤嘤嘤
 */
public class userData {
    private Map<String,String> root;//用户数据根目录
    private static String flag="user_data";//标识
    private Context mcontext;
    public userData(Context context)
    {
        root=new HashMap<>();
        mcontext=context;
        readData(flag);
    }
    public boolean findExistUsername(String name)//查找是否有该用户名
    {
        return root.containsKey(name);
    }
    public boolean verifyPassword(String name,String password)//验证用户名和密码是否匹配
    {
        if(findExistUsername(name))
        {
            if(root.get(name).equals(password))
            {
                return true;
            }
        }
        return false;
    }
    public boolean getRegister(String name,String password)//注册,并返回是否注册成功
    {
        if(findExistUsername(name))
        {
            return false;
        }
        root.put(name,password);
        saveData(flag);
        return true;
    }
    private void saveData(String key)//保存数据到本地
    {
        //原理:将Map格式转换成json字符串,并指定一个特定标识来记录,Value按照发生器逐一保存就好
        JSONArray mJsonArray = new JSONArray();
        Iterator<Map.Entry<String, String>> iterator = root.entrySet().iterator();
        JSONObject object = new JSONObject();

        while (iterator.hasNext()) {
            Map.Entry<String, String> entry = iterator.next();
            try {
                object.put(entry.getKey(), entry.getValue());
            } catch (JSONException e) {
                //异常处理
                //妈咪妈咪哄!BUG快离开!
            }
        }
        mJsonArray.put(object);
        SharedPreferences sp=mcontext.getSharedPreferences("config",Context.MODE_PRIVATE);
        SharedPreferences.Editor editor=sp.edit();
        editor.putString(key,mJsonArray.toString());
        editor.commit();
    }
     private void readData(String key)//sharedpreferences从本地读取数据
    {
        root.clear();
        SharedPreferences sp=mcontext.getSharedPreferences("config",Context.MODE_PRIVATE);
        String result=sp.getString(key,"");
        try {
            JSONArray array=new JSONArray(result);
            for(int i=0;i<array.length();i++)
            {
                JSONObject itemObject =array.getJSONObject(i);
                JSONArray names=itemObject.names();
                if(names!=null)
                {
                    for(int j=0;j<names.length();j++)
                    {
                        String name=names.getString(j);
                        String value=itemObject.getString(name);
                        root.put(name,value);
                    }
                }
            }
        }catch (JSONException e){
            //异常处理
            //妈咪妈咪哄!BUG快离开!
        }
    }
    private void clearLocalData()//清除本地数据,这个方法一般用不到,故写成私有的
    {
        SharedPreferences preferences = mcontext.getSharedPreferences("config", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();
        editor.clear();
        editor.commit();

    }

}

使用方法

data=new userData(LoginActivity.this);//这里只用传递当前活动,文件名之类的都已经在类体中定义过,可以按需修改

其实如果你不是存储的map类型数据,就不需要这么麻烦了,直接put就完事了。。。

下面给出sharedpreferences的一般用法:

参考这篇文章即可(简书是个好东西)

这里我用SharedPreferences写了一个记事本存储的类,可以做一个大体的参考,功能基本通用。

package com.paul.notebook.dataBase;

import android.content.Context;
import android.content.SharedPreferences;

import com.bumptech.glide.disklrucache.DiskLruCache;

/**
 * 作者:created by 巴塞罗那的余晖 on 2019/3/10 22:20
 * 邮箱:zhubaoluo@outlook.com
 * 不会写BUG的程序猿不是好程序猿,嘤嘤嘤
 */
public class contentData {
    private String content;//记事本内容
    private String title;//记事本标题,作为标识符
    private Context context;//传入的活动
    private String flag;//对应标题的key

    public void setContent(String content) {
        this.content = content;
    }
    public void setTitle(String title)
    {
        this.title=title;
    }
    public void put(String title,String content)
    {
        this.title=title;
        this.content=content;
    }
    public contentData(Context context,String flag)//初始化函数,传入当前活动和key
    {
        this.context=context;
        content="";
        title="";
        this.flag=flag;
    }
    private void save_data()//保存数据到本地
    {
        SharedPreferences sp=context.getSharedPreferences("content_data", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor=sp.edit();
        editor.putString(title,content);//标题对应文章内容
        editor.putString(flag,title);//flag对应标题
        editor.commit();//提交保存
    }
    public boolean readData()
    {
        boolean result=true;
        SharedPreferences sp=context.getSharedPreferences("content_data", Context.MODE_PRIVATE);
        title=sp.getString(flag,"哦吼");//先取出标题,如果没有找到就返回后面的值
        if(title.equals("哦吼"))
        {
           result=false;
        }
        else
        {
            content = sp.getString(title, "");//取出title后再去取对应的内容
            if(content.equals(""))
            {
                result=false;
            }

        }
        return result;

    }

    public boolean saveData()//保证标题和内容都不为空(空也是可以存储的,但是没意义)
    {
        if(title==""||content=="")
            return false;
        save_data();
        return true;
    }


    public String getContent() {
        return content;
    }

    public String getTitle() {
        return title;
    }
}

使用方法,类似于前面的Map

data=new contentData(MainActivity.this,username);//传入当前活动和你要保存的key,保存文件名称是默认的
原文地址:https://www.cnblogs.com/robotpaul/p/10510571.html