Android 开发入门篇 互动版

创建SharedHelper类:

public class SharedHelper {
    private Context mContext;
    public SharedHelper() {}
    public SharedHelper(Context mContext) {
        this.mContext = mContext;
    }
    //定义一个保存数据的方法 
    public void save(String username, String passwd) {
        SharedPreferences sp = mContext.getSharedPreferences("mysp", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putString("username", username);
        editor.putString("passwd", passwd);
        editor.commit();
        Toast.makeText(mContext, "信息已写入SharedPreference中", Toast.LENGTH_SHORT).show();
    }
    //定义一个读取SP文件的方法
    public Map<String, String> read() {
        Map<String, String> data = new HashMap<String, String>();
        SharedPreferences sp = mContext.getSharedPreferences("mysp", Context.MODE_PRIVATE);
        data.put("username", sp.getString("username", ""));
        data.put("passwd", sp.getString("passwd", ""));
        return data;
    }
}

使用该类也很简单:

SharedHelper sh ;
//存储
sh.save(name , pass);
//读取
Map<String,String> data = sh.read();
data.get("username");
data.get("passwd");
用该类实现保存/读取用户登陆信息。源码下载地址:https://github.com/hubwiz/android-rudiments