Android 缓存的使用

缓存基础类
import android.content.Context;
import android.content.SharedPreferences;

public class CacheParam {
/**

  • 得到缓存的值*/
    public static boolean getkey(Context context,String key) {
    //context.getSharedPreferences第一个参数文件名,第二个是设置访问权限 私有化 仅限本程序访问
    SharedPreferences sharedPreferences = context.getSharedPreferences("setting", Context.MODE_PRIVATE);
    //第一个参数是key 第二个参数为 找不到key 的时候的默认值
    return sharedPreferences.getBoolean(key, false);
    }
    /**
  • 保存缓存值*/
    public static void setkey(Context context,String key,boolean defaultvalue)
    {
    SharedPreferences sharedPreferences = context.getSharedPreferences("setting", Context.MODE_PRIVATE);
    sharedPreferences.edit().putBoolean(key,defaultvalue).commit();
    }
    public static void setkeyforstring(Context context,String key,String string)
    {
    SharedPreferences sharedPreferences = context.getSharedPreferences("setting", Context.MODE_PRIVATE);
    sharedPreferences.edit().putString(key,string).commit();

    }
    public static String getkeyforstring(Context context,String key) {
    //context.getSharedPreferences第一个参数文件名,第二个是设置访问权限 私有化 仅限本程序访问
    SharedPreferences sharedPreferences = context.getSharedPreferences("setting", Context.MODE_PRIVATE);
    //第一个参数是key 第二个参数为 找不到key 的时候的默认值
    return sharedPreferences.getString(key, "");
    }
    public static void clear(Context context) {
    SharedPreferences preferences = context.getSharedPreferences("setting", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = preferences.edit();
    editor.clear();

     editor.commit();

    }

}

基础类的调用
void getckpwd() {
if (checkBox.isChecked()) {
String struser = etname.getText().toString();
String strpwd = etpwd.getText().toString();
CacheParam.setkeyforstring(LogInActivity.this, "ischeck", "1");
CacheParam.setkeyforstring(LogInActivity.this, "username", struser);
CacheParam.setkeyforstring(LogInActivity.this, "userpwd", strpwd);
// Toast.makeText(getApplicationContext(), "1", Toast.LENGTH_SHORT).show();
} else {
CacheParam.clear(LogInActivity.this);
// Toast.makeText(getApplicationContext(), "0", Toast.LENGTH_SHORT).show();
}
}

String GetUser, GetPwd, GetCheck;
GetCheck = CacheParam.getkeyforstring(LogInActivity.this, "ischeck");
GetUser = CacheParam.getkeyforstring(LogInActivity.this, "username");
GetPwd = CacheParam.getkeyforstring(LogInActivity.this, "userpwd");

    //java中判断字符串是否相同 不能用==
    if (GetCheck.equals("1")) {
        checkBox.setChecked(true);
        if (GetUser != "") {
            etname.setText(GetUser);
        }
        if (GetPwd != "") {
            etpwd.setText(GetPwd);
        }
    } else {
        checkBox.setChecked(false);
    }

Android 缓存的使用

上一篇:Calendar API


下一篇:C#之扩展方法