package com.xt.deeptest5g.Utils;import android.content.Context;
import android.content.SharedPreferences;/*** author : ZJS* e-mail : * date : 20-7-30下午7:46* desc : 用户账户信息保存工具类* version : 1.0*/
public class SharedPreferencesUtils {/*** 保存在手机里面的文件名*/private static final String FILE_NAME = "share_date";/*** 保存数据的方法,我们需要拿到保存数据的具体类型,然后根据类型调用不同的保存方法** @param context* @param key* @param object*/public static void setParam(Context context, String key, Object object) {String type = object.getClass().getSimpleName();SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);SharedPreferences.Editor edit = sp.edit();if ("String".equals(type)) {edit.putString(key, ((String) object));}if ("Integer".equals(type)) {edit.putInt(key, ((Integer) object));}if ("Boolean".equals(type)) {edit.putBoolean(key, ((Boolean) object));}if ("Float".equals(type)) {edit.putFloat(key, ((Float) object));}if ("Long".equals(type)) {edit.putLong(key, ((Long) object));}edit.commit();}/*** 得到保存数据的方法,我们根据默认值得到保存的数据的具体类型,然后调用相对于的方法获取值** @param context* @param key* @param defaultObject* @return*/public static Object getParam(Context context, String key, Object defaultObject) {String type = defaultObject.getClass().getSimpleName();SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);if ("String".equals(type)) {return sp.getString(key, ((String) defaultObject));}if ("Integer".equals(type)) {return sp.getInt(key, (Integer) defaultObject);}if ("Boolean".equals(type)) {return sp.getBoolean(key, (Boolean) defaultObject);}if ("Float".equals(type)) {return sp.getFloat(key, (Float) defaultObject);}if ("Long".equals(type)) {return sp.getLong(key, (Long) defaultObject);}return null;}/*** 清除所有数据** @param context*/public static void clear(Context context) {SharedPreferences sp = context.getSharedPreferences(FILE_NAME,Context.MODE_PRIVATE);SharedPreferences.Editor editor = sp.edit();editor.clear().commit();}/*** 清除指定数据** @param context*/public static void clearAll(Context context, String key) {SharedPreferences sp = context.getSharedPreferences(FILE_NAME,Context.MODE_PRIVATE);SharedPreferences.Editor editor = sp.edit();editor.remove(key);editor.commit();}
}
登录Activity:包含两个editext,一个button:
调用:
case R.id.btn_login:phone = etPhone.getText().toString();pass = etPass.getText().toString();SharedPreferencesUtils.setParam(this, "phone", phone);SharedPreferencesUtils.setParam(this, "pass", pass);startActivity(new Intent(this, MainActivity.class));break;
mainActivity:
显示
public void initDate() {String phone1 = (String) SharedPreferencesUtils.getParam(this, "phone", "15564770");String pass1 = (String) SharedPreferencesUtils.getParam(this, "pass", "123456");phone.setText(phone1);pass.setText(pass1);}
没有问题!