import java.util.HashMap;
import java.util.Map;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.text.TextUtils;
public class UtilsOfShared {
/**
* 用SharedPreferences保存用户信息
*/
public static boolean saveUserInfo(Context context,String number,String password){
/**
* SharedPreferences:
* 创建/data/data/包名/shared_prefs/info.xml,
* 即使你自己定义了文件类型,创建的结果仍然是xml文件,
* 例如你要创建info.txt,实际创建的结果是info.txt.xml
*/
try {
SharedPreferences sp=context.getSharedPreferences("info", Context.MODE_PRIVATE);
//获取一个编辑器
Editor editor=sp.edit();
//用编辑器将number和password放入info.xml中
editor.putString("number", number);
editor.putString("password", password);
//至此,编辑器真正提交数据
editor.commit();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 用SharedPreferences获取用户信息
*/
public static Map<String,String> getUserInfo(Context context){
//创建一个SharedPreferences
SharedPreferences sp=context.getSharedPreferences("info", Context.MODE_PRIVATE);
//从sp中获取number和password
String number=sp.getString("number", null);
String password=sp.getString("password", null);
//判断number,password是否为null
if(!TextUtils.isEmpty(number)&&!TextUtils.isEmpty(password)){
Map<String ,String> map=new HashMap<String, String>();
map.put("number", number);
map.put("password", password);
return map;
}
return null;
}
}